diff --git a/pom.xml b/pom.xml index f6f4671362a..0c3b0f978c0 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 b73140f986a..9436695e479 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 { private final Map rabbitTemplates; - public RabbitHealthIndicatorAutoConfiguration( - Map rabbitTemplates) { + public RabbitHealthIndicatorAutoConfiguration(Map rabbitTemplates) { this.rabbitTemplates = 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 af6a3bef06a..5991adf4cb4 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 @@ -44,8 +44,7 @@ public class AuditAutoConfiguration { private final AuditEventRepository auditEventRepository; - public AuditAutoConfiguration( - ObjectProvider auditEventRepository) { + public AuditAutoConfiguration(ObjectProvider auditEventRepository) { this.auditEventRepository = auditEventRepository.getIfAvailable(); } @@ -56,16 +55,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 123bd4952d8..09f9933a3e6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 AuditEventsEndpointAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnBean(AuditEventRepository.class) @ConditionalOnEnabledEndpoint - 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 bbe1aa0d5d3..689d49eff88 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 BeansEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint - 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/cassandra/CassandraHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfiguration.java index fcb71265d3b..e7bf25472cc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +49,13 @@ import org.springframework.data.cassandra.core.CassandraOperations; @ConditionalOnBean(CassandraOperations.class) @ConditionalOnEnabledHealthIndicator("cassandra") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) -@AutoConfigureAfter({ CassandraAutoConfiguration.class, - CassandraDataAutoConfiguration.class }) -public class CassandraHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +@AutoConfigureAfter({ CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class }) +public class CassandraHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map cassandraOperations; - public CassandraHealthIndicatorAutoConfiguration( - Map cassandraOperations) { + public CassandraHealthIndicatorAutoConfiguration(Map cassandraOperations) { this.cassandraOperations = 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 6ddb856e25e..8a68261cdd6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +50,16 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { * @param filters filters to apply */ public CloudFoundryWebEndpointDiscoverer(ApplicationContext applicationContext, - ParameterValueMapper parameterValueMapper, - EndpointMediaTypes endpointMediaTypes, PathMapper endpointPathMapper, - Collection invokerAdvisors, + ParameterValueMapper parameterValueMapper, EndpointMediaTypes endpointMediaTypes, + PathMapper endpointPathMapper, Collection invokerAdvisors, Collection> filters) { - super(applicationContext, parameterValueMapper, endpointMediaTypes, - endpointPathMapper, invokerAdvisors, filters); + super(applicationContext, parameterValueMapper, endpointMediaTypes, endpointPathMapper, 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,16 +67,14 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { } private boolean isHealthEndpointExtension(Object extensionBean) { - AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(extensionBean.getClass(), - EndpointWebExtension.class); + AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(extensionBean.getClass(), + EndpointWebExtension.class); Class endpoint = (attributes != null) ? attributes.getClass("endpoint") : null; return (endpoint != null && HealthEndpoint.class.isAssignableFrom(endpoint)); } private boolean isCloudFoundryHealthEndpointExtension(Object extensionBean) { - return AnnotatedElementUtils.hasAnnotation(extensionBean.getClass(), - HealthEndpointCloudFoundryExtension.class); + return AnnotatedElementUtils.hasAnnotation(extensionBean.getClass(), HealthEndpointCloudFoundryExtension.class); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/HealthEndpointCloudFoundryExtension.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/HealthEndpointCloudFoundryExtension.java index fbd65f5ec6b..5735d0f326b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/HealthEndpointCloudFoundryExtension.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/HealthEndpointCloudFoundryExtension.java @@ -35,8 +35,7 @@ import org.springframework.boot.actuate.health.HealthEndpoint; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented -@EndpointExtension(filter = CloudFoundryEndpointFilter.class, - endpoint = HealthEndpoint.class) +@EndpointExtension(filter = CloudFoundryEndpointFilter.class, endpoint = HealthEndpoint.class) public @interface HealthEndpointCloudFoundryExtension { } 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 b15c83333ab..7f2ef0904ae 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 1438147cacb..2c600721e03 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 Madhura Bhave * @author Phillip Webb */ -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,40 +66,32 @@ 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 @ResponseBody protected Publisher> links(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); - return this.securityInterceptor.preHandle(exchange, "") - .map((securityResponse) -> { - if (!securityResponse.getStatus().equals(HttpStatus.OK)) { - return new ResponseEntity<>(securityResponse.getStatus()); - } - AccessLevel accessLevel = exchange - .getAttribute(AccessLevel.REQUEST_ATTRIBUTE); - Map links = this.linksResolver - .resolveLinks(request.getURI().toString()); - return new ResponseEntity<>( - Collections.singletonMap("_links", - getAccessibleLinks(accessLevel, links)), - HttpStatus.OK); - }); + return this.securityInterceptor.preHandle(exchange, "").map((securityResponse) -> { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { + return new ResponseEntity<>(securityResponse.getStatus()); + } + AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + Map links = this.linksResolver.resolveLinks(request.getURI().toString()); + return new ResponseEntity<>(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)); } @@ -116,8 +106,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; @@ -125,16 +114,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 d1b6b31f2e9..5ea0d5a97af 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 @@ -67,8 +67,7 @@ import org.springframework.web.server.WebFilter; * @since 2.0.0 */ @Configuration -@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true) @AutoConfigureAfter(HealthEndpointAutoConfiguration.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) @@ -86,58 +85,51 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { @ConditionalOnBean({ HealthEndpoint.class, ReactiveHealthEndpointWebExtension.class }) public CloudFoundryReactiveHealthEndpointWebExtension cloudFoundryReactiveHealthEndpointWebExtension( ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension) { - return new CloudFoundryReactiveHealthEndpointWebExtension( - reactiveHealthEndpointWebExtension); + return new CloudFoundryReactiveHealthEndpointWebExtension(reactiveHealthEndpointWebExtension); } @Bean public CloudFoundryWebFluxEndpointHandlerMapping cloudFoundryWebFluxEndpointHandlerMapping( ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes, - WebClient.Builder webClientBuilder, - ControllerEndpointsSupplier controllerEndpointsSupplier) { + WebClient.Builder webClientBuilder, ControllerEndpointsSupplier controllerEndpointsSupplier) { CloudFoundryWebEndpointDiscoverer endpointDiscoverer = new CloudFoundryWebEndpointDiscoverer( - this.applicationContext, parameterMapper, endpointMediaTypes, - PathMapper.useEndpointId(), Collections.emptyList(), - Collections.emptyList()); - CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor( - webClientBuilder, this.applicationContext.getEnvironment()); + this.applicationContext, parameterMapper, endpointMediaTypes, PathMapper.useEndpointId(), + Collections.emptyList(), Collections.emptyList()); + CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor(webClientBuilder, + this.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; } @@ -155,8 +147,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); } @@ -170,10 +161,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 62df0709797..0fa64aecb25 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. @@ -52,8 +52,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) { @@ -64,9 +64,8 @@ class ReactiveCloudFoundrySecurityService { } protected ReactorClientHttpConnector buildTrustAllSslConnector() { - return new ReactorClientHttpConnector((options) -> options.sslSupport( - (sslContextBuilder) -> sslContextBuilder.sslProvider(SslProvider.JDK) - .trustManager(InsecureTrustManagerFactory.INSTANCE))); + return new ReactorClientHttpConnector((options) -> options.sslSupport((sslContextBuilder) -> sslContextBuilder + .sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE))); } /** @@ -79,26 +78,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) { @@ -122,9 +116,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) { @@ -141,11 +134,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 f9532a615a7..d3428069e08 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 @@ -68,10 +68,8 @@ import org.springframework.web.servlet.DispatcherServlet; * @since 2.0.0 */ @Configuration -@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", - matchIfMissing = true) -@AutoConfigureAfter({ ServletManagementContextAutoConfiguration.class, - HealthEndpointAutoConfiguration.class }) +@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true) +@AutoConfigureAfter({ ServletManagementContextAutoConfiguration.class, HealthEndpointAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @ConditionalOnBean(DispatcherServlet.class) @@ -96,52 +94,46 @@ public class CloudFoundryActuatorAutoConfiguration { @Bean public CloudFoundryWebEndpointServletHandlerMapping cloudFoundryWebEndpointServletHandlerMapping( ParameterValueMapper parameterMapper, EndpointMediaTypes endpointMediaTypes, - RestTemplateBuilder restTemplateBuilder, - ServletEndpointsSupplier servletEndpointsSupplier, + RestTemplateBuilder restTemplateBuilder, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier) { - CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer( - this.applicationContext, parameterMapper, endpointMediaTypes, - PathMapper.useEndpointId(), Collections.emptyList(), + CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer(this.applicationContext, + parameterMapper, endpointMediaTypes, PathMapper.useEndpointId(), Collections.emptyList(), Collections.emptyList()); - CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor( - restTemplateBuilder, this.applicationContext.getEnvironment()); + CloudFoundrySecurityInterceptor securityInterceptor = getSecurityInterceptor(restTemplateBuilder, + this.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; } @@ -153,13 +145,11 @@ public class CloudFoundryActuatorAutoConfiguration { @ConditionalOnClass(WebSecurity.class) @Order(SecurityProperties.IGNORED_ORDER) @Configuration - 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 47233f35c10..337c9cbfed8 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. @@ -48,17 +48,15 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMappi * @author Madhura Bhave * @author Phillip Webb */ -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; @@ -66,41 +64,33 @@ 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 @ResponseBody - protected Map> links(HttpServletRequest request, - HttpServletResponse response) { - SecurityResponse securityResponse = this.securityInterceptor.preHandle(request, - null); + protected Map> links(HttpServletRequest request, HttpServletResponse response) { + SecurityResponse securityResponse = this.securityInterceptor.preHandle(request, null); if (!securityResponse.getStatus().equals(HttpStatus.OK)) { sendFailureResponse(response, securityResponse); } - AccessLevel accessLevel = (AccessLevel) request - .getAttribute(AccessLevel.REQUEST_ATTRIBUTE); - Map links = this.linksResolver - .resolveLinks(request.getRequestURL().toString()); + AccessLevel accessLevel = (AccessLevel) request.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + Map links = this.linksResolver.resolveLinks(request.getRequestURL().toString()); Map filteredLinks = new LinkedHashMap<>(); if (accessLevel == null) { return Collections.singletonMap("_links", filteredLinks); } 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); } - 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) { this.logger.debug("Failed to send error response", ex); @@ -118,8 +108,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; @@ -128,11 +117,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 8569f7203e3..4cbaeba9d82 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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"); } } @@ -105,8 +103,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", ""); @@ -118,8 +115,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 a89484e77c3..51adb2b521a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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,27 +114,24 @@ 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( - (source, conditionAndOutcomes) -> add(source, conditionAndOutcomes)); - this.parentId = (context.getParent() != null) ? context.getParent().getId() - : null; + report.getConditionAndOutcomesBySource() + .forEach((source, conditionAndOutcomes) -> add(source, conditionAndOutcomes)); + 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)); } } @@ -175,8 +169,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 c5c343af3f0..b1b2c6500b4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ConditionsReportEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) @ConditionalOnEnabledEndpoint - 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/elasticsearch/ElasticsearchHealthIndicatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfiguration.java index fdf09099663..85810481949 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ElasticsearchHealthIndicatorAutoConfiguration { @ConditionalOnClass(Client.class) @ConditionalOnBean(Client.class) @EnableConfigurationProperties(ElasticsearchHealthIndicatorProperties.class) - static class ElasticsearchClientHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + static class ElasticsearchClientHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map clients; @@ -82,8 +82,7 @@ public class ElasticsearchHealthIndicatorAutoConfiguration { protected ElasticsearchHealthIndicator createHealthIndicator(Client client) { Duration responseTimeout = this.properties.getResponseTimeout(); return new ElasticsearchHealthIndicator(client, - (responseTimeout != null) ? responseTimeout.toMillis() : 100, - this.properties.getIndices()); + (responseTimeout != null) ? responseTimeout.toMillis() : 100, this.properties.getIndices()); } } @@ -91,8 +90,8 @@ public class ElasticsearchHealthIndicatorAutoConfiguration { @Configuration @ConditionalOnClass(JestClient.class) @ConditionalOnBean(JestClient.class) - static class ElasticsearchJestHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { + static class ElasticsearchJestHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map clients; @@ -107,8 +106,7 @@ public class ElasticsearchHealthIndicatorAutoConfiguration { } @Override - protected ElasticsearchJestHealthIndicator createHealthIndicator( - JestClient client) { + protected ElasticsearchJestHealthIndicator createHealthIndicator(JestClient client) { return new ElasticsearchJestHealthIndicator(client); } 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 c1944cb6320..23394bb8688 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 @@ -30,8 +30,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * @author Andy Wilkinson * @since 2.0.0 */ -@ConfigurationProperties(prefix = "management.health.elasticsearch", - ignoreUnknownFields = false) +@ConfigurationProperties(prefix = "management.health.elasticsearch", ignoreUnknownFields = false) public class ElasticsearchHealthIndicatorProperties { /** 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 b76736536ca..c278b318776 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 3b490285422..6b88e84ec26 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. @@ -42,8 +42,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; @@ -53,8 +52,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"); @@ -65,9 +64,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); @@ -76,8 +74,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) { @@ -85,8 +82,7 @@ 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) { @@ -107,8 +103,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/OnEnabledEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnEnabledEndpointCondition.java index ff4b7f17919..c76e8fcbb23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 OnEnabledEndpointCondition extends SpringBootCondition { private static final ConcurrentReferenceHashMap> enabledByDefaultCache = new ConcurrentReferenceHashMap<>(); @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); AnnotationAttributes attributes = getEndpointAttributes(context, metadata); EndpointId id = EndpointId.of(attributes.getString("id")); @@ -61,46 +60,37 @@ class OnEnabledEndpointCondition extends SpringBootCondition { if (userDefinedEnabled != null) { return new ConditionOutcome(userDefinedEnabled, ConditionMessage.forCondition(ConditionalOnEnabledEndpoint.class) - .because("found property " + key + " with value " - + userDefinedEnabled)); + .because("found property " + key + " with value " + userDefinedEnabled)); } Boolean userDefinedDefault = isEnabledByDefault(environment); if (userDefinedDefault != null) { return new ConditionOutcome(userDefinedDefault, - ConditionMessage.forCondition(ConditionalOnEnabledEndpoint.class) - .because("no property " + key - + " found so using user defined default from " - + ENABLED_BY_DEFAULT_KEY)); + ConditionMessage.forCondition(ConditionalOnEnabledEndpoint.class).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(ConditionalOnEnabledEndpoint.class).because( - "no property " + key + " found so using endpoint default")); + return new ConditionOutcome(endpointDefault, ConditionMessage.forCondition(ConditionalOnEnabledEndpoint.class) + .because("no property " + key + " found so using endpoint default")); } 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); } - private AnnotationAttributes getEndpointAttributes(ConditionContext context, - AnnotatedTypeMetadata metadata) { - Assert.state( - metadata instanceof MethodMetadata - && metadata.isAnnotated(Bean.class.getName()), + private AnnotationAttributes getEndpointAttributes(ConditionContext context, AnnotatedTypeMetadata metadata) { + Assert.state(metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName()), "OnEnabledEndpointCondition may only be used on @Bean methods"); Class endpointType = getEndpointType(context, (MethodMetadata) metadata); return getEndpointAttributes(endpointType); } private Class getEndpointType(ConditionContext context, MethodMetadata metadata) { - Map attributes = metadata - .getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName()); + Map attributes = metadata.getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName()); if (attributes != null && attributes.containsKey("endpoint")) { Class target = (Class) attributes.get("endpoint"); if (target != Void.class) { @@ -109,27 +99,23 @@ class OnEnabledEndpointCondition extends SpringBootCondition { } // We should be safe to load at this point since we are in the REGISTER_BEAN phase try { - return ClassUtils.forName(metadata.getReturnTypeName(), - context.getClassLoader()); + return ClassUtils.forName(metadata.getReturnTypeName(), context.getClassLoader()); } catch (Throwable ex) { - throw new IllegalStateException("Failed to extract endpoint id for " - + metadata.getDeclaringClassName() + "." + metadata.getMethodName(), - ex); + throw new IllegalStateException("Failed to extract endpoint id for " + metadata.getDeclaringClassName() + + "." + metadata.getMethodName(), ex); } } protected AnnotationAttributes getEndpointAttributes(Class type) { - AnnotationAttributes attributes = AnnotatedElementUtils - .findMergedAnnotationAttributes(type, Endpoint.class, true, true); + AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(type, Endpoint.class, + true, true); if (attributes != null) { return attributes; } - attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(type, - EndpointExtension.class, false, true); - Assert.state(attributes != null, - "No endpoint is specified and the return type of the @Bean method is " - + "neither an @Endpoint, nor an @EndpointExtension"); + attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(type, EndpointExtension.class, false, true); + Assert.state(attributes != null, "No endpoint is specified and the return type of the @Bean method is " + + "neither an @Endpoint, nor an @EndpointExtension"); return getEndpointAttributes(attributes.getClass("endpoint")); } 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 c69ff053da9..d424ba5729b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { private final String contextId; - DefaultEndpointObjectNameFactory(JmxEndpointProperties properties, - MBeanServer mBeanServer, String contextId) { + DefaultEndpointObjectNameFactory(JmxEndpointProperties properties, MBeanServer mBeanServer, String contextId) { this.properties = properties; this.mBeanServer = mBeanServer; this.contextId = contextId; } @Override - public ObjectName getObjectName(ExposableJmxEndpoint endpoint) - throws MalformedObjectNameException { + public ObjectName getObjectName(ExposableJmxEndpoint endpoint) throws MalformedObjectNameException { StringBuilder builder = new StringBuilder(this.properties.getDomain()); builder.append(":type=Endpoint"); - builder.append( - ",name=" + StringUtils.capitalize(endpoint.getEndpointId().toString())); + builder.append(",name=" + StringUtils.capitalize(endpoint.getEndpointId().toString())); String baseName = builder.toString(); if (this.mBeanServer != null && hasMBean(baseName)) { builder.append(",context=" + this.contextId); @@ -76,8 +73,7 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { return ""; } StringBuilder builder = new StringBuilder(); - this.properties.getStaticNames() - .forEach((name, value) -> builder.append("," + name + "=" + value)); + this.properties.getStaticNames().forEach((name, value) -> builder.append("," + name + "=" + 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 9ced284a7fb..e382b54679c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +64,27 @@ 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, - invokerAdvisors.getIfAvailable(Collections::emptyList), - filters.getIfAvailable(Collections::emptyList)); + invokerAdvisors.getIfAvailable(Collections::emptyList), filters.getIfAvailable(Collections::emptyList)); } @Bean @ConditionalOnSingleCandidate(MBeanServer.class) - public JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, - ObjectProvider objectMapper, + public JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, ObjectProvider objectMapper, JmxEndpointsSupplier jmxEndpointsSupplier) { String contextId = ObjectUtils.getIdentityHexString(this.applicationContext); - EndpointObjectNameFactory objectNameFactory = new DefaultEndpointObjectNameFactory( - this.properties, mBeanServer, contextId); + EndpointObjectNameFactory objectNameFactory = new DefaultEndpointObjectNameFactory(this.properties, mBeanServer, + contextId); JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper( objectMapper.getIfAvailable()); return new JmxEndpointExporter(mBeanServer, objectNameFactory, responseMapper, @@ -99,8 +95,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 40797e7239e..356e87ece10 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. @@ -35,8 +35,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 @@ -48,8 +47,7 @@ class MappingWebEndpointPathMapper implements PathMapper { @Override public String getRootPath(EndpointId endpointId) { String path = this.pathMapping.get(endpointId); - return StringUtils.hasText(path) ? path - : PathMapper.useEndpointId().getRootPath(endpointId); + return StringUtils.hasText(path) ? path : PathMapper.useEndpointId().getRootPath(endpointId); } } 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 66356de3bc5..3777220c27e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -60,19 +60,15 @@ public class ServletEndpointManagementContextConfiguration { private final ApplicationContext context; - public WebMvcServletEndpointManagementContextConfiguration( - ApplicationContext context) { + public WebMvcServletEndpointManagementContextConfiguration(ApplicationContext context) { this.context = context; } @Bean - public ServletEndpointRegistrar servletEndpointRegistrar( - WebEndpointProperties properties, + public ServletEndpointRegistrar servletEndpointRegistrar(WebEndpointProperties properties, ServletEndpointsSupplier servletEndpointsSupplier) { - DispatcherServletPath dispatcherServletPath = this.context - .getBean(DispatcherServletPath.class); - return new ServletEndpointRegistrar( - dispatcherServletPath.getRelativePath(properties.getBasePath()), + DispatcherServletPath dispatcherServletPath = this.context.getBean(DispatcherServletPath.class); + return new ServletEndpointRegistrar(dispatcherServletPath.getRelativePath(properties.getBasePath()), servletEndpointsSupplier.getEndpoints()); } @@ -85,19 +81,15 @@ public class ServletEndpointManagementContextConfiguration { private final ApplicationContext context; - public JerseyServletEndpointManagementContextConfiguration( - ApplicationContext context) { + public JerseyServletEndpointManagementContextConfiguration(ApplicationContext context) { this.context = context; } @Bean - public ServletEndpointRegistrar servletEndpointRegistrar( - WebEndpointProperties properties, + public ServletEndpointRegistrar servletEndpointRegistrar(WebEndpointProperties properties, ServletEndpointsSupplier servletEndpointsSupplier) { - JerseyApplicationPath jerseyApplicationPath = this.context - .getBean(JerseyApplicationPath.class); - return new ServletEndpointRegistrar( - jerseyApplicationPath.getRelativePath(properties.getBasePath()), + JerseyApplicationPath jerseyApplicationPath = this.context.getBean(JerseyApplicationPath.class); + 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 e976e860ee2..cbe7135f903 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +65,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; } @@ -92,47 +90,41 @@ public class WebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(WebEndpointsSupplier.class) - public WebEndpointDiscoverer webEndpointDiscoverer( - ParameterValueMapper parameterValueMapper, + public WebEndpointDiscoverer webEndpointDiscoverer(ParameterValueMapper parameterValueMapper, EndpointMediaTypes endpointMediaTypes, PathMapper webEndpointPathMapper, ObjectProvider> invokerAdvisors, ObjectProvider>> filters) { - return new WebEndpointDiscoverer(this.applicationContext, parameterValueMapper, - endpointMediaTypes, webEndpointPathMapper, - invokerAdvisors.getIfAvailable(Collections::emptyList), + return new WebEndpointDiscoverer(this.applicationContext, parameterValueMapper, endpointMediaTypes, + webEndpointPathMapper, invokerAdvisors.getIfAvailable(Collections::emptyList), filters.getIfAvailable(Collections::emptyList)); } @Bean @ConditionalOnMissingBean(ControllerEndpointsSupplier.class) - public ControllerEndpointDiscoverer controllerEndpointDiscoverer( - PathMapper webEndpointPathMapper, + public ControllerEndpointDiscoverer controllerEndpointDiscoverer(PathMapper webEndpointPathMapper, ObjectProvider>> filters) { - return new ControllerEndpointDiscoverer(this.applicationContext, - webEndpointPathMapper, filters.getIfAvailable(Collections::emptyList)); + return new ControllerEndpointDiscoverer(this.applicationContext, webEndpointPathMapper, + filters.getIfAvailable(Collections::emptyList)); } @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()); } @@ -142,11 +134,10 @@ public class WebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean(ServletEndpointsSupplier.class) - public ServletEndpointDiscoverer servletEndpointDiscoverer( - ApplicationContext applicationContext, PathMapper webEndpointPathMapper, + public ServletEndpointDiscoverer servletEndpointDiscoverer(ApplicationContext applicationContext, + PathMapper webEndpointPathMapper, ObjectProvider>> filters) { - return new ServletEndpointDiscoverer(applicationContext, - webEndpointPathMapper, + return new ServletEndpointDiscoverer(applicationContext, webEndpointPathMapper, filters.getIfAvailable(Collections::emptyList)); } 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 4002e712d7f..0d171420349 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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()); @@ -71,10 +69,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 eef6d8d7231..de34cee58ad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,33 +59,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 c336da1c243..ed3db9bce0d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,36 +59,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 4ede4fff92a..bd28a57e8cf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 EnvironmentEndpointAutoConfiguration { private final EnvironmentEndpointProperties properties; - public EnvironmentEndpointAutoConfiguration( - EnvironmentEndpointProperties properties) { + public EnvironmentEndpointAutoConfiguration(EnvironmentEndpointProperties properties) { this.properties = properties; } @@ -61,8 +60,7 @@ public class EnvironmentEndpointAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint @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 1d4a5d8a20c..21f292508be 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. @@ -42,17 +42,14 @@ public abstract class CompositeHealthIndicatorConfiguration composite.addHealthIndicator(name, - createHealthIndicator(source))); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator); + beans.forEach((name, source) -> composite.addHealthIndicator(name, createHealthIndicator(source))); return composite; } @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]; @@ -60,8 +57,8 @@ public abstract class CompositeHealthIndicatorConfiguration composite.addHealthIndicator(name, - createHealthIndicator(source))); + CompositeReactiveHealthIndicator composite = new CompositeReactiveHealthIndicator(this.healthAggregator); + beans.forEach((name, source) -> composite.addHealthIndicator(name, createHealthIndicator(source))); return composite; } @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]; @@ -59,8 +56,8 @@ public abstract class CompositeReactiveHealthIndicatorConfiguration healthAggregator, ObjectProvider> reactiveHealthIndicators, ObjectProvider> healthIndicators) { - this.reactiveHealthIndicator = new CompositeReactiveHealthIndicatorFactory() - .createReactiveHealthIndicator( - healthAggregator.getIfAvailable(OrderedHealthAggregator::new), - reactiveHealthIndicators - .getIfAvailable(Collections::emptyMap), - healthIndicators.getIfAvailable(Collections::emptyMap)); + this.reactiveHealthIndicator = new CompositeReactiveHealthIndicatorFactory().createReactiveHealthIndicator( + healthAggregator.getIfAvailable(OrderedHealthAggregator::new), + reactiveHealthIndicators.getIfAvailable(Collections::emptyMap), + healthIndicators.getIfAvailable(Collections::emptyMap)); } @Bean @@ -92,8 +88,7 @@ class HealthEndpointWebExtensionConfiguration { @ConditionalOnBean(HealthEndpoint.class) public ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension( HealthWebEndpointResponseMapper responseMapper) { - return new ReactiveHealthEndpointWebExtension(this.reactiveHealthIndicator, - responseMapper); + return new ReactiveHealthEndpointWebExtension(this.reactiveHealthIndicator, responseMapper); } } @@ -106,11 +101,9 @@ class HealthEndpointWebExtensionConfiguration { @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint @ConditionalOnBean(HealthEndpoint.class) - public HealthEndpointWebExtension healthEndpointWebExtension( - ApplicationContext applicationContext, + public HealthEndpointWebExtension healthEndpointWebExtension(ApplicationContext applicationContext, HealthWebEndpointResponseMapper responseMapper) { - return new HealthEndpointWebExtension( - HealthIndicatorBeansComposite.get(applicationContext), + return new HealthEndpointWebExtension(HealthIndicatorBeansComposite.get(applicationContext), responseMapper); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansComposite.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansComposite.java index 131c9a698f8..2416b207b65 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansComposite.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansComposite.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ final class HealthIndicatorBeansComposite { 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); } CompositeHealthIndicatorFactory factory = new CompositeHealthIndicatorFactory(); return factory.createHealthIndicator(healthAggregator, indicators); } - private static HealthAggregator getHealthAggregator( - ApplicationContext applicationContext) { + private static HealthAggregator getHealthAggregator(ApplicationContext applicationContext) { try { return applicationContext.getBean(HealthAggregator.class); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansReactiveComposite.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansReactiveComposite.java index 259b13c30bc..d4a1547ee1c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansReactiveComposite.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorBeansReactiveComposite.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +38,12 @@ final class HealthIndicatorBeansReactiveComposite { public static ReactiveHealthIndicator get(ApplicationContext applicationContext) { HealthAggregator healthAggregator = getHealthAggregator(applicationContext); - return new CompositeReactiveHealthIndicatorFactory() - .createReactiveHealthIndicator(healthAggregator, - applicationContext.getBeansOfType(ReactiveHealthIndicator.class), - applicationContext.getBeansOfType(HealthIndicator.class)); + return new CompositeReactiveHealthIndicatorFactory().createReactiveHealthIndicator(healthAggregator, + applicationContext.getBeansOfType(ReactiveHealthIndicator.class), + applicationContext.getBeansOfType(HealthIndicator.class)); } - private static HealthAggregator getHealthAggregator( - ApplicationContext applicationContext) { + private static HealthAggregator getHealthAggregator(ApplicationContext applicationContext) { try { return applicationContext.getBean(HealthAggregator.class); } 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 228093311ea..6100fabdd30 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 InfoContributorAutoConfiguration { @Bean @ConditionalOnEnabledInfoContributor("env") @Order(DEFAULT_ORDER) - public EnvironmentInfoContributor envInfoContributor( - ConfigurableEnvironment environment) { + public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) { return new EnvironmentInfoContributor(environment); } 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 ad6ec7a4d1f..27a2f2e05f9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 InfoEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint - public InfoEndpoint infoEndpoint( - ObjectProvider> infoContributors) { + public InfoEndpoint infoEndpoint(ObjectProvider> infoContributors) { return new InfoEndpoint(infoContributors.getIfAvailable(Collections::emptyList)); } 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 20a10a91e67..5e903a9214b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 Map dataSources; @@ -71,15 +70,13 @@ public class DataSourceHealthIndicatorAutoConfiguration extends private DataSourcePoolMetadataProvider poolMetadataProvider; - public DataSourceHealthIndicatorAutoConfiguration( - ObjectProvider> dataSources, + public DataSourceHealthIndicatorAutoConfiguration(ObjectProvider> dataSources, ObjectProvider> metadataProviders) { this.dataSources = filterDataSources(dataSources.getIfAvailable()); this.metadataProviders = metadataProviders.getIfAvailable(); } - private Map filterDataSources( - Map candidates) { + private Map filterDataSources(Map candidates) { if (candidates == null) { return null; } @@ -94,8 +91,7 @@ public class DataSourceHealthIndicatorAutoConfiguration extends @Override public void afterPropertiesSet() throws Exception { - this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider( - this.metadataProviders); + this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(this.metadataProviders); } @Bean @@ -110,8 +106,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 3ec2c60668a..91e414f1f22 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +49,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 { private final Map connectionFactories; - public JmsHealthIndicatorAutoConfiguration( - ObjectProvider> connectionFactories) { + public JmsHealthIndicatorAutoConfiguration(ObjectProvider> connectionFactories) { this.connectionFactories = connectionFactories.getIfAvailable(); } 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 b47472bbdbc..f84f596daf2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 beb4e3ccec8..34d9ea78b0e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.ldap.core.LdapOperations; @ConditionalOnEnabledHealthIndicator("ldap") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(LdapDataAutoConfiguration.class) -public class LdapHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class LdapHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map ldapOperations; - public LdapHealthIndicatorAutoConfiguration( - Map ldapOperations) { + public LdapHealthIndicatorAutoConfiguration(Map ldapOperations) { this.ldapOperations = 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 7a4c8658cf5..ab8a0a91981 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +59,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 9489a5bbf0a..6d11fe0d779 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,25 +57,20 @@ public class LogFileWebEndpointAutoConfiguration { private static class LogFileCondition extends SpringBootCondition { @Override - public ConditionOutcome getMatchOutcome(ConditionContext context, - AnnotatedTypeMetadata metadata) { + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String config = environment.resolvePlaceholders("${logging.file:}"); ConditionMessage.Builder message = ConditionMessage.forCondition("Log File"); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found("logging.file").items(config)); + return ConditionOutcome.match(message.found("logging.file").items(config)); } config = environment.resolvePlaceholders("${logging.path:}"); if (StringUtils.hasText(config)) { - return ConditionOutcome - .match(message.found("logging.path").items(config)); + return ConditionOutcome.match(message.found("logging.path").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()); } 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 6abb42df794..1fd43ee3456 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 5c37eacce9e..8da2e6d0c1a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; @ConditionalOnEnabledHealthIndicator("mail") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(MailSenderAutoConfiguration.class) -public class MailHealthIndicatorAutoConfiguration extends - CompositeHealthIndicatorConfiguration { +public class MailHealthIndicatorAutoConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map mailSenders; - public MailHealthIndicatorAutoConfiguration( - ObjectProvider> mailSenders) { + public MailHealthIndicatorAutoConfiguration(ObjectProvider> mailSenders) { this.mailSenders = mailSenders.getIfAvailable(); } 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 558b73bdf25..42f83b250ca 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.context.annotation.Import; * @since 2.0.0 */ @Configuration -@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 f5b45c4684b..dfccafb7172 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/MeterRegistryConfigurer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java index a0562ac03dd..a19f633650a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class MeterRegistryConfigurer { private final boolean addToGlobalRegistry; - MeterRegistryConfigurer(Collection binders, - Collection filters, - Collection> customizers, - boolean addToGlobalRegistry) { + MeterRegistryConfigurer(Collection binders, Collection filters, + Collection> customizers, boolean addToGlobalRegistry) { this.binders = (binders != null) ? binders : Collections.emptyList(); this.filters = (filters != null) ? filters : Collections.emptyList(); this.customizers = (customizers != null) ? customizers : Collections.emptyList(); @@ -68,8 +66,7 @@ class MeterRegistryConfigurer { @SuppressWarnings("unchecked") private void customize(MeterRegistry registry) { LambdaSafe.callbacks(MeterRegistryCustomizer.class, this.customizers, registry) - .withLogger(MeterRegistryConfigurer.class) - .invoke((customizer) -> customizer.customize(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 b6ab97c8ac4..2d561b10ee1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -68,8 +67,7 @@ class MeterRegistryPostProcessor implements BeanPostProcessor { private MeterRegistryConfigurer getConfigurer() { if (this.configurer == null) { - this.configurer = new MeterRegistryConfigurer( - this.meterBinders.getIfAvailable(Collections::emptyList), + this.configurer = new MeterRegistryConfigurer(this.meterBinders.getIfAvailable(Collections::emptyList), this.meterFilters.getIfAvailable(Collections::emptyList), this.meterRegistryCustomizers.getIfAvailable(Collections::emptyList), this.metricsProperties.getObject().isUseGlobalRegistry()); 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 6c3e1335188..59829d2d9f1 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 @@ -71,13 +71,11 @@ public class MetricsAutoConfiguration { } @Bean - public static MeterRegistryPostProcessor meterRegistryPostProcessor( - ObjectProvider> meterBinders, + public static MeterRegistryPostProcessor meterRegistryPostProcessor(ObjectProvider> meterBinders, ObjectProvider> meterFilters, ObjectProvider>> meterRegistryCustomizers, ObjectProvider metricsProperties) { - return new MeterRegistryPostProcessor(meterBinders, meterFilters, - meterRegistryCustomizers, metricsProperties); + return new MeterRegistryPostProcessor(meterBinders, meterFilters, meterRegistryCustomizers, metricsProperties); } @Bean @@ -87,8 +85,7 @@ public class MetricsAutoConfiguration { } @Configuration - @ConditionalOnProperty(value = "management.metrics.binders.jvm.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "management.metrics.binders.jvm.enabled", matchIfMissing = true) static class JvmMeterBindersConfiguration { @Bean @@ -121,35 +118,30 @@ public class MetricsAutoConfiguration { static class MeterBindersConfiguration { @Bean - @ConditionalOnClass(name = { "ch.qos.logback.classic.LoggerContext", - "org.slf4j.LoggerFactory" }) + @ConditionalOnClass(name = { "ch.qos.logback.classic.LoggerContext", "org.slf4j.LoggerFactory" }) @Conditional(LogbackLoggingCondition.class) @ConditionalOnMissingBean - @ConditionalOnProperty(value = "management.metrics.binders.logback.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "management.metrics.binders.logback.enabled", matchIfMissing = true) public LogbackMetrics logbackMetrics() { return new LogbackMetrics(); } @Bean - @ConditionalOnProperty(value = "management.metrics.binders.uptime.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "management.metrics.binders.uptime.enabled", matchIfMissing = true) @ConditionalOnMissingBean public UptimeMetrics uptimeMetrics() { return new UptimeMetrics(); } @Bean - @ConditionalOnProperty(value = "management.metrics.binders.processor.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "management.metrics.binders.processor.enabled", matchIfMissing = true) @ConditionalOnMissingBean public ProcessorMetrics processorMetrics() { return new ProcessorMetrics(); } @Bean - @ConditionalOnProperty(name = "management.metrics.binders.files.enabled", - matchIfMissing = true) + @ConditionalOnProperty(name = "management.metrics.binders.files.enabled", matchIfMissing = true) @ConditionalOnMissingBean public FileDescriptorMetrics fileDescriptorMetrics() { return new FileDescriptorMetrics(); @@ -160,18 +152,14 @@ public class MetricsAutoConfiguration { 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/MetricsEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsEndpointAutoConfiguration.java index 82210c46fdd..34e6fc636df 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.annotation.Configuration; */ @Configuration @ConditionalOnClass(Timed.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/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 b44b2786c17..6074ce45e1b 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 final Logger logger = LoggerFactory - .getLogger(OnlyOnceLoggingDenyMeterFilter.class); + private final Logger logger = LoggerFactory.getLogger(OnlyOnceLoggingDenyMeterFilter.class); private final AtomicBoolean alreadyWarned = new AtomicBoolean(false); @@ -50,8 +49,7 @@ public final class OnlyOnceLoggingDenyMeterFilter implements MeterFilter { @Override public MeterFilterReply accept(Meter.Id id) { - if (this.logger.isWarnEnabled() - && this.alreadyWarned.compareAndSet(false, true)) { + if (this.logger.isWarnEnabled() && this.alreadyWarned.compareAndSet(false, true)) { this.logger.warn(this.message.get()); } return MeterFilterReply.DENY; 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 c6e43bf4534..51b20c9ea79 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. @@ -53,24 +53,20 @@ 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( - lookup(distribution.getPercentilesHistogram(), id, null)) + .percentilesHistogram(lookup(distribution.getPercentilesHistogram(), id, null)) .percentiles(lookup(distribution.getPercentiles(), id, null)) - .sla(convertSla(id.getType(), lookup(distribution.getSla(), id, null))) - .build().merge(config); + .sla(convertSla(id.getType(), lookup(distribution.getSla(), id, null))).build().merge(config); } private long[] convertSla(Meter.Type meterType, ServiceLevelAgreementBoundary[] sla) { 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 1289f46c863..6ec948f0e04 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.context.annotation.Configuration; class CacheMeterBinderProvidersConfiguration { @Configuration - @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 3c5b88ff285..763d9b61414 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.annotation.Import; @Configuration @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 cb440ccacb0..6406c4ed173 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 CacheMetricsRegistrarConfiguration { private final Map cacheManagers; - CacheMetricsRegistrarConfiguration(MeterRegistry registry, - Collection> binderProviders, + CacheMetricsRegistrarConfiguration(MeterRegistry registry, Collection> binderProviders, Map cacheManagers) { this.registry = registry; this.binderProviders = binderProviders; @@ -70,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) { @@ -87,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/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 4b69ef2cdc3..89f52c94461 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 -@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/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 5340a6df276..b677834a317 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 -@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 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 a0a8a5db16a..a4e5be5c368 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 -@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/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 7b21b56a237..fc9f03b9dad 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 @@ -42,13 +42,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration -@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 { @@ -60,8 +59,7 @@ public class NewRelicMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, - Clock clock) { + public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, Clock clock) { return new NewRelicMeterRegistry(newRelicConfig, clock); } 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 c6505521f7a..138af39c232 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 @@ -44,13 +44,12 @@ import org.springframework.context.annotation.Configuration; * @author Jon Schneider */ @Configuration -@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 { @@ -62,9 +61,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); } @@ -80,8 +78,7 @@ public class PrometheusMetricsExportAutoConfiguration { @Bean @ConditionalOnEnabledEndpoint @ConditionalOnMissingBean - public PrometheusScrapeEndpoint prometheusEndpoint( - CollectorRegistry collectorRegistry) { + public PrometheusScrapeEndpoint prometheusEndpoint(CollectorRegistry collectorRegistry) { return new PrometheusScrapeEndpoint(collectorRegistry); } 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 5bc4a5c79c0..96538af576d 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 -@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 bc7f081c491..4afa8ef6a0f 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 1cc33f831d1..56266863b94 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 -@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/StatsdProperties.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdProperties.java index 69b88785e64..99092220be6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdProperties.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdProperties.java @@ -124,8 +124,7 @@ public class StatsdProperties { } @Deprecated - @DeprecatedConfigurationProperty( - reason = "No longer configurable and an unbounded queue will always be used") + @DeprecatedConfigurationProperty(reason = "No longer configurable and an unbounded queue will always be used") public Integer getQueueSize() { return this.queueSize; } 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 25175ddbe14..1d2b7a74987 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,14 +62,12 @@ 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 @@ -81,8 +78,7 @@ public class StatsdPropertiesConfigAdapter @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 ee5bbcc38a4..d469587e087 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 @@ -41,13 +41,12 @@ import org.springframework.context.annotation.Configuration; * @since 2.0.0 */ @Configuration -@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 { @@ -59,8 +58,7 @@ public class WavefrontMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean - public WavefrontMeterRegistry wavefrontMeterRegistry(WavefrontConfig wavefrontConfig, - Clock clock) { + public WavefrontMeterRegistry wavefrontMeterRegistry(WavefrontConfig wavefrontConfig, Clock clock) { return new WavefrontMeterRegistry(wavefrontConfig, clock); } 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 d6a6e256a32..7e7fba3435a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class DataSourcePoolMetricsAutoConfiguration { private void bindDataSourceToRegistry(String beanName, DataSource dataSource) { String dataSourceName = getDataSourceName(beanName); - new DataSourcePoolMetrics(dataSource, this.metadataProviders, dataSourceName, - Collections.emptyList()).bindTo(this.registry); + new DataSourcePoolMetrics(dataSource, this.metadataProviders, dataSourceName, Collections.emptyList()) + .bindTo(this.registry); } /** @@ -89,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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/HikariDataSourceMetricsPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/HikariDataSourceMetricsPostProcessor.java index dc4ccdfad5d..74f08cbd81f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/HikariDataSourceMetricsPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/HikariDataSourceMetricsPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.core.Ordered; */ class HikariDataSourceMetricsPostProcessor implements BeanPostProcessor, Ordered { - private static final Log logger = LogFactory - .getLog(HikariDataSourceMetricsPostProcessor.class); + private static final Log logger = LogFactory.getLog(HikariDataSourceMetricsPostProcessor.class); private final ApplicationContext context; @@ -65,12 +64,10 @@ class HikariDataSourceMetricsPostProcessor implements BeanPostProcessor, Ordered return null; } - private void bindMetricsRegistryToHikariDataSource(MeterRegistry registry, - HikariDataSource dataSource) { + private void bindMetricsRegistryToHikariDataSource(MeterRegistry registry, HikariDataSource dataSource) { if (!hasExisingMetrics(dataSource)) { try { - dataSource.setMetricsTrackerFactory( - new MicrometerMetricsTrackerFactory(registry)); + dataSource.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(registry)); } catch (Exception ex) { logger.warn("Failed to bind Hikari metrics: " + ex.getMessage()); @@ -79,8 +76,7 @@ class HikariDataSourceMetricsPostProcessor implements BeanPostProcessor, Ordered } private boolean hasExisingMetrics(HikariDataSource dataSource) { - return dataSource.getMetricRegistry() != null - || dataSource.getMetricsTrackerFactory() != null; + return dataSource.getMetricRegistry() != null || dataSource.getMetricsTrackerFactory() != null; } private MeterRegistry getMeterRegistry() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfiguration.java index a88cc55ada6..b1c9bb15f58 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 RestTemplateMetricsAutoConfiguration { } @Bean - public MetricsRestTemplateCustomizer metricsRestTemplateCustomizer( - MeterRegistry meterRegistry, + public MetricsRestTemplateCustomizer metricsRestTemplateCustomizer(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider restTemplateTagConfigurer) { return new MetricsRestTemplateCustomizer(meterRegistry, restTemplateTagConfigurer, this.properties.getWeb().getClient().getRequestsMetricName()); @@ -76,11 +75,11 @@ public class RestTemplateMetricsAutoConfiguration { @Order(0) public MeterFilter metricsWebClientUriTagFilter() { String metricName = this.properties.getWeb().getClient().getRequestsMetricName(); - MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter(() -> String - .format("Reached the maximum number of URI tags for '%s'. Are you using " + MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter( + () -> String.format("Reached the maximum number of URI tags for '%s'. Are you using " + "'uriVariables' on RestTemplate calls?", metricName)); - return MeterFilter.maximumAllowableTags(metricName, "uri", - this.properties.getWeb().getClient().getMaxUriTags(), denyFilter); + return MeterFilter.maximumAllowableTags(metricName, "uri", this.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/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 7d36305a71f..9133f147a40 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.core.annotation.Order; * @since 2.0.0 */ @Configuration -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @ConditionalOnBean(MeterRegistry.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) public class WebFluxMetricsAutoConfiguration { @@ -63,8 +62,7 @@ public class WebFluxMetricsAutoConfiguration { } @Bean - public MetricsWebFilter webfluxMetrics(MeterRegistry registry, - WebFluxTagsProvider tagConfigurer) { + public MetricsWebFilter webfluxMetrics(MeterRegistry registry, WebFluxTagsProvider tagConfigurer) { return new MetricsWebFilter(registry, tagConfigurer, this.properties.getWeb().getServer().getRequestsMetricName(), this.properties.getWeb().getServer().isAutoTimeRequests()); @@ -74,10 +72,10 @@ public class WebFluxMetricsAutoConfiguration { @Order(0) public MeterFilter metricsHttpServerUriTagFilter() { String metricName = this.properties.getWeb().getServer().getRequestsMetricName(); - 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); + 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 a2c6ac8b329..4f3ea80acf9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @since 2.0.0 */ @Configuration -@AutoConfigureAfter({ MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class }) +@AutoConfigureAfter({ MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @ConditionalOnBean(MeterRegistry.class) @@ -76,14 +75,12 @@ public class WebMvcMetricsAutoConfiguration { } @Bean - public FilterRegistrationBean webMvcMetricsFilter( - MeterRegistry registry, WebMvcTagsProvider tagsProvider) { + public FilterRegistrationBean webMvcMetricsFilter(MeterRegistry registry, + WebMvcTagsProvider tagsProvider) { Server serverProperties = this.properties.getWeb().getServer(); WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, - serverProperties.getRequestsMetricName(), - serverProperties.isAutoTimeRequests()); - FilterRegistrationBean registration = new FilterRegistrationBean<>( - filter); + serverProperties.getRequestsMetricName(), serverProperties.isAutoTimeRequests()); + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC); return registration; @@ -93,10 +90,10 @@ public class WebMvcMetricsAutoConfiguration { @Order(0) public MeterFilter metricsHttpServerUriTagFilter() { String metricName = this.properties.getWeb().getServer().getRequestsMetricName(); - 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); + 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/metrics/web/tomcat/TomcatMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfiguration.java index eb65b0ebfc1..8fb4e4ac100 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,7 @@ public class TomcatMetricsAutoConfiguration { @Bean @ConditionalOnMissingBean public TomcatMetrics tomcatMetrics() { - return new TomcatMetrics( - (this.context != null) ? this.context.getManager() : null, - Collections.emptyList()); + return new TomcatMetrics((this.context != null) ? this.context.getManager() : null, Collections.emptyList()); } @Bean 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 af141404ef3..053139ba775 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.annotation.Import; @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter({ MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class }) -@Import({ MongoReactiveHealthIndicatorConfiguration.class, - MongoHealthIndicatorConfiguration.class }) +@Import({ MongoReactiveHealthIndicatorConfiguration.class, MongoHealthIndicatorConfiguration.class }) public class MongoHealthIndicatorAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorConfiguration.java index 5c20e8aab4d..e9beafcd27f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.data.mongodb.core.MongoTemplate; @Configuration @ConditionalOnClass(MongoTemplate.class) @ConditionalOnBean(MongoTemplate.class) -class MongoHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { +class MongoHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map mongoTemplates; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfiguration.java index d67c19556dc..7104b2219ef 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 @@ import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @Configuration @ConditionalOnClass(ReactiveMongoTemplate.class) @ConditionalOnBean(ReactiveMongoTemplate.class) -class MongoReactiveHealthIndicatorConfiguration extends - CompositeReactiveHealthIndicatorConfiguration { +class MongoReactiveHealthIndicatorConfiguration + extends CompositeReactiveHealthIndicatorConfiguration { private final Map reactiveMongoTemplate; - MongoReactiveHealthIndicatorConfiguration( - Map reactiveMongoTemplate) { + MongoReactiveHealthIndicatorConfiguration(Map reactiveMongoTemplate) { this.reactiveMongoTemplate = reactiveMongoTemplate; } 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 51130a29d70..03ee2b86bd6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 { private final Map sessionFactories; - public Neo4jHealthIndicatorAutoConfiguration( - Map sessionFactories) { + public Neo4jHealthIndicatorAutoConfiguration(Map sessionFactories) { this.sessionFactories = 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 852347b05e8..c9ebc23c715 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.context.annotation.Import; @ConditionalOnEnabledHealthIndicator("redis") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(RedisAutoConfiguration.class) -@Import({ RedisReactiveHealthIndicatorConfiguration.class, - RedisHealthIndicatorConfiguration.class }) +@Import({ RedisReactiveHealthIndicatorConfiguration.class, RedisHealthIndicatorConfiguration.class }) public class RedisHealthIndicatorAutoConfiguration { } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorConfiguration.java index d919958659e..918cf1a399f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +39,12 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; @Configuration @ConditionalOnClass(RedisConnectionFactory.class) @ConditionalOnBean(RedisConnectionFactory.class) -class RedisHealthIndicatorConfiguration extends - CompositeHealthIndicatorConfiguration { +class RedisHealthIndicatorConfiguration + extends CompositeHealthIndicatorConfiguration { private final Map redisConnectionFactories; - RedisHealthIndicatorConfiguration( - Map redisConnectionFactories) { + RedisHealthIndicatorConfiguration(Map redisConnectionFactories) { this.redisConnectionFactories = redisConnectionFactories; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfiguration.java index d59d5b924e9..6a5f9cdabb6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 RedisReactiveHealthIndicatorConfiguration extends private final Map redisConnectionFactories; - RedisReactiveHealthIndicatorConfiguration( - Map redisConnectionFactories) { + RedisReactiveHealthIndicatorConfiguration(Map redisConnectionFactories) { this.redisConnectionFactories = 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 d10e83f9b44..3cc0288cbd5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ScheduledTasksEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint - public ScheduledTasksEndpoint scheduledTasksEndpoint( - ObjectProvider> holders) { + public ScheduledTasksEndpoint scheduledTasksEndpoint(ObjectProvider> holders) { return new ScheduledTasksEndpoint(holders.getIfAvailable(Collections::emptyList)); } 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 c25b4fc60ab..b982a146078 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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() { } @@ -132,20 +131,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; @@ -155,20 +149,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 @@ -176,8 +167,7 @@ public final class EndpointRequest { this.delegate = createDelegate(pathMappedEndpoints); } - private ServerWebExchangeMatcher createDelegate( - Supplier pathMappedEndpoints) { + private ServerWebExchangeMatcher createDelegate(Supplier pathMappedEndpoints) { try { return createDelegate(pathMappedEndpoints.get()); } @@ -186,8 +176,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()); @@ -195,18 +184,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) { @@ -223,22 +208,18 @@ public final class EndpointRequest { } private EndpointId getEndpointId(Class source) { - Endpoint annotation = AnnotatedElementUtils.getMergedAnnotation(source, - Endpoint.class); - Assert.state(annotation != null, - () -> "Class " + source + " is not annotated with @Endpoint"); + Endpoint annotation = AnnotatedElementUtils.getMergedAnnotation(source, Endpoint.class); + Assert.state(annotation != null, () -> "Class " + source + " is not annotated with @Endpoint"); return EndpointId.of(annotation.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) { return this.delegate.matches(exchange); } @@ -261,18 +242,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) { return this.delegate.matches(exchange); } 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 2199926c179..ecebacbed92 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,8 +131,7 @@ public final class EndpointRequest { } @Override - protected final boolean matches(HttpServletRequest request, - Supplier context) { + protected final boolean matches(HttpServletRequest request, Supplier context) { return this.delegate.matches(request); } @@ -148,18 +147,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); } @@ -186,17 +182,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; @@ -221,8 +214,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()) { @@ -230,20 +222,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) { @@ -260,18 +248,14 @@ public final class EndpointRequest { } private EndpointId getEndpointId(Class source) { - Endpoint annotation = AnnotatedElementUtils.getMergedAnnotation(source, - Endpoint.class); - Assert.state(annotation != null, - () -> "Class " + source + " is not annotated with @Endpoint"); + Endpoint annotation = AnnotatedElementUtils.getMergedAnnotation(source, Endpoint.class); + Assert.state(annotation != null, () -> "Class " + source + " is not annotated with @Endpoint"); return EndpointId.of(annotation.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()); } @@ -285,12 +269,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; } @@ -302,8 +285,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/session/SessionsEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfiguration.java index c83dc525258..b0cf9b1ce03 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SessionsEndpointAutoConfiguration { @ConditionalOnBean(FindByIndexNameSessionRepository.class) @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint - 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 25b5f6d1579..e48e1c14c3f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/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 8fcc06c2d8a..b0a51fd86aa 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 @ConditionalOnWebApplication -@ConditionalOnProperty(prefix = "management.trace.http", name = "enabled", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "management.trace.http", name = "enabled", matchIfMissing = true) @EnableConfigurationProperties(HttpTraceProperties.class) public class HttpTraceAutoConfiguration { @@ -61,8 +60,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); } @@ -74,10 +72,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/JerseyManagementChildContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementChildContextConfiguration.java index 87804f41bb0..80202572a4b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementChildContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementChildContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JerseyManagementChildContextConfiguration { public JerseyManagementChildContextConfiguration( ObjectProvider> resourceConfigCustomizers) { - this.resourceConfigCustomizers = resourceConfigCustomizers - .getIfAvailable(Collections::emptyList); + this.resourceConfigCustomizers = resourceConfigCustomizers.getIfAvailable(Collections::emptyList); } @Bean public ServletRegistrationBean jerseyServletRegistration() { - return new ServletRegistrationBean<>( - new ServletContainer(endpointResourceConfig()), "/*"); + return new ServletRegistrationBean<>(new ServletContainer(endpointResourceConfig()), "/*"); } @Bean 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 1124d4536d3..a4df5592fc6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,7 @@ public class MappingsEndpointAutoConfiguration { @ConditionalOnEnabledEndpoint public MappingsEndpoint mappingsEndpoint(ApplicationContext applicationContext, ObjectProvider> descriptionProviders) { - return new MappingsEndpoint( - descriptionProviders.getIfAvailable(Collections::emptyList), - applicationContext); + return new MappingsEndpoint(descriptionProviders.getIfAvailable(Collections::emptyList), applicationContext); } @Configuration 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 174e08b9644..e44e17a8193 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +57,12 @@ 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, - JettyWebServerFactoryCustomizer.class, - UndertowWebServerFactoryCustomizer.class); + super(beanFactory, ReactiveWebServerFactoryCustomizer.class, TomcatWebServerFactoryCustomizer.class, + JettyWebServerFactoryCustomizer.class, UndertowWebServerFactoryCustomizer.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 d657adac714..a92cf8f851e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +55,14 @@ import org.springframework.util.Assert; */ @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) -@EnableConfigurationProperties({ WebEndpointProperties.class, - ManagementServerProperties.class }) +@EnableConfigurationProperties({ WebEndpointProperties.class, ManagementServerProperties.class }) public class ManagementContextAutoConfiguration { - private static final Log logger = LogFactory - .getLog(ManagementContextAutoConfiguration.class); + private static final Log logger = LogFactory.getLog(ManagementContextAutoConfiguration.class); @Configuration @ConditionalOnManagementPort(ManagementPortType.SAME) - static class SameManagementContextConfiguration - implements SmartInitializingSingleton { + static class SameManagementContextConfiguration implements SmartInitializingSingleton { private final Environment environment; @@ -77,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"); } /** @@ -95,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 @@ -121,8 +113,7 @@ public class ManagementContextAutoConfiguration { @Configuration @ConditionalOnManagementPort(ManagementPortType.DIFFERENT) - static class DifferentManagementContextConfiguration - implements SmartInitializingSingleton { + static class DifferentManagementContextConfiguration implements SmartInitializingSingleton { private final ApplicationContext applicationContext; @@ -137,8 +128,7 @@ public class ManagementContextAutoConfiguration { @Override public void afterSingletonsInstantiated() { if (this.applicationContext instanceof WebServerApplicationContext - && ((WebServerApplicationContext) this.applicationContext) - .getWebServer() != null) { + && ((WebServerApplicationContext) this.applicationContext).getWebServer() != null) { ConfigurableWebServerApplicationContext managementContext = this.managementContextFactory .createManagementContext(this.applicationContext, EnableChildManagementContextConfiguration.class, @@ -146,21 +136,18 @@ public class ManagementContextAutoConfiguration { managementContext.setServerNamespace("management"); managementContext.setId(this.applicationContext.getId() + ":management"); setClassLoaderIfPossible(managementContext); - CloseManagementContextListener.addIfPossible(this.applicationContext, - managementContext); + CloseManagementContextListener.addIfPossible(this.applicationContext, managementContext); managementContext.refresh(); } else { logger.warn("Could not start embedded management container on " - + "different port (management endpoints are still available " - + "through JMX)"); + + "different port (management endpoints are still available " + "through JMX)"); } } private void setClassLoaderIfPossible(ConfigurableApplicationContext child) { if (child instanceof DefaultResourceLoader) { - ((DefaultResourceLoader) child) - .setClassLoader(this.applicationContext.getClassLoader()); + ((DefaultResourceLoader) child).setClassLoader(this.applicationContext.getClassLoader()); } } @@ -170,15 +157,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; } @@ -216,8 +201,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 f40736631ae..e7a2a19cfec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ public enum ManagementPortType { if (managementPort != null && managementPort < 0) { return DISABLED; } - 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 e1003a60957..1b5a59f605a 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 WebApplicationContext.class.isInstance(resourceLoader); 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 8ccb7e1e8e5..f74b3506fe1 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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); 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 2e5a6d9c28f..67a1bc82e51 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 @@ -96,8 +96,7 @@ class ServletManagementChildContextConfiguration { @Configuration @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 @@ -108,25 +107,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 684ab015316..6ca724d26b7 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 - @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 8295805b269..44152ef6df5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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, "/"); } @@ -82,8 +81,7 @@ class WebMvcEndpointChildContextConfiguration { } @Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME) - public CompositeHandlerAdapter compositeHandlerAdapter( - ListableBeanFactory beanFactory) { + public CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) { return new CompositeHandlerAdapter(beanFactory); } @@ -93,8 +91,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 dab2dbcbadd..e075dedb13c 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 @@ -55,40 +55,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, JestAutoConfiguration.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, JestAutoConfiguration.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, JestAutoConfiguration.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, JestAutoConfiguration.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 26d8af124a7..0511b0ff8db 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 62df061e015..6470c733192 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,34 +55,28 @@ public class AuditAutoConfigurationTests { @Test public void ownAuditEventRepository() { - registerAndRefresh(CustomAuditEventRepositoryConfiguration.class, - AuditAutoConfiguration.class); - assertThat(this.context.getBean(AuditEventRepository.class)) - .isInstanceOf(TestAuditEventRepository.class); + registerAndRefresh(CustomAuditEventRepositoryConfiguration.class, AuditAutoConfiguration.class); + assertThat(this.context.getBean(AuditEventRepository.class)).isInstanceOf(TestAuditEventRepository.class); } @Test public void ownAuthenticationAuditListener() { - registerAndRefresh(CustomAuthenticationAuditListenerConfiguration.class, - AuditAutoConfiguration.class); + registerAndRefresh(CustomAuthenticationAuditListenerConfiguration.class, AuditAutoConfiguration.class); assertThat(this.context.getBean(AbstractAuthenticationAuditListener.class)) .isInstanceOf(TestAuthenticationAuditListener.class); } @Test public void ownAuthorizationAuditListener() { - registerAndRefresh(CustomAuthorizationAuditListenerConfiguration.class, - AuditAutoConfiguration.class); + registerAndRefresh(CustomAuthorizationAuditListenerConfiguration.class, AuditAutoConfiguration.class); assertThat(this.context.getBean(AbstractAuthorizationAuditListener.class)) .isInstanceOf(TestAuthorizationAuditListener.class); } @Test public void ownAuditListener() { - registerAndRefresh(CustomAuditListenerConfiguration.class, - AuditAutoConfiguration.class); - assertThat(this.context.getBean(AbstractAuditListener.class)) - .isInstanceOf(TestAuditListener.class); + registerAndRefresh(CustomAuditListenerConfiguration.class, AuditAutoConfiguration.class); + assertThat(this.context.getBean(AbstractAuditListener.class)).isInstanceOf(TestAuditListener.class); } private void registerAndRefresh(Class... annotatedClasses) { @@ -114,8 +108,7 @@ public class AuditAutoConfigurationTests { } - protected static class TestAuthenticationAuditListener - extends AbstractAuthenticationAuditListener { + protected static class TestAuthenticationAuditListener extends AbstractAuthenticationAuditListener { @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { @@ -137,8 +130,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 21d0734dfec..148de27b008 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 @@ 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 runShouldHaveEndpointBean() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(AuditEventsEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { - this.contextRunner - .withPropertyValues("management.endpoint.auditevents.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(AuditEventsEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.auditevents.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } } 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 25fdfe2f401..5867c78da08 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,17 @@ 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 - .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false") - .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/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthIndicatorAutoConfigurationTests.java index 2b00fb164f5..d885ae34403 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/cloudfoundry/AuthorizationExceptionMatcher.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AuthorizationExceptionMatcher.java index 1924147876f..3fb8b994fb5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AuthorizationExceptionMatcher.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AuthorizationExceptionMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +32,12 @@ public final class AuthorizationExceptionMatcher { } public static Matcher withReason(Reason reason) { - return new CustomMatcher( - "CloudFoundryAuthorizationException with " + reason + " reason") { + return new CustomMatcher("CloudFoundryAuthorizationException with " + reason + " reason") { @Override public boolean matches(Object object) { return ((object instanceof CloudFoundryAuthorizationException) - && ((CloudFoundryAuthorizationException) object) - .getReason() == reason); + && ((CloudFoundryAuthorizationException) object).getReason() == reason); } }; 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 313e1d51a6c..44a8b951226 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 94564af5ea6..e4ef45a1533 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 c29b165394e..c2f097d5594 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,34 +60,29 @@ public class CloudFoundryWebEndpointDiscovererTests { for (ExposableWebEndpoint endpoint : endpoints) { if (endpoint.getEndpointId().equals(EndpointId.of("health"))) { WebOperation operation = endpoint.getOperations().iterator().next(); - assertThat(operation.invoke(new InvocationContext( - mock(SecurityContext.class), Collections.emptyMap()))) + assertThat(operation + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap()))) .isEqualTo("cf"); } } }); } - private void load(Class configuration, - Consumer consumer) { + private void load(Class configuration, Consumer consumer) { this.load((id) -> null, (id) -> id, configuration, consumer); } - private void load(Function timeToLive, - PathMapper endpointPathMapper, Class configuration, + private void load(Function timeToLive, PathMapper endpointPathMapper, Class configuration, Consumer consumer) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - configuration); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configuration); try { 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, endpointPathMapper, - Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), - Collections.emptyList()); + CloudFoundryWebEndpointDiscoverer discoverer = new CloudFoundryWebEndpointDiscoverer(context, + parameterMapper, mediaTypes, endpointPathMapper, + Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), Collections.emptyList()); consumer.accept(discoverer); } finally { 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 512600add6f..a8c254b0ebd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 TokenTests { @Test public void invalidJwtShouldThrowException() { - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); new Token("invalid-token"); } @@ -46,28 +45,23 @@ public class TokenTests { public void invalidJwtClaimsShouldThrowException() { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes())); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + new Token(Base64Utils.encodeToString(header.getBytes()) + "." + Base64Utils.encodeToString(claims.getBytes())); } @Test public void invalidJwtHeaderShouldThrowException() { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes())); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + new Token(Base64Utils.encodeToString(header.getBytes()) + "." + Base64Utils.encodeToString(claims.getBytes())); } @Test public void emptyJwtSignatureShouldThrowException() { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); new Token(token); } @@ -84,8 +78,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 @@ -93,8 +86,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); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getSignatureAlgorithm(); } @@ -103,8 +95,7 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getIssuer(); } @@ -113,8 +104,7 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getKeyId(); } @@ -123,15 +113,14 @@ 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); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); token.getExpiry(); } 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; } 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 0d817dc7739..44d676f2465 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 8c773f57bda..446702339fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,109 +71,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()); }; } @@ -188,8 +167,7 @@ public class CloudFoundryWebFluxEndpointIntegrationTests { @Bean public CloudFoundrySecurityInterceptor interceptor() { - return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, - "app-id"); + return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, "app-id"); } @Bean @@ -200,28 +178,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, PathMapper.useEndpointId(), - Collections.emptyList(), Collections.emptyList()); + return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes, + PathMapper.useEndpointId(), 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 1a37ef949df..011cabe9c7b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +80,13 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { public ExpectedException thrown = ExpectedException.none(); 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, - HealthEndpointAutoConfiguration.class, - ReactiveCloudFoundryActuatorAutoConfiguration.class)); + HealthEndpointAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); @After public void close() { @@ -99,90 +95,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(); }); } @@ -190,28 +163,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(); }); @@ -220,34 +187,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.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") + this.contextRunner.withUserConfiguration(TestConfiguration.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); - 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")); }); @@ -255,96 +212,70 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test public void endpointPathCustomizationIsNotApplied() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") + this.contextRunner.withUserConfiguration(TestConfiguration.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); - 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(); - WebOperation webOperation = endpoint.getOperations().iterator() - .next(); - Object invoker = ReflectionTestUtils.getField(webOperation, - "invoker"); + WebOperation webOperation = endpoint.getOperations().iterator().next(); + Object invoker = ReflectionTestUtils.getField(webOperation, "invoker"); assertThat(ReflectionTestUtils.getField(invoker, "target")) - .isInstanceOf( - CloudFoundryReactiveHealthEndpointWebExtension.class); + .isInstanceOf(CloudFoundryReactiveHealthEndpointWebExtension.class); }); } @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"); + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, + "webClient"); this.thrown.expectCause(instanceOf(SSLException.class)); - webClient.get().uri("https://self-signed.badssl.com/").exchange() - .block(Duration.ofSeconds(30)); + webClient.get().uri("https://self-signed.badssl.com/").exchange().block(Duration.ofSeconds(30)); }); } - private CloudFoundryWebFluxEndpointHandlerMapping getHandlerMapping( - ApplicationContext context) { + private CloudFoundryWebFluxEndpointHandlerMapping getHandlerMapping(ApplicationContext context) { return context.getBean("cloudFoundryWebFluxEndpointHandlerMapping", CloudFoundryWebFluxEndpointHandlerMapping.class); } 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 b2be64d684e..17041bae2b6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,62 +54,54 @@ public class ReactiveCloudFoundrySecurityInterceptorTests { @Before 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 2d7055afade..058abc17a92 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @After @@ -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 52863567000..a24ed464a3f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,93 +92,69 @@ 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(); - Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, - "cachedTokenKeys"); + Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, "cachedTokenKeys"); assertThat(cachedTokenKeys).isEqualTo(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(); - Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, - "cachedTokenKeys"); + Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, "cachedTokenKeys"); assertThat(cachedTokenKeys).isEqualTo(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(); - Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, - "cachedTokenKeys"); + Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, "cachedTokenKeys"); assertThat(cachedTokenKeys).isEqualTo(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(); - Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, - "cachedTokenKeys"); + Object cachedTokenKeys = ReflectionTestUtils.getField(this.tokenValidator, "cachedTokenKeys"); assertThat(cachedTokenKeys).isEqualTo(VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -188,13 +164,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(); } @@ -203,35 +177,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(); @@ -240,53 +207,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(); @@ -296,17 +251,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 ba3babeb996..c291f8b78fa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,108 +68,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 + ";charset=UTF-8")); + .andExpect(header().string("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) -> { - 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); }); @@ -177,26 +146,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(); @@ -209,88 +175,66 @@ 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.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") + this.contextRunner.withUserConfiguration(TestConfiguration.class).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") .withUserConfiguration(TestConfiguration.class).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(HealthEndpointAutoConfiguration.class)) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)).run((context) -> { Collection endpoints = context .getBean("cloudFoundryWebEndpointServletHandlerMapping", CloudFoundryWebEndpointServletHandlerMapping.class) .getEndpoints(); ExposableWebEndpoint endpoint = endpoints.iterator().next(); - WebOperation webOperation = endpoint.getOperations().iterator() - .next(); - Object invoker = ReflectionTestUtils.getField(webOperation, - "invoker"); + WebOperation webOperation = endpoint.getOperations().iterator().next(); + 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); } 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 4b2d1a53443..57454ee61f6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/CloudFoundryMvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java index cc107cb5000..f05007faa86 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,92 +68,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); } @@ -162,13 +144,12 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { } private void load(Class configuration, Consumer clientConsumer) { - BiConsumer consumer = (context, - client) -> clientConsumer.accept(client); - AnnotationConfigServletWebServerApplicationContext context = createApplicationContext( - configuration, CloudFoundryMvcConfiguration.class); + BiConsumer consumer = (context, client) -> clientConsumer.accept(client); + AnnotationConfigServletWebServerApplicationContext context = createApplicationContext(configuration, + CloudFoundryMvcConfiguration.class); try { - consumer.accept(context, WebTestClient.bindToServer() - .baseUrl("http://localhost:" + getPort(context)).build()); + consumer.accept(context, + WebTestClient.bindToServer().baseUrl("http://localhost:" + getPort(context)).build()); } finally { context.close(); @@ -187,8 +168,7 @@ public class CloudFoundryMvcWebEndpointIntegrationTests { @Bean public CloudFoundrySecurityInterceptor interceptor() { - return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, - "app-id"); + return new CloudFoundrySecurityInterceptor(tokenValidator, securityService, "app-id"); } @Bean @@ -199,28 +179,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, PathMapper.useEndpointId(), - Collections.emptyList(), Collections.emptyList()); + return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes, + PathMapper.useEndpointId(), 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 391656e2a62..1428c6ff0ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 CloudFoundrySecurityInterceptorTests { @Before 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 aa7e35cc124..746ae6eb609 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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"; @@ -67,31 +66,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 @@ -100,8 +92,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); } @@ -112,8 +103,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); } @@ -121,10 +111,8 @@ public class CloudFoundrySecurityServiceTests { @Test public void getAccessLevelWhenTokenIsNotValidShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withUnauthorizedRequest()); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); + .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); this.securityService.getAccessLevel("my-access-token", "my-app-id"); } @@ -133,26 +121,22 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withStatus(HttpStatus.FORBIDDEN)); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.ACCESS_DENIED)); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.ACCESS_DENIED)); this.securityService.getAccessLevel("my-access-token", "my-app-id"); } @Test public void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); + .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); this.securityService.getAccessLevel("my-access-token", "my-app-id"); } @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" @@ -161,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(); @@ -172,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)); @@ -184,19 +168,17 @@ 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.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); + 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.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); this.securityService.fetchTokenKeys(); } @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); @@ -207,10 +189,8 @@ public class CloudFoundrySecurityServiceTests { @Test public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { - this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); + this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); this.securityService.getUaaUrl(); } 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 fb5bc49c9ca..7080662479b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SkipSslVerificationHttpRequestFactoryTests { String httpsUrl = getHttpsUrl(); SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); - ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, - String.class); + ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); this.thrown.expect(ResourceAccessException.class); this.thrown.expectCause(isSSLHandshakeException()); @@ -75,8 +74,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 19465932e67..392e2cc562d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +81,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); @Before public void setup() { @@ -94,28 +92,23 @@ 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\"]}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_KEY_ID)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_KEY_ID)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @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(); } @@ -125,8 +118,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(); } @@ -136,8 +128,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(); } @@ -148,22 +139,17 @@ 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.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.INVALID_SIGNATURE)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_SIGNATURE)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @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\"]}"; - this.thrown.expect(AuthorizationExceptionMatcher - .withReason(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test @@ -172,10 +158,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\"]}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.TOKEN_EXPIRED)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.TOKEN_EXPIRED)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @Test @@ -184,40 +168,33 @@ 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\"}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_ISSUER)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_ISSUER)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } @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\"]}"; - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.INVALID_AUDIENCE)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + this.thrown.expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_AUDIENCE)); + this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes()))); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { 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/condition/ConditionsReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java index 407d3ab9362..2281e9494bd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,17 @@ 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.run((context) -> assertThat(context) - .hasSingleBean(ConditionsReportEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(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 fbb7cf06bfb..7a8a14abb3c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -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 8ff536d27be..37c53b77e4c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,18 @@ 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") - .run((context) -> assertThat(context) - .hasSingleBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(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 477a92e2f6e..e278aa27f26 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,42 +41,35 @@ 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) - .run(validateTestProperties("******", "654321")); + this.contextRunner.withUserConfiguration(Config.class).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") + this.contextRunner.withUserConfiguration(Config.class) + .withPropertyValues("management.endpoint.configprops.keys-to-sanitize: .*pass.*, property") .run(validateTestProperties("******", "******")); } - 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 f7a248d78a5..26307c20012 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +41,18 @@ public class CouchbaseHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CouchbaseConfiguration.class, - CouchbaseHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + 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(ApplicationHealthIndicator.class)); } @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/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorAutoConfigurationTests.java index ffbe0a2041b..da649fcca8c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +43,13 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ElasticsearchAutoConfiguration.class, - ElasticsearchHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + ElasticsearchHealthIndicatorAutoConfiguration.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)); } @@ -61,18 +58,15 @@ public class ElasticsearchHealthIndicatorAutoConfigurationTests { public void runWhenUsingJestClientShouldCreateIndicator() { this.contextRunner.withUserConfiguration(JestClientConfiguration.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 8b9457f3767..d5de4a8db2b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a19dc66b94e..6dd8c827eab 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ExposeExcludePropertyEndpointFilterTests { public void createWhenPrefixIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Prefix must not be empty"); - new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, - new MockEnvironment(), null); + new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null); } @Test public void createWhenPrefixIsEmptyShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Prefix must not be empty"); - new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, - new MockEnvironment(), ""); + new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), ""); } @Test @@ -126,8 +124,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(); } @@ -157,8 +155,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" }) @@ -168,13 +166,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/ConditionalOnEnabledEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnEnabledEndpointTests.java index d2260e28947..1709757d28c 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 @@ -41,8 +41,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")); } @@ -55,51 +54,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 @@ -128,23 +116,18 @@ 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")); } @@ -163,14 +146,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 4d023a44109..ddc737ea490 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 DefaultEndpointObjectNameFactoryTests { private final MockEnvironment environment = new MockEnvironment(); - private final JmxEndpointProperties properties = new JmxEndpointProperties( - this.environment); + private final JmxEndpointProperties properties = new JmxEndpointProperties(this.environment); private final MBeanServer mBeanServer = mock(MBeanServer.class); @@ -52,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 @@ -78,8 +73,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 @@ -89,28 +83,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.mBeanServer, - this.contextId).getObjectName(endpoint); + return new DefaultEndpointObjectNameFactory(this.properties, 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 bb0543b0cd4..64354596927 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MappingWebEndpointPathMapperTests { @Test public void defaultConfiguration() { - MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( - Collections.emptyMap()); + MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); assertThat(mapper.getRootPath(EndpointId.of("test"))).isEqualTo("test"); } @@ -47,10 +46,8 @@ public class MappingWebEndpointPathMapperTests { @Test public void mixedCaseDefaultConfiguration() { - MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( - Collections.emptyMap()); - assertThat(mapper.getRootPath(EndpointId.of("testEndpoint"))) - .isEqualTo("testEndpoint"); + MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); + assertThat(mapper.getRootPath(EndpointId.of("testEndpoint"))).isEqualTo("testEndpoint"); } @Test 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 a02e6caecbd..4cea8cddf88 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); String basePath = (String) ReflectionTestUtils.getField(bean, "basePath"); assertThat(basePath).isEqualTo("/test/actuator"); }); @@ -62,12 +61,10 @@ public class ServletEndpointManagementContextConfigurationTests { @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); String basePath = (String) ReflectionTestUtils.getField(bean, "basePath"); assertThat(basePath).isEqualTo("/jersey/actuator"); }); @@ -76,8 +73,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 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 86c9e96af0c..2d851196722 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -51,22 +51,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"); }); } @@ -81,23 +76,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)); } } 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 1ab56f3006f..ee6ddc8c15f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 - @Import({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - WebMvcEndpointManagementContextConfiguration.class, - WebFluxEndpointManagementContextConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class }) + @Import({ 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 63b8f041040..d635645432f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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 976f33b399e..9b01f1e57b8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 699e66d146b..92d0b6fdaed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.springframework.test.web.servlet.result.MockMvcResultMatchers. * * @author Andy Wilkinson */ -public class ConditionsReportEndpointDocumentationTests - extends MockMvcEndpointDocumentationTests { +public class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); @@ -65,53 +64,36 @@ public class ConditionsReportEndpointDocumentationTests @Before public void before() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation - .documentationConfiguration(this.restDocumentation).uris()) - .build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(this.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 @@ -119,12 +101,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 50a8b134c58..d547a4b0342 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 e24c45790b1..3a476f82098 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 @@ -58,61 +58,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() { @@ -121,17 +109,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); @@ -142,8 +127,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 @@ -155,18 +139,14 @@ public class EnvironmentEndpointDocumentationTests return new EnvironmentEndpoint(new AbstractEnvironment() { @Override - protected void customizePropertySources( - MutablePropertySources propertySources) { - StreamSupport - .stream(environment.getPropertySources().spliterator(), false) - .filter(this::includedPropertySource) - .forEach(propertySources::addLast); + protected void customizePropertySources(MutablePropertySources propertySources) { + StreamSupport.stream(environment.getPropertySources().spliterator(), false) + .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 27bbbc899c2..7cadac35a34 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -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 1278122abd4..112d8027baa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +51,14 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati @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.")))); } @Configuration @@ -72,8 +68,7 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati @Bean public HealthEndpoint endpoint(Map healthIndicators) { - return new HealthEndpoint(new CompositeHealthIndicator( - new OrderedHealthAggregator(), healthIndicators)); + return new HealthEndpoint(new CompositeHealthIndicator(new OrderedHealthAggregator(), healthIndicators)); } @Bean @@ -82,8 +77,7 @@ public class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentati } @Bean - public DataSourceHealthIndicator dataSourceHealthIndicator( - DataSource dataSource) { + public DataSourceHealthIndicator dataSourceHealthIndicator(DataSource dataSource) { return new DataSourceHealthIndicator(dataSource); } 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 7c3378bfa1d..1c8abca5845 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -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 0ad090be2c9..77c3d7bef69 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 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 9fe01df8fac..2db4932c094 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/LiquibaseEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java index d7ee3430b9f..cbf54aa94cd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 0aebeaa81cd..78442345cb4 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=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 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 08fd96c62b2..26b4b9834c8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 7d6a9ba81a4..4fdf3c51d48 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 @@ -62,10 +62,8 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r * @author Andy Wilkinson */ @RunWith(SpringRunner.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 { @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); @@ -77,92 +75,61 @@ public class MappingsEndpointReactiveDocumentationTests @Before public void webTestClient() { - this.client = WebTestClient - .bindToServer().filter(documentationConfiguration(this.restDocumentation) - .snippets().withDefaults()) + this.client = WebTestClient.bindToServer() + .filter(documentationConfiguration(this.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) { @@ -184,8 +151,7 @@ public class MappingsEndpointReactiveDocumentationTests } @Bean - public MappingsEndpoint mappingsEndpoint( - Collection descriptionProviders, + public MappingsEndpoint mappingsEndpoint(Collection descriptionProviders, ConfigurableApplicationContext context) { return new MappingsEndpoint(descriptionProviders, context); } @@ -205,10 +171,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 db3f7c3a3f6..0a94616cbae 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 @@ -63,8 +63,7 @@ import static org.springframework.restdocs.webtestclient.WebTestClientRestDocume */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class MappingsEndpointServletDocumentationTests - extends AbstractEndpointDocumentationTests { +public class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocumentationTests { @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); @@ -76,115 +75,76 @@ public class MappingsEndpointServletDocumentationTests @Before public void webTestClient() { - this.client = WebTestClient.bindToServer() - .filter(documentationConfiguration(this.restDocumentation)) + this.client = WebTestClient.bindToServer().filter(documentationConfiguration(this.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) { @@ -216,8 +176,7 @@ public class MappingsEndpointServletDocumentationTests } @Bean - public MappingsEndpoint mappingsEndpoint( - Collection descriptionProviders, + public MappingsEndpoint mappingsEndpoint(Collection descriptionProviders, ConfigurableApplicationContext context) { return new MappingsEndpoint(descriptionProviders, context); } @@ -232,10 +191,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 7b9f59892a6..f11b0fb04e8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 0afd69584d2..44b620bd1e5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.WebApplicationContext; */ @RunWith(SpringRunner.class) @SpringBootTest -public abstract class MockMvcEndpointDocumentationTests - extends AbstractEndpointDocumentationTests { +public abstract class MockMvcEndpointDocumentationTests extends AbstractEndpointDocumentationTests { @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); @@ -51,9 +50,7 @@ public abstract class MockMvcEndpointDocumentationTests @Before public void before() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation - .documentationConfiguration(this.restDocumentation).uris()) - .build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(this.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 ea3412d34b5..03443fb40fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -53,15 +51,14 @@ public class PrometheusScrapeEndpointDocumentationTests @Bean public PrometheusScrapeEndpoint endpoint() { CollectorRegistry collectorRegistry = new CollectorRegistry(true); - PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry( - new PrometheusConfig() { + PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(new PrometheusConfig() { - @Override - public String get(String key) { - return null; - } + @Override + public String get(String key) { + return null; + } - }, collectorRegistry, Clock.SYSTEM); + }, 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 94a3264668f..067aae1b821 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,45 +43,36 @@ 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.[].")))); + 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.[].")))); } 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 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 e8091162874..afa81df482d 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 @@ -90,17 +83,14 @@ public class SessionsEndpointDocumentationTests sessions.put(sessionOne.getId(), sessionOne); sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionThree.getId(), sessionThree); - given(this.sessionRepository.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "alice")) + given(this.sessionRepository + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "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 @@ -110,26 +100,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); @@ -141,8 +127,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 a83b04ad321..cbe69b789d9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 cc4cb764af2..4d2029d17a4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,156 +37,104 @@ 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 { 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."), + .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."), + + "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.") - .optional(), - fieldWithPath("threads.[].lockInfo").description( - "Object for which the thread is blocked " - + "waiting.") + 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(), + fieldWithPath("threads.[].lockInfo") + .description("Object for which the thread is blocked " + "waiting.").optional(), fieldWithPath("threads.[].lockInfo.className") - .description( - "Fully qualified class name of the lock" - + " object.") - .optional(), + .description("Fully qualified class name of the lock" + " object.").optional(), fieldWithPath("threads.[].lockInfo.identityHashCode") - .description( - "Identity hash code of the lock object.") - .optional(), - fieldWithPath("threads.[].lockedMonitors").description( - "Monitors locked by this thread, if any"), + .description("Identity hash code of the lock object.").optional(), + 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.[].identifyHashCode") - .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.[].identifyHashCode").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")))); } @Configuration 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 fb0b1e1c65f..e9c041637b4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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() { @@ -51,8 +50,7 @@ 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 @@ -62,24 +60,20 @@ public class EnvironmentEndpointAutoConfigurationTests { .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 1a6318eeed3..4080500b913 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +36,18 @@ 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)) .withUserConfiguration(FlywayConfiguration.class); @Test public void runShouldHaveEndpointBean() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); + this.contextRunner.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)); } @Configuration 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 9baebff022c..fafcd5c9e24 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,32 +45,27 @@ import static org.mockito.Mockito.verify; public class HealthEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HealthEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)); @Test public void healthEndpointShowDetailsDefault() { - this.contextRunner - .withUserConfiguration(ReactiveHealthIndicatorConfiguration.class) - .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.withUserConfiguration(ReactiveHealthIndicatorConfiguration.class).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") - .withUserConfiguration(ReactiveHealthIndicatorConfiguration.class) - .run((context) -> { - ReactiveHealthIndicator indicator = context.getBean( - "reactiveHealthIndicator", ReactiveHealthIndicator.class); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") + .withUserConfiguration(ReactiveHealthIndicatorConfiguration.class).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); @@ -81,21 +76,17 @@ public class HealthEndpointAutoConfigurationTests { @Test public void healthEndpointMergeRegularAndReactive() { - this.contextRunner - .withPropertyValues("management.endpoint.health.show-details=always") - .withUserConfiguration(HealthIndicatorConfiguration.class, - ReactiveHealthIndicatorConfiguration.class) + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always") + .withUserConfiguration(HealthIndicatorConfiguration.class, ReactiveHealthIndicatorConfiguration.class) .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 1c037a3bec3..8816c4f10af 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,155 +41,113 @@ import static org.mockito.Mockito.mock; */ public class HealthEndpointWebExtensionTests { - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HealthIndicatorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class)); + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().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.getHealth(mock(SecurityContext.class)).getBody() - .getDetails()).isEmpty(); + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertThat(extension.getHealth(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.getHealth(securityContext).getBody().getDetails()) - .isEmpty(); + assertThat(extension.getHealth(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.getHealth(securityContext).getBody().getDetails()) - .isNotEmpty(); + given(securityContext.getPrincipal()).willReturn(mock(Principal.class)); + assertThat(extension.getHealth(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.getHealth(null).getBody().getDetails()) - .isNotEmpty(); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always").run((context) -> { + HealthEndpointWebExtension extension = context.getBean(HealthEndpointWebExtension.class); + assertThat(extension.getHealth(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.getHealth(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.getHealth(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.getHealth(securityContext).getBody().getDetails()) - .isEmpty(); + assertThat(extension.getHealth(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.getHealth(securityContext).getBody().getDetails()) - .isNotEmpty(); + assertThat(extension.getHealth(securityContext).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) -> { - 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.getHealth(securityContext).getBody().getDetails()) - .isNotEmpty(); + assertThat(extension.getHealth(securityContext).getBody().getDetails()).isNotEmpty(); }); } 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 eef5da279b8..ebded1e0da1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 6aafbe13a30..35d96729089 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,178 +48,142 @@ 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(); }); } 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 9ec266e447f..9923bcdd75c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +38,19 @@ import static org.mockito.Mockito.mock; public class InfluxDbHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(InfluxDbConfiguration.class).withConfiguration( - AutoConfigurations.of(InfluxDbHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withUserConfiguration(InfluxDbConfiguration.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 e4c669fb1ea..5c5ded5b7ad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 31b6761fd6a..182b876ec26 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/integrationtest/ControllerEndpointWebFluxIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java index ad5caa82e0b..f8d10d20f2b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 cc4153dcdcf..810188caa95 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 AnnotationConfigWebApplicationContext(); 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 9fa46c8a52b..2c7cd08bba5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,33 +46,23 @@ public class JerseyEndpointIntegrationTests { @Test public void linksAreProvidedToAllEndpointTypes() throws Exception { - 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(EndpointsConfiguration.class) - .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(EndpointsConfiguration.class) + .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 299a3f95816..b0f52406152 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,51 +45,39 @@ 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, - HttpTraceAutoConfiguration.class)) - .withConfiguration( - AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, + JmxEndpointAutoConfiguration.class, HttpTraceAutoConfiguration.class)) + .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(); @@ -110,14 +98,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); } } @@ -127,8 +113,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 be5d17cf7b1..5e664e65f46 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 @@ -68,8 +68,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\""); @@ -77,36 +76,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 @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 { @@ -115,9 +111,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 55d092404ea..1774469fd2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,40 +57,34 @@ 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, - ElasticsearchAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class, JestAutoConfiguration.class, - SolrRepositoriesAutoConfiguration.class, SolrAutoConfiguration.class, - RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, - MetricsAutoConfiguration.class }) + ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, JestAutoConfiguration.class, + SolrRepositoriesAutoConfiguration.class, SolrAutoConfiguration.class, RedisAutoConfiguration.class, + RedisRepositoriesAutoConfiguration.class, MetricsAutoConfiguration.class }) @SpringBootConfiguration 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 ef5a6951d0b..a64465bc916 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,123 +47,89 @@ public class WebFluxEndpointCorsIntegrationTests { @Before public void createContext() { this.context = new AnnotationConfigReactiveWebApplicationContext(); - this.context.register(JacksonAutoConfiguration.class, - CodecsAutoConfiguration.class, WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, - BeansEndpointAutoConfiguration.class); - TestPropertyValues.of("management.endpoints.web.exposure.include:*") - .applyTo(this.context); + this.context.register(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class); + TestPropertyValues.of("management.endpoints.web.exposure.include:*").applyTo(this.context); } @Test public void corsIsDisabledByDefault() { - createWebTestClient().options().uri("/actuator/beans") - .header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange() - .expectStatus().isForbidden().expectHeader() - .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN); + createWebTestClient().options().uri("/actuator/beans").header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus().isForbidden() + .expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN); } @Test public void settingAllowedOriginsEnablesCors() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org") - .applyTo(this.context); - createWebTestClient().options().uri("/actuator/beans") - .header("Origin", "test.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange() - .expectStatus().isForbidden(); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org").applyTo(this.context); + createWebTestClient().options().uri("/actuator/beans").header("Origin", "test.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus().isForbidden(); performAcceptedCorsRequest("/actuator/beans"); } @Test public void maxAgeDefaultsTo30Minutes() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org") - .applyTo(this.context); - performAcceptedCorsRequest("/actuator/beans").expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org").applyTo(this.context); + performAcceptedCorsRequest("/actuator/beans").expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, + "1800"); } @Test public void maxAgeCanBeConfigured() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.max-age: 2400") - .applyTo(this.context); - performAcceptedCorsRequest("/actuator/beans").expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.max-age: 2400").applyTo(this.context); + performAcceptedCorsRequest("/actuator/beans").expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, + "2400"); } @Test public void requestsWithDisallowedHeadersAreRejected() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org") - .applyTo(this.context); - createWebTestClient().options().uri("/actuator/beans") - .header("Origin", "spring.example.org") + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org").applyTo(this.context); + createWebTestClient().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(); + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus().isForbidden(); } @Test public void allowedHeadersCanBeConfigured() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .applyTo(this.context); - createWebTestClient().options().uri("/actuator/beans") - .header("Origin", "spring.example.org") + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo").applyTo(this.context); + createWebTestClient().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"); + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus().isOk() + .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"); } @Test public void requestsWithDisallowedMethodsAreRejected() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org") - .applyTo(this.context); - createWebTestClient().options().uri("/actuator/beans") - .header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH").exchange() - .expectStatus().isForbidden(); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org").applyTo(this.context); + createWebTestClient().options().uri("/actuator/beans").header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH").exchange().expectStatus().isForbidden(); } @Test public void allowedMethodsCanBeConfigured() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .applyTo(this.context); - createWebTestClient().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"); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-methods:GET,HEAD").applyTo(this.context); + createWebTestClient().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() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:true") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:true").applyTo(this.context); performAcceptedCorsRequest("/actuator/beans").expectHeader() .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } @Test public void credentialsCanBeDisabled() { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:false") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:false").applyTo(this.context); performAcceptedCorsRequest("/actuator/beans").expectHeader() .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS); } @@ -175,12 +141,9 @@ public class WebFluxEndpointCorsIntegrationTests { } private WebTestClient.ResponseSpec performAcceptedCorsRequest(String url) { - return createWebTestClient().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(); + return createWebTestClient().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 51578634553..e6daa3e6c01 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 a4d0b430e02..d7a35d5e5d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +55,12 @@ public class WebMvcEndpointCorsIntegrationTests { public void createContext() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); - this.context.register(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + this.context.register(JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class); - TestPropertyValues.of("management.endpoints.web.exposure.include:*") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.exposure.include:*").applyTo(this.context); } @Test @@ -71,111 +68,80 @@ public class WebMvcEndpointCorsIntegrationTests { createMockMvc() .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() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com") - .applyTo(this.context); - createMockMvc() - .perform(options("/actuator/beans").header("Origin", "bar.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com").applyTo(this.context); + createMockMvc().perform(options("/actuator/beans").header("Origin", "bar.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")).andExpect(status().isForbidden()); performAcceptedCorsRequest(); } @Test public void maxAgeDefaultsTo30Minutes() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com") - .applyTo(this.context); - performAcceptedCorsRequest() - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com").applyTo(this.context); + performAcceptedCorsRequest().andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); } @Test public void maxAgeCanBeConfigured() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.max-age: 2400") - .applyTo(this.context); - performAcceptedCorsRequest() - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.max-age: 2400").applyTo(this.context); + performAcceptedCorsRequest().andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")); } @Test public void requestsWithDisallowedHeadersAreRejected() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com") - .applyTo(this.context); - createMockMvc() - .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()); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com").applyTo(this.context); + createMockMvc().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()); } @Test public void allowedHeadersCanBeConfigured() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo").applyTo(this.context); createMockMvc() .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")); + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")); } @Test public void requestsWithDisallowedMethodsAreRejected() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com") - .applyTo(this.context); - createMockMvc() - .perform(options("/actuator/health") - .header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) - .andExpect(status().isForbidden()); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com").applyTo(this.context); + createMockMvc().perform(options("/actuator/health").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")).andExpect(status().isForbidden()); } @Test public void allowedMethodsCanBeConfigured() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .applyTo(this.context); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allowed-methods:GET,HEAD").applyTo(this.context); createMockMvc() - .perform(options("/actuator/beans") - .header(HttpHeaders.ORIGIN, "foo.example.com") + .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")); + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")); } @Test public void credentialsCanBeAllowed() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allow-credentials:true") - .applyTo(this.context); - performAcceptedCorsRequest().andExpect( - header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allow-credentials:true").applyTo(this.context); + performAcceptedCorsRequest().andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); } @Test public void credentialsCanBeDisabled() throws Exception { - TestPropertyValues - .of("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allow-credentials:false") - .applyTo(this.context); - performAcceptedCorsRequest().andExpect( - header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + TestPropertyValues.of("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allow-credentials:false").applyTo(this.context); + performAcceptedCorsRequest().andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); } private MockMvc createMockMvc() { @@ -191,8 +157,7 @@ public class WebMvcEndpointCorsIntegrationTests { return createMockMvc() .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 94a01c0b203..c7bf9f33aec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +61,16 @@ 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, + 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)) - .withConfiguration( - AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) - .withUserConfiguration(CustomMvcEndpoint.class, - CustomServletEndpoint.class) + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) + .withUserConfiguration(CustomMvcEndpoint.class, CustomServletEndpoint.class) .withPropertyValues("server.port:0"); @Test @@ -144,8 +137,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(); @@ -164,17 +156,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; } @@ -182,8 +171,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 1771cefd7e9..c6c02496465 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +83,14 @@ public class WebMvcEndpointIntegrationTests { this.context = new AnnotationConfigWebApplicationContext(); 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 AnnotationConfigWebApplicationContext(); 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 AnnotationConfigWebApplicationContext(); 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 AnnotationConfigWebApplicationContext(); 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 53923c02f1f..589b91a5877 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 c971c3d7629..5d5ed4cc737 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 b72704ec3a2..7a4e7c8fde5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,49 +50,41 @@ 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.run((context) -> { ExposableServletEndpoint endpoint = getEndpoint(context); assertThat(endpoint.getRootPath()).isEqualTo("jolokia"); - Object servlet = ReflectionTestUtils.getField(endpoint.getEndpointServlet(), - "servlet"); + Object servlet = ReflectionTestUtils.getField(endpoint.getEndpointServlet(), "servlet"); assertThat(servlet).isInstanceOf(AgentServlet.class); }); } @Test public void jolokiaServletWhenDisabledShouldNotBeDiscovered() { - this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false") - .run((context) -> { - Collection endpoints = context - .getBean(ServletEndpointsSupplier.class).getEndpoints(); - assertThat(endpoints).isEmpty(); - }); + this.contextRunner.withPropertyValues("management.endpoint.jolokia.enabled=false").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") - .run((context) -> { - ExposableServletEndpoint endpoint = getEndpoint(context); - assertThat(endpoint.getEndpointServlet()).extracting("initParameters") - .containsOnly(Collections.singletonMap("debug", "true")); - }); + this.contextRunner.withPropertyValues("management.endpoint.jolokia.config.debug=true").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(); } @@ -100,10 +92,9 @@ public class JolokiaEndpointAutoConfigurationTests { static class TestConfiguration { @Bean - public ServletEndpointDiscoverer servletEndpointDiscoverer( - ApplicationContext applicationContext) { - return new ServletEndpointDiscoverer(applicationContext, - PathMapper.useEndpointId(), Collections.emptyList()); + public ServletEndpointDiscoverer servletEndpointDiscoverer(ApplicationContext applicationContext) { + return new ServletEndpointDiscoverer(applicationContext, PathMapper.useEndpointId(), + 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 2d29d9e4467..ee4dcb56b8a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import static org.mockito.Mockito.mock; public class LdapHealthIndicatorAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(LdapConfiguration.class).withConfiguration( - AutoConfigurations.of(LdapHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withUserConfiguration(LdapConfiguration.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 2655a57d306..f550f5cac10 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,46 +38,37 @@ 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.withUserConfiguration(LiquibaseConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); + this.contextRunner.withUserConfiguration(LiquibaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(LiquibaseConfiguration.class) .withPropertyValues("management.endpoint.liquibase.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LiquibaseEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test public void disablesCloseOfDataSourceWhenEndpointIsEnabled() { - this.contextRunner - .withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(LiquibaseEndpoint.class); - assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) - .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", - false); - }); + this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(LiquibaseEndpoint.class); + assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) + .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 +92,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 aec1c9a27a9..7e21dcc7936 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,48 +49,40 @@ public class LogFileWebEndpointAutoConfigurationTests { @Test public void logFileWebEndpointIsAutoConfiguredWhenLoggingFileIsSet() { - this.contextRunner.withPropertyValues("logging.file:test.log").run( - (context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + this.contextRunner.withPropertyValues("logging.file:test.log") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void logFileWebEndpointIsAutoConfiguredWhenLoggingPathIsSet() { - this.contextRunner.withPropertyValues("logging.path:test/logs").run( - (context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + this.contextRunner.withPropertyValues("logging.path:test/logs") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { - this.contextRunner - .withPropertyValues( - "management.endpoint.logfile.external-file:external.log") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.logfile.external-file:external.log") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void logFileWebEndpointCanBeDisabled() { - this.contextRunner - .withPropertyValues("logging.file:test.log", - "management.endpoint.logfile.enabled:false") - .run((context) -> assertThat(context) - .hasSingleBean(LogFileWebEndpoint.class)); + this.contextRunner.withPropertyValues("logging.file:test.log", "management.endpoint.logfile.enabled:false") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test public void logFileWebEndpointUsesConfiguredExternalFile() throws IOException { File file = this.temp.newFile("logfile"); FileCopyUtils.copy("--TEST--".getBytes(), file); - this.contextRunner.withPropertyValues( - "management.endpoint.logfile.external-file:" + file.getAbsolutePath()) + this.contextRunner.withPropertyValues("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 d296b0356e9..c0b0076ad9d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,30 +36,24 @@ 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.run( - (context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); + this.contextRunner.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 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 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 decf60e50f2..0cf3fcb7a84 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 9f4ec64480a..951cd59e32e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a109e08ad4b..2e3dcd5ac9c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +32,17 @@ 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.run( - (context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.threaddump.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ThreadDumpEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.threaddump.enabled:false") + .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 f2b50d7dc3f..9b8377943fb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 dad5d9acb14..aa6daf58bc9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +32,13 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; */ public class MeterRegistryConfigurerIntegrationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun + .limitedTo(AtlasMetricsExportAutoConfiguration.class, PrometheusMetricsExportAutoConfiguration.class)); @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()); 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 4a356a80a21..9b7b0c7af50 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 class MeterRegistryConfigurerTests { @Test public void configureWhenCompositeShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + false); CompositeMeterRegistry composite = new CompositeMeterRegistry(); configurer.configure(composite); verify(this.mockCustomizer).customize(composite); @@ -84,8 +84,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyCustomizer() { this.customizers.add(this.mockCustomizer); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + false); configurer.configure(this.mockRegistry); verify(this.mockCustomizer).customize(this.mockRegistry); } @@ -93,8 +93,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyFilter() { this.filters.add(this.mockFilter); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + false); configurer.configure(this.mockRegistry); verify(this.mockConfig).meterFilter(this.mockFilter); } @@ -102,8 +102,8 @@ public class MeterRegistryConfigurerTests { @Test public void configureShouldApplyBinder() { this.binders.add(this.mockBinder); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + false); configurer.configure(this.mockRegistry); verify(this.mockBinder).bindTo(this.mockRegistry); } @@ -113,8 +113,8 @@ public class MeterRegistryConfigurerTests { this.customizers.add(this.mockCustomizer); this.filters.add(this.mockFilter); this.binders.add(this.mockBinder); - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + false); configurer.configure(this.mockRegistry); InOrder ordered = inOrder(this.mockBinder, this.mockConfig, this.mockCustomizer); ordered.verify(this.mockCustomizer).customize(this.mockRegistry); @@ -124,12 +124,11 @@ public class MeterRegistryConfigurerTests { @Test public void configureWhenAddToGlobalRegistryShouldAddToGlobalRegistry() { - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, true); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + true); try { configurer.configure(this.mockRegistry); - assertThat(Metrics.globalRegistry.getRegistries()) - .contains(this.mockRegistry); + assertThat(Metrics.globalRegistry.getRegistries()).contains(this.mockRegistry); } finally { Metrics.removeRegistry(this.mockRegistry); @@ -138,11 +137,10 @@ public class MeterRegistryConfigurerTests { @Test public void configureWhenNotAddToGlobalRegistryShouldAddToGlobalRegistry() { - MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, - this.filters, this.customizers, false); + MeterRegistryConfigurer configurer = new MeterRegistryConfigurer(this.binders, this.filters, this.customizers, + false); configurer.configure(this.mockRegistry); - assertThat(Metrics.globalRegistry.getRegistries()) - .doesNotContain(this.mockRegistry); + assertThat(Metrics.globalRegistry.getRegistries()).doesNotContain(this.mockRegistry); } } 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 c8391dbc420..9e2ab0e4681 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,42 +38,33 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MeterRegistryCustomizerTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun + .limitedTo(AtlasMetricsExportAutoConfiguration.class, PrometheusMetricsExportAutoConfiguration.class)); @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 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 b35f36c1a71..99c64dd629d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +42,21 @@ 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 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 @@ -73,8 +70,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)); } @@ -91,10 +87,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 e3b78bd9b84..48477c33e6f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,184 +59,144 @@ 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); - List filters = (List) ReflectionTestUtils - .getField(meterRegistry, "filters"); - assertThat(filters).hasSize(3); - assertThat(filters.get(0).accept((Meter.Id) null)) - .isEqualTo(MeterFilterReply.DENY); - assertThat(filters.get(1)).isInstanceOf(PropertiesMeterFilter.class); - assertThat(filters.get(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); + List filters = (List) ReflectionTestUtils.getField(meterRegistry, "filters"); + assertThat(filters).hasSize(3); + assertThat(filters.get(0).accept((Meter.Id) null)).isEqualTo(MeterFilterReply.DENY); + assertThat(filters.get(1)).isInstanceOf(PropertiesMeterFilter.class); + assertThat(filters.get(2).accept((Meter.Id) null)).isEqualTo(MeterFilterReply.ACCEPT); + verify((MeterBinder) context.getBean("meterBinder")).bindTo(meterRegistry); + verify(context.getBean(MeterRegistryCustomizer.class)).customize(meterRegistry); + }); } @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 allowsJvmMetricsToBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.binders.jvm.enabled=false") + this.contextRunner.withPropertyValues("management.metrics.binders.jvm.enabled=false") .run((context) -> assertThat(context).doesNotHaveBean(JvmGcMetrics.class) - .doesNotHaveBean(JvmMemoryMetrics.class) - .doesNotHaveBean(JvmThreadMetrics.class) + .doesNotHaveBean(JvmMemoryMetrics.class).doesNotHaveBean(JvmThreadMetrics.class) .doesNotHaveBean(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")); } @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 allowsLogbackMetricsToBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.binders.logback.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(LogbackMetrics.class)); + this.contextRunner.withPropertyValues("management.metrics.binders.logback.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(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")); } @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 allowsUptimeMetricsToBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.binders.uptime.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(UptimeMetrics.class)); + this.contextRunner.withPropertyValues("management.metrics.binders.uptime.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(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 allowsProcessorMetricsToBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.binders.processor.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(ProcessorMetrics.class)); + this.contextRunner.withPropertyValues("management.metrics.binders.processor.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(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 allowsFileDescriptorMetricsToBeDisabled() { - this.contextRunner - .withPropertyValues("management.metrics.binders.files.enabled=false") - .run((context) -> assertThat(context) - .doesNotHaveBean(FileDescriptorMetrics.class)); + this.contextRunner.withPropertyValues("management.metrics.binders.files.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(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/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 48149f43c01..2fbe9dc53a3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 7c3eb5e4f0e..34b1270e858 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,112 +56,96 @@ public class PropertiesMeterFilterTests { @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 @@ -169,8 +153,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 @@ -178,119 +162,107 @@ 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); } @Test public void configureWhenAllSlaSetShouldSetSlaToValue() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("distribution.sla.all=1,2,3")); - assertThat(filter.configure(createMeterId("spring.boot"), - DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.sla.all=1,2,3")); + assertThat( + filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) .containsExactly(1000000, 2000000, 3000000); } @Test public void configureWhenSlaDurationShouldOnlyApplyToTimer() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("distribution.sla.all=1ms,2ms,3ms")); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.sla.all=1ms,2ms,3ms")); Meter.Id timer = createMeterId("spring.boot", Meter.Type.TIMER); Meter.Id summary = createMeterId("spring.boot", Meter.Type.DISTRIBUTION_SUMMARY); Meter.Id counter = createMeterId("spring.boot", Meter.Type.COUNTER); - assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT) - .getSlaBoundaries()).containsExactly(1000000, 2000000, 3000000); - assertThat(filter.configure(summary, DistributionStatisticConfig.DEFAULT) - .getSlaBoundaries()).isNullOrEmpty(); - assertThat(filter.configure(counter, DistributionStatisticConfig.DEFAULT) - .getSlaBoundaries()).isNullOrEmpty(); + assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) + .containsExactly(1000000, 2000000, 3000000); + assertThat(filter.configure(summary, DistributionStatisticConfig.DEFAULT).getSlaBoundaries()).isNullOrEmpty(); + assertThat(filter.configure(counter, DistributionStatisticConfig.DEFAULT).getSlaBoundaries()).isNullOrEmpty(); } @Test public void configureWhenSlaLongShouldOnlyApplyToTimerAndDistributionSummary() { - PropertiesMeterFilter filter = new PropertiesMeterFilter( - createProperties("distribution.sla.all=1,2,3")); + PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.sla.all=1,2,3")); Meter.Id timer = createMeterId("spring.boot", Meter.Type.TIMER); Meter.Id summary = createMeterId("spring.boot", Meter.Type.DISTRIBUTION_SUMMARY); Meter.Id counter = createMeterId("spring.boot", Meter.Type.COUNTER); - assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT) - .getSlaBoundaries()).containsExactly(1000000, 2000000, 3000000); - assertThat(filter.configure(summary, DistributionStatisticConfig.DEFAULT) - .getSlaBoundaries()).containsExactly(1, 2, 3); - assertThat(filter.configure(counter, DistributionStatisticConfig.DEFAULT) - .getSlaBoundaries()).isNullOrEmpty(); + assertThat(filter.configure(timer, DistributionStatisticConfig.DEFAULT).getSlaBoundaries()) + .containsExactly(1000000, 2000000, 3000000); + assertThat(filter.configure(summary, DistributionStatisticConfig.DEFAULT).getSlaBoundaries()).containsExactly(1, + 2, 3); + assertThat(filter.configure(counter, DistributionStatisticConfig.DEFAULT).getSlaBoundaries()).isNullOrEmpty(); } private Id createMeterId(String name) { @@ -300,16 +272,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 344eb8da4fb..5097835a9f3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ServiceLevelAgreementBoundaryTests { @Test public void getValueForDistributionSummaryWhenFromDurationStringShouldReturnNull() { - ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary - .valueOf("123ms"); + ServiceLevelAgreementBoundary sla = ServiceLevelAgreementBoundary.valueOf("123ms"); assertThat(sla.getValue(Type.DISTRIBUTION_SUMMARY)).isNull(); } @@ -66,8 +65,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); } @@ -84,11 +82,9 @@ public class ServiceLevelAgreementBoundaryTests { public void valueOfShouldWorkInBinder() { MockEnvironment environment = new MockEnvironment(); TestPropertyValues.of("duration=10ms", "long=20").applyTo(environment); - assertThat(Binder.get(environment) - .bind("duration", Bindable.of(ServiceLevelAgreementBoundary.class)).get() + assertThat(Binder.get(environment).bind("duration", Bindable.of(ServiceLevelAgreementBoundary.class)).get() .getValue(Type.TIMER)).isEqualTo(10000000); - assertThat(Binder.get(environment) - .bind("long", Bindable.of(ServiceLevelAgreementBoundary.class)).get() + assertThat(Binder.get(environment).bind("long", Bindable.of(ServiceLevelAgreementBoundary.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/amqp/RabbitMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java index e168a9c1b67..444a7d31f83 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 RabbitMetricsAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()) + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @Test @@ -47,11 +46,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 86d2a4a0437..4e0f3622945 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,40 +35,36 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class CacheMetricsAutoConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withUserConfiguration(CachingConfiguration.class) + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withUserConfiguration(CachingConfiguration.class) .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.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/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 303a593e96e..ddfbfa10a3e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 27971cb77c8..f88ee006110 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 5666a0619eb..70662421c66 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/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 9e44e8191f2..c3835b6ee5c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 408f0abe731..a43e8dd563d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 1a57d8634ed..fa897be1204 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 7c6b2895af0..ece1d17d84a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +39,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 f2a6af7c264..6d9b6c2a66c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 706fcbdb041..e106fbb7604 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 bcabbff0b65..c2364026139 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,92 +40,71 @@ 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) - .run((context) -> assertThat(context) - .hasSingleBean(PrometheusScrapeEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test public void scrapeEndpointCanBeDisabled() { - this.contextRunner - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class)) + this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) .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)); } @Configuration @@ -161,8 +140,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); } @@ -184,8 +163,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 67dc389ddb8..7f49295fb71 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 1df357e16e0..19aa0db827b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 d5a3228ae85..b0b9d91ada3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 a416882f9ed..95679a69c24 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 8444b3c6837..7a4c1e6aa69 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 6e10e9f5824..aa2e2e2eee2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 dc9746291e6..0b3ddc09855 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/test/MetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java index 90ae2030086..4538ae8a377 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 @@ -80,8 +80,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat * @author Jon Schneider */ @RunWith(SpringRunner.class) -@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 { @@ -100,29 +99,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 @@ -131,23 +124,19 @@ 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 - @ImportAutoConfiguration({ MetricsAutoConfiguration.class, - RabbitMetricsAutoConfiguration.class, CacheMetricsAutoConfiguration.class, - DataSourcePoolMetricsAutoConfiguration.class, - RestTemplateMetricsAutoConfiguration.class, - WebFluxMetricsAutoConfiguration.class, WebMvcMetricsAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - RestTemplateAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, + @ImportAutoConfiguration({ MetricsAutoConfiguration.class, RabbitMetricsAutoConfiguration.class, + CacheMetricsAutoConfiguration.class, DataSourcePoolMetricsAutoConfiguration.class, + RestTemplateMetricsAutoConfiguration.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 c59b5189423..30a438ccc7f 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. @@ -71,12 +71,11 @@ public final class MetricsRun { EXPORT_AUTO_CONFIGURATIONS = Collections.unmodifiableSet(implementations); } - private static final AutoConfigurations AUTO_CONFIGURATIONS = AutoConfigurations.of( - MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class, - RabbitMetricsAutoConfiguration.class, CacheMetricsAutoConfiguration.class, - DataSourcePoolMetricsAutoConfiguration.class, - RestTemplateMetricsAutoConfiguration.class, - WebFluxMetricsAutoConfiguration.class, WebMvcMetricsAutoConfiguration.class); + private static final AutoConfigurations AUTO_CONFIGURATIONS = AutoConfigurations.of(MetricsAutoConfiguration.class, + CompositeMeterRegistryAutoConfiguration.class, RabbitMetricsAutoConfiguration.class, + CacheMetricsAutoConfiguration.class, DataSourcePoolMetricsAutoConfiguration.class, + RestTemplateMetricsAutoConfiguration.class, WebFluxMetricsAutoConfiguration.class, + WebMvcMetricsAutoConfiguration.class); private MetricsRun() { } @@ -107,8 +106,7 @@ public final class MetricsRun { Assert.state(EXPORT_AUTO_CONFIGURATIONS.contains(configuration), () -> "Unknown export auto-configuration " + configuration.getName()); } - return contextRunner - .withPropertyValues("management.metrics.use-global-registry=false") + return 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/RestTemplateMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfigurationTests.java index a997072c5a6..ce7050220ba 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/client/RestTemplateMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat */ public class RestTemplateMetricsAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration( - AutoConfigurations.of(RestTemplateAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); @Rule public OutputCapture out = new OutputCapture(); @@ -55,8 +54,7 @@ public class RestTemplateMetricsAutoConfigurationTests { public void restTemplateCreatedWithBuilderIsInstrumented() { this.contextRunner.run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); - RestTemplate restTemplate = context.getBean(RestTemplateBuilder.class) - .build(); + RestTemplate restTemplate = context.getBean(RestTemplateBuilder.class).build(); validateRestTemplate(restTemplate, registry); }); } @@ -66,8 +64,7 @@ public class RestTemplateMetricsAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(MetricsRestTemplateCustomizer.class); RestTemplate restTemplate = new RestTemplateBuilder() - .customizers(context.getBean(MetricsRestTemplateCustomizer.class)) - .build(); + .customizers(context.getBean(MetricsRestTemplateCustomizer.class)).build(); MeterRegistry registry = context.getBean(MeterRegistry.class); validateRestTemplate(restTemplate, registry); }); @@ -75,34 +72,27 @@ public class RestTemplateMetricsAutoConfigurationTests { @Test public void afterMaxUrisReachedFurtherUrisAreDenied() { - 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(this.out.toString()).contains( - "Reached the maximum number of URI tags for 'http.client.requests'."); - assertThat(this.out.toString()).contains( - "Are you using 'uriVariables' on RestTemplate calls?"); - }); + 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(this.out.toString()) + .contains("Reached the maximum number of URI tags for 'http.client.requests'."); + assertThat(this.out.toString()).contains("Are you using 'uriVariables' on RestTemplate calls?"); + }); } @Test public void shouldNotDenyNorLogIfMaxUrisIsNotReached() { - 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(this.out.toString()).doesNotContain( - "Reached the maximum number of URI tags for 'http.client.requests'."); - assertThat(this.out.toString()).doesNotContain( - "Are you using 'uriVariables' on RestTemplate calls?"); - }); + 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(this.out.toString()) + .doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'."); + assertThat(this.out.toString()).doesNotContain("Are you using 'uriVariables' on RestTemplate calls?"); + }); } - 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); @@ -119,8 +109,7 @@ public class RestTemplateMetricsAutoConfigurationTests { MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); server.expect(requestTo("/test")).andRespond(withStatus(HttpStatus.OK)); assertThat(registry.find("http.client.requests").meter()).isNull(); - assertThat(restTemplate.getForEntity("/test", Void.class).getStatusCode()) - .isEqualTo(HttpStatus.OK); + assertThat(restTemplate.getForEntity("/test", Void.class).getStatusCode()).isEqualTo(HttpStatus.OK); registry.get("http.client.requests").meter(); } 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 9b359c3feba..fd281f17e1b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 WebFluxMetricsAutoConfigurationTests { private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, - WebFluxMetricsAutoConfiguration.class)); + SimpleMetricsExportAutoConfiguration.class, WebFluxMetricsAutoConfiguration.class)); @Rule public OutputCapture output = new OutputCapture(); @@ -65,56 +64,46 @@ 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() { - 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(this.output.toString()) - .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() { - 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(this.output.toString()).doesNotContain( - "Reached the maximum number of URI tags for 'http.server.requests'"); + assertThat(this.output.toString()) + .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.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 3433c32b7b4..84d057ae6ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,33 +62,30 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class WebMvcMetricsAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebMvcMetricsAutoConfiguration.class)); @Rule public OutputCapture output = new OutputCapture(); @Test public void backsOffWhenMeterRegistryIsMissing() { - this.contextRunner.run((context) -> assertThat(context) - .doesNotHaveBean(WebMvcMetricsAutoConfiguration.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(WebMvcMetricsAutoConfiguration.class)); } @Test public void definesTagsProviderAndFilterWhenMeterRegistryIsPresent() { - this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(DefaultWebMvcTagsProvider.class); - assertThat(context).hasSingleBean(FilterRegistrationBean.class); - assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) - .isInstanceOf(WebMvcMetricsFilter.class); - }); + this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(DefaultWebMvcTagsProvider.class); + assertThat(context).hasSingleBean(FilterRegistrationBean.class); + assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) + .isInstanceOf(WebMvcMetricsFilter.class); + }); } @Test public void tagsProviderBacksOff() { - this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class, - TagsProviderConfiguration.class).run((context) -> { + this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class, TagsProviderConfiguration.class) + .run((context) -> { assertThat(context).doesNotHaveBean(DefaultWebMvcTagsProvider.class); assertThat(context).hasSingleBean(TestWebMvcTagsProvider.class); }); @@ -96,77 +93,55 @@ public class WebMvcMetricsAutoConfigurationTests { @Test public void filterRegistrationHasExpectedDispatcherTypesAndOrder() { - this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class) - .run((context) -> { - FilterRegistrationBean registration = context - .getBean(FilterRegistrationBean.class); - assertThat(registration).hasFieldOrPropertyWithValue( - "dispatcherTypes", - EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC)); - assertThat(registration.getOrder()) - .isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1); - }); + this.contextRunner.withUserConfiguration(MeterRegistryConfiguration.class).run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC)); + assertThat(registration.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1); + }); } @Test public void afterMaxUrisReachedFurtherUrisAreDenied() { - this.contextRunner - .withUserConfiguration(TestController.class, - MeterRegistryConfiguration.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2") - .run((context) -> { + this.contextRunner.withUserConfiguration(TestController.class, MeterRegistryConfiguration.class) + .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(this.output.toString()) - .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() { - this.contextRunner - .withUserConfiguration(TestController.class, - MeterRegistryConfiguration.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5") - .run((context) -> { + this.contextRunner.withUserConfiguration(TestController.class, MeterRegistryConfiguration.class) + .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(this.output.toString()) - .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 @SuppressWarnings("rawtypes") public void longTaskTimingInterceptorIsRegistered() { - this.contextRunner - .withUserConfiguration(TestController.class, - MeterRegistryConfiguration.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)); + this.contextRunner.withUserConfiguration(TestController.class, MeterRegistryConfiguration.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); } @@ -194,14 +169,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 f14b008f3ee..56ba0fc20d2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,81 +50,59 @@ public class TomcatMetricsAutoConfigurationTests { @Test public void autoConfiguresTomcatMetricsWithEmbeddedServletTomcat() { - new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of( - TomcatMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TomcatMetrics.class); - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - context.getBean(TomcatMetrics.class).bindTo(registry); - 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).run((context) -> { + assertThat(context).hasSingleBean(TomcatMetrics.class); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + context.getBean(TomcatMetrics.class).bindTo(registry); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test public void sessionMetricsAreAvailableWhenEarlyMeterBinderInitializationOccurs() { - new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of( - TomcatMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, - EarlyMeterBinderInitializationConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TomcatMetrics.class); - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - context.getBean(TomcatMetrics.class).bindTo(registry); - 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, + EarlyMeterBinderInitializationConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TomcatMetrics.class); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + context.getBean(TomcatMetrics.class).bindTo(registry); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test public void autoConfiguresTomcatMetricsWithEmbeddedReactiveTomcat() { - new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of( - TomcatMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TomcatMetrics.class); - SimpleMeterRegistry registry = new SimpleMeterRegistry(); - context.getBean(TomcatMetrics.class).bindTo(registry); - 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).run((context) -> { + assertThat(context).hasSingleBean(TomcatMetrics.class); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + context.getBean(TomcatMetrics.class).bindTo(registry); + 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)) .run((context) -> assertThat(context).hasSingleBean(TomcatMetrics.class)); } @Test public void allowsCustomTomcatMetricsToBeUsed() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(CustomTomcatMetrics.class) - .run((context) -> assertThat(context).hasSingleBean(TomcatMetrics.class) - .hasBean("customTomcatMetrics")); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) + .withUserConfiguration(CustomTomcatMetrics.class).run((context) -> assertThat(context) + .hasSingleBean(TomcatMetrics.class).hasBean("customTomcatMetrics")); } @Configuration 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 1c3d585b92c..e51115e512b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/MongoReactiveHealthIndicatorConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfigurationTests.java index a5c629a57fa..3b8ad9786c9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,28 +39,21 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoReactiveHealthIndicatorConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class, - MongoHealthIndicatorAutoConfiguration.class, - HealthIndicatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoHealthIndicatorAutoConfiguration.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 6dc82847a48..9f21b4dc2c8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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/RedisReactiveHealthIndicatorConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfigurationTests.java index 6c570e9711d..6ebbf436feb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/redis/RedisReactiveHealthIndicatorConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +37,20 @@ public class RedisReactiveHealthIndicatorConfigurationTests { 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(RedisReactiveHealthIndicatorConfiguration.class) - .doesNotHaveBean(RedisHealthIndicator.class) - .doesNotHaveBean(ApplicationHealthIndicator.class)); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicatorConfiguration.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 43179658a27..c31929de33c 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,29 +36,23 @@ 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.run((context) -> assertThat(context) - .hasSingleBean(ScheduledTasksEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(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 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 0f909fd80f3..db0aa43f37d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -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/servlet/AbstractEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java index 70250569002..f091aba05a5 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 @@ -59,15 +59,12 @@ public abstract class AbstractEndpointRequestIntegrationTests { @Test public void toAllEndpointsShouldMatch() { - getContextRunner().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() - .expectStatus().isOk(); - }); + getContextRunner().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().expectStatus() + .isOk(); + }); } @Test @@ -80,9 +77,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(); } @@ -157,8 +152,7 @@ public abstract class AbstractEndpointRequestIntegrationTests { } - public interface TestPathMappedEndpoint - extends ExposableEndpoint, PathMappedEndpoint { + public interface TestPathMappedEndpoint extends ExposableEndpoint, PathMappedEndpoint { } @@ -170,12 +164,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 c5757d5d039..c3f1efebb56 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -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 dc66ea0bfbb..562f148a3d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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, PathMapper.useEndpointId(), + EndpointMediaTypes endpointMediaTypes = new EndpointMediaTypes(mediaTypes, mediaTypes); + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(this.applicationContext, + new ConversionServiceParameterValueMapper(), endpointMediaTypes, PathMapper.useEndpointId(), 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-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 868fd98fa76..950125fab2b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,58 +54,45 @@ 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("server.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("server.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("server.servlet.path=/admin") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e1").exchange() - .expectStatus().isOk(); - }); + getContextRunner().withPropertyValues("server.servlet.path=/admin").run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e1").exchange().expectStatus().isOk(); + }); } @Test public void toAnyEndpointWhenServletPathSetShouldMatch() { - getContextRunner().withPropertyValues("server.servlet.path=/admin", - "spring.security.user.password=password").run((context) -> { + getContextRunner().withPropertyValues("server.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 @@ -125,18 +112,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, PathMapper.useEndpointId(), + 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, PathMapper.useEndpointId(), 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-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 2412b4fe461..a5a572d5d2f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +36,18 @@ 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.run( - (context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(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 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 36a3ce285f4..126a8994fa4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a81db3aee05..7f5a47f10b1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +33,19 @@ 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 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/jersey/JerseyManagementChildContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementChildContextConfigurationTests.java index 020de998a41..4a4c970eb98 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementChildContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyManagementChildContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 @@ public class JerseyManagementChildContextConfigurationTests { @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 resourceConfigCustomizerBeanIsNotRequired() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(ResourceConfig.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ResourceConfig.class)); } @Configuration 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 4067df7ee3b..160239f6f6b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 160b048849a..ae4163986fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,37 +37,32 @@ import static org.assertj.core.api.Assertions.assertThat; public class ManagementContextAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class)); @Rule public OutputCapture output = new OutputCapture(); @Test public void managementServerPortShouldBeIgnoredForNonEmbeddedServer() { - this.contextRunner.withPropertyValues("management.server.port=8081") - .run((context) -> { - assertThat(context.getStartupFailure()).isNull(); - assertThat(this.output.toString()) - .contains("Could not start embedded management container on " - + "different port (management endpoints are still available through JMX)"); - }); + this.contextRunner.withPropertyValues("management.server.port=8081").run((context) -> { + assertThat(context.getStartupFailure()).isNull(); + assertThat(this.output.toString()).contains("Could not start embedded management container on " + + "different port (management endpoints are still available through JMX)"); + }); } @Test public void childManagementContextShouldStartForEmbeddedServer() { 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("management.server.port=8081") - .run((context) -> assertThat(this.output.toString()).doesNotContain( - "Could not start embedded management container on " + .run((context) -> assertThat(this.output.toString()) + .doesNotContain("Could not start embedded management container on " + "different port (management endpoints are still available through JMX)")); } 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 a06e43bf1af..4d72177b335 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,29 +39,23 @@ public class ManagementContextConfigurationImportSelectorTests { @Test public void selectImportsShouldOrderResult() { - String[] imports = new TestManagementContextConfigurationsImportSelector(C.class, - A.class, D.class, B.class).selectImports( - new StandardAnnotationMetadata(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(new StandardAnnotationMetadata(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( - new StandardAnnotationMetadata(EnableSameContext.class)); - assertThat(imports).containsExactlyInAnyOrder(SameOnly.class.getName(), - A.class.getName()); + String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, + A.class).selectImports(new StandardAnnotationMetadata(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( - new StandardAnnotationMetadata(EnableChildContext.class)); - assertThat(imports).containsExactlyInAnyOrder(ChildOnly.class.getName(), - A.class.getName()); + String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, + A.class).selectImports(new StandardAnnotationMetadata(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 e4556f0f01d..f9e35534b59 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 4bdb6a4f70e..05e626700f0 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 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 11668407c1d..1ac6bf9ef32 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ public class HttpTraceAutoConfigurationTests { @Test public void configuresRepository() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(InMemoryHttpTraceRepository.class)); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(InMemoryHttpTraceRepository.class)); } @Test public void usesUserProvidedRepository() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .withUserConfiguration(CustomRepositoryConfiguration.class) - .run((context) -> { + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .withUserConfiguration(CustomRepositoryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(HttpTraceRepository.class); assertThat(context.getBean(HttpTraceRepository.class)) .isInstanceOf(CustomHttpTraceRepository.class); @@ -69,78 +63,57 @@ public class HttpTraceAutoConfigurationTests { @Test public void configuresTracer() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(HttpExchangeTracer.class)); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(HttpExchangeTracer.class)); } @Test public void usesUserProvidedTracer() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.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 configuresWebFilter() { new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(HttpTraceWebFilter.class)); + .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(HttpTraceWebFilter.class)); } @Test public void usesUserProvidedWebFilter() { new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .withUserConfiguration(CustomWebFilterConfiguration.class) - .run((context) -> { + .withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .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() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(HttpTraceFilter.class)); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(HttpTraceFilter.class)); } @Test public void usesUserProvidedServletFilter() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.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); }); } @Test public void backsOffWhenDisabled() { - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(HttpTraceAutoConfiguration.class)) + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(HttpTraceAutoConfiguration.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 { @@ -187,8 +160,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); } @@ -198,18 +171,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); } @@ -219,8 +190,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 f871c963696..3e70629c63d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 @@ 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 runShouldHaveEndpointBean() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(HttpTraceEndpoint.class)); + this.contextRunner.run((context) -> assertThat(context).hasSingleBean(HttpTraceEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { - this.contextRunner - .withPropertyValues("management.endpoint.httptrace.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HttpTraceEndpoint.class)); + this.contextRunner.withPropertyValues("management.endpoint.httptrace.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } @Test public void endpointBacksOffWhenRepositoryIsNotAvailable() { this.contextRunner.withPropertyValues("management.trace.http.enabled:false") - .run((context) -> assertThat(context) - .doesNotHaveBean(HttpTraceEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpTraceEndpoint.class)); } } 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 9a8b8c9da42..7bb0e9c22c5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 ec33eb3f7f8..395e2cdbe6e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/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/context/ShutdownEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java index 1a44ebe2b0e..847d8d77bba 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 99dd5f0093f..a2d054c769d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +99,27 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext Map contextProperties = new HashMap<>(); ApplicationContext target = context; while (target != null) { - contextProperties.put(target.getId(), - describeConfigurationProperties(target, mapper)); + contextProperties.put(target.getId(), describeConfigurationProperties(target, mapper)); 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) { @@ -132,14 +128,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; } @@ -153,14 +147,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 + "'")); } } @@ -188,10 +180,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())); } /** @@ -201,13 +192,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 @@ -266,8 +256,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) { @@ -290,11 +279,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) { @@ -311,14 +298,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; @@ -326,9 +312,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; } @@ -344,8 +329,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); @@ -366,15 +351,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 }); @@ -394,8 +375,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); @@ -411,8 +391,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private final Map contexts; - private ApplicationConfigurationProperties( - Map contexts) { + private ApplicationConfigurationProperties(Map contexts) { this.contexts = contexts; } @@ -432,8 +411,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; @@ -459,8 +437,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/CouchbaseHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicator.java index edd1b3a357e..be9fc4c603a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +57,11 @@ public class CouchbaseHealthIndicator extends AbstractHealthIndicator { * @deprecated since 2.0.6 in favour of {@link #CouchbaseHealthIndicator(Cluster)} */ @Deprecated - public CouchbaseHealthIndicator(CouchbaseOperations couchbaseOperations, - Duration timeout) { + public CouchbaseHealthIndicator(CouchbaseOperations couchbaseOperations, Duration timeout) { super("Couchbase health check failed"); Assert.notNull(couchbaseOperations, "CouchbaseOperations must not be null"); Assert.notNull(timeout, "Timeout must not be null"); - this.healthCheck = new OperationsHealthCheck(couchbaseOperations, - timeout.toMillis()); + this.healthCheck = new OperationsHealthCheck(couchbaseOperations, timeout.toMillis()); } /** @@ -114,17 +112,14 @@ public class CouchbaseHealthIndicator extends AbstractHealthIndicator { public void checkHealth(Builder builder) throws Exception { ClusterInfo cluster = this.operations.getCouchbaseClusterInfo(); BucketInfo bucket = getBucketInfo(); - String versions = StringUtils - .collectionToCommaDelimitedString(cluster.getAllVersions()); - String nodes = StringUtils - .collectionToCommaDelimitedString(bucket.nodeList()); + String versions = StringUtils.collectionToCommaDelimitedString(cluster.getAllVersions()); + String nodes = StringUtils.collectionToCommaDelimitedString(bucket.nodeList()); builder.up().withDetail("versions", versions).withDetail("nodes", nodes); } private BucketInfo getBucketInfo() throws Exception { try { - return this.operations.getCouchbaseBucket().bucketManager() - .info(this.timeout, TimeUnit.MILLISECONDS); + return this.operations.getCouchbaseBucket().bucketManager().info(this.timeout, TimeUnit.MILLISECONDS); } catch (RuntimeException ex) { if (ex.getCause() instanceof TimeoutException) { @@ -149,8 +144,8 @@ public class CouchbaseHealthIndicator extends AbstractHealthIndicator { DiagnosticsReport diagnostics = this.cluster.diagnostics(); builder = isCouchbaseUp(diagnostics) ? builder.up() : builder.down(); builder.withDetail("sdk", diagnostics.sdk()); - builder.withDetail("endpoints", diagnostics.endpoints().stream() - .map(this::describe).collect(Collectors.toList())); + builder.withDetail("endpoints", + 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 fe24db8ef9f..64d32f19c7f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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); } /** @@ -64,8 +62,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; @@ -74,10 +71,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/endpoint/AbstractExposableEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java index 4aa16360858..f134e4b899f 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; @@ -48,8 +47,7 @@ public abstract class AbstractExposableEndpoint * {@link #AbstractExposableEndpoint(EndpointId, boolean, Collection)} */ @Deprecated - public AbstractExposableEndpoint(String id, boolean enabledByDefault, - Collection operations) { + public AbstractExposableEndpoint(String id, boolean enabledByDefault, Collection operations) { this(EndpointId.of(id), enabledByDefault, operations); } @@ -60,8 +58,7 @@ public abstract class AbstractExposableEndpoint * @param operations the endpoint operations * @since 2.0.6 */ - 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 3bfe14a0a3f..11a594d9117 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +41,9 @@ public final class EndpointId { private EndpointId(String value) { Assert.hasText(value, "Value must not be empty"); - Assert.isTrue(VALID_CHARS.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_CHARS.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"); this.value = value; this.lowerCaseValue = value.toLowerCase(Locale.ENGLISH); this.lowerCaseAlphaNumeric = getAlphaNumerics(this.lowerCaseValue); @@ -71,8 +68,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 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 11a8482196c..346a50624a9 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; @@ -51,9 +51,8 @@ public abstract class AbstractDiscoveredEndpoint * {@link #AbstractDiscoveredEndpoint(EndpointDiscoverer, Object, EndpointId, boolean, Collection)} */ @Deprecated - public AbstractDiscoveredEndpoint(EndpointDiscoverer discoverer, - Object endpointBean, String id, boolean enabledByDefault, - Collection operations) { + public AbstractDiscoveredEndpoint(EndpointDiscoverer discoverer, Object endpointBean, String id, + boolean enabledByDefault, Collection operations) { this(discoverer, endpointBean, EndpointId.of(id), enabledByDefault, operations); } @@ -66,9 +65,8 @@ public abstract class AbstractDiscoveredEndpoint * @param operations the endpoint operations * @since 2.0.6 */ - 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"); @@ -88,8 +86,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 b9341bd506d..1c6dc847208 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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,43 @@ 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) { - AnnotationAttributes annotationAttributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(method, annotationType); + private O createOperation(EndpointId endpointId, Object target, Method method, OperationType operationType, + Class annotationType) { + AnnotationAttributes annotationAttributes = AnnotatedElementUtils.getMergedAnnotationAttributes(method, + annotationType); if (annotationAttributes == null) { return null; } - DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, - operationType, annotationAttributes); - OperationInvoker invoker = new ReflectiveOperationInvoker(target, operationMethod, - this.parameterValueMapper); + DiscoveredOperationMethod operationMethod = new DiscoveredOperationMethod(method, operationType, + annotationAttributes); + 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 9876d918ee8..56607068ab2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,30 +83,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); } }; @@ -128,17 +123,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(); @@ -152,15 +144,13 @@ public abstract class EndpointDiscoverer, O exten private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() .collect(Collectors.toMap(EndpointBean::getId, (bean) -> bean)); - 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); } } @@ -170,13 +160,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); } @@ -197,25 +184,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) { @@ -232,27 +216,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()); } /** @@ -266,8 +244,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()); } @@ -299,11 +276,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; @@ -316,16 +291,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; @@ -333,8 +307,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); } /** @@ -346,10 +319,8 @@ public abstract class EndpointDiscoverer, O exten * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) * @since 2.0.6 */ - protected E createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - return createEndpoint(endpointBean, (id != null) ? id.toString() : null, - enabledByDefault, operations); + protected E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations) { + return createEndpoint(endpointBean, (id != null) ? id.toString() : null, enabledByDefault, operations); } /** @@ -363,8 +334,8 @@ public abstract class EndpointDiscoverer, O exten * {@link #createEndpoint(Object, EndpointId, boolean, Collection)} */ @Deprecated - protected abstract E createEndpoint(Object endpointBean, String id, - boolean enabledByDefault, Collection operations); + protected abstract E createEndpoint(Object endpointBean, String id, boolean enabledByDefault, + Collection operations); /** * Factory method to create an {@link Operation endpoint operation}. @@ -374,10 +345,9 @@ public abstract class EndpointDiscoverer, O exten * @return a created operation * @since 2.0.6 */ - protected O createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { - return createOperation((endpointId != null) ? endpointId.toString() : null, - operationMethod, invoker); + protected O createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { + return createOperation((endpointId != null) ? endpointId.toString() : null, operationMethod, invoker); } /** @@ -390,8 +360,8 @@ public abstract class EndpointDiscoverer, O exten * {@link #createOperation(EndpointId, DiscoveredOperationMethod, OperationInvoker)} */ @Deprecated - protected abstract O createOperation(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker); + protected abstract O createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker); /** * Create an {@link OperationKey} for the given operation. @@ -463,13 +433,11 @@ public abstract class EndpointDiscoverer, O exten private Set extensions = new LinkedHashSet<>(); EndpointBean(String beanName, Object bean) { - AnnotationAttributes attributes = AnnotatedElementUtils - .findMergedAnnotationAttributes(bean.getClass(), Endpoint.class, true, - true); + AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(bean.getClass(), + Endpoint.class, true, true); String id = attributes.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); @@ -486,8 +454,8 @@ public abstract class EndpointDiscoverer, O exten } private Class getFilter(Class type) { - AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(type, FilteredEndpoint.class); + AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(type, + FilteredEndpoint.class); if (attributes == null) { return null; } @@ -532,15 +500,13 @@ public abstract class EndpointDiscoverer, O exten ExtensionBean(String beanName, Object bean) { this.bean = bean; this.beanName = beanName; - AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(bean.getClass(), - EndpointExtension.class); + AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(bean.getClass(), + EndpointExtension.class); Class endpointType = attributes.getClass("endpoint"); - AnnotationAttributes endpointAttributes = AnnotatedElementUtils - .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, - true); - Assert.state(endpointAttributes != null, () -> "Extension " - + endpointType.getName() + " does not specify an endpoint"); + AnnotationAttributes endpointAttributes = AnnotatedElementUtils.findMergedAnnotationAttributes(endpointType, + Endpoint.class, true, true); + Assert.state(endpointAttributes != null, + () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(endpointAttributes.getString("id")); this.filter = attributes.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 7aef676e791..23348dbd0a5 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. @@ -37,10 +37,9 @@ public interface OperationInvokerAdvisor { * @return an potentially new operation invoker with support for additional features * @since 2.0.6 */ - default OperationInvoker apply(EndpointId endpointId, OperationType operationType, - OperationParameters parameters, OperationInvoker invoker) { - return apply((endpointId != null) ? endpointId.toString() : null, operationType, - parameters, invoker); + default OperationInvoker apply(EndpointId endpointId, OperationType operationType, OperationParameters parameters, + OperationInvoker invoker) { + return apply((endpointId != null) ? endpointId.toString() : null, operationType, parameters, invoker); } /** @@ -54,7 +53,7 @@ public interface OperationInvokerAdvisor { * {@link #apply(EndpointId, OperationType, OperationParameters, OperationInvoker)} */ @Deprecated - OperationInvoker apply(String endpointId, OperationType operationType, - OperationParameters parameters, OperationInvoker invoker); + OperationInvoker apply(String 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 fde9a17ee22..45bc85cd674 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a5ca198cf91..c0f527f6c83 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,21 +36,20 @@ public class CachingOperationInvokerAdvisor implements OperationInvokerAdvisor { private final Function endpointIdTimeToLive; - public CachingOperationInvokerAdvisor( - Function endpointIdTimeToLive) { + public CachingOperationInvokerAdvisor(Function endpointIdTimeToLive) { this.endpointIdTimeToLive = endpointIdTimeToLive; } @Override @Deprecated - public OperationInvoker apply(String endpointId, OperationType operationType, - OperationParameters parameters, OperationInvoker invoker) { + public OperationInvoker apply(String endpointId, OperationType operationType, OperationParameters parameters, + OperationInvoker invoker) { return apply(EndpointId.of(endpointId), operationType, parameters, invoker); } @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) { @@ -62,8 +61,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 aaabc1b831b..4b77190f476 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 35f09939b36..f7e5f6f03f2 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,8 +46,7 @@ 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); @@ -56,36 +54,33 @@ public class JmxEndpointDiscoverer @Override @Deprecated - protected ExposableJmxEndpoint createEndpoint(Object endpointBean, String id, - boolean enabledByDefault, Collection operations) { - return createEndpoint(endpointBean, EndpointId.of(id), enabledByDefault, - operations); + protected ExposableJmxEndpoint createEndpoint(Object endpointBean, String id, boolean enabledByDefault, + Collection operations) { + return createEndpoint(endpointBean, EndpointId.of(id), enabledByDefault, operations); } @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 @Deprecated - protected JmxOperation createOperation(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected JmxOperation createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return createOperation(EndpointId.of(endpointId), operationMethod, invoker); } @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 56fc86f6202..5d0bbd75746 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +61,9 @@ 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); } 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 f3fc76f9d72..1fc341ff405 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); } }); }); @@ -189,8 +186,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 53d1a6a528c..d512f5bdf5e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); logger.info("Registered '" + path + "' to " + name); 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 3b4bcbc7231..2c514aaba8d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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.replaceAll("\\{.*?}", "{*}"); this.httpMethod = httpMethod; @@ -118,15 +118,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: " - + StringUtils.collectionToCommaDelimitedString(this.consumes)); + result.append(" consumes: " + StringUtils.collectionToCommaDelimitedString(this.consumes)); } if (!CollectionUtils.isEmpty(this.produces)) { - result.append(" produces: " - + StringUtils.collectionToCommaDelimitedString(this.produces)); + result.append(" produces: " + 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 95b16f259d4..e9fc98266eb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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; * @author Phillip Webb * @since 2.0.0 */ -public class ControllerEndpointDiscoverer - extends EndpointDiscoverer +public class ControllerEndpointDiscoverer extends EndpointDiscoverer implements ControllerEndpointsSupplier { private final PathMapper endpointPathMapper; @@ -51,11 +50,9 @@ public class ControllerEndpointDiscoverer * @param endpointPathMapper the endpoint path mapper * @param filters filters to apply */ - public ControllerEndpointDiscoverer(ApplicationContext applicationContext, - PathMapper endpointPathMapper, + public ControllerEndpointDiscoverer(ApplicationContext applicationContext, PathMapper endpointPathMapper, Collection> filters) { - super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), - filters); + super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), filters); Assert.notNull(endpointPathMapper, "EndpointPathMapper must not be null"); this.endpointPathMapper = endpointPathMapper; } @@ -69,38 +66,34 @@ public class ControllerEndpointDiscoverer @Override @Deprecated - protected ExposableControllerEndpoint createEndpoint(Object endpointBean, String id, - boolean enabledByDefault, Collection operations) { - return createEndpoint(endpointBean, (id != null) ? EndpointId.of(id) : null, - enabledByDefault, operations); + protected ExposableControllerEndpoint createEndpoint(Object endpointBean, String id, boolean enabledByDefault, + Collection operations) { + return createEndpoint(endpointBean, (id != null) ? EndpointId.of(id) : null, enabledByDefault, operations); } @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 = this.endpointPathMapper.getRootPath(id); - return new DiscoveredControllerEndpoint(this, endpointBean, id, rootPath, - enabledByDefault); + return new DiscoveredControllerEndpoint(this, endpointBean, id, rootPath, enabledByDefault); } @Override @Deprecated - protected Operation createOperation(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected Operation createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return createOperation(EndpointId.of(endpointId), operationMethod, invoker); } @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 d6a7a98f003..9c0ac4f3886 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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} methods. 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 fdc57aa3fd5..ab9af5e7f69 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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; * @author Phillip Webb * @since 2.0.0 */ -public class ServletEndpointDiscoverer - extends EndpointDiscoverer +public class ServletEndpointDiscoverer extends EndpointDiscoverer implements ServletEndpointsSupplier { private final PathMapper endpointPathMapper; @@ -51,11 +50,9 @@ public class ServletEndpointDiscoverer * @param endpointPathMapper the endpoint path mapper * @param filters filters to apply */ - public ServletEndpointDiscoverer(ApplicationContext applicationContext, - PathMapper endpointPathMapper, + public ServletEndpointDiscoverer(ApplicationContext applicationContext, PathMapper endpointPathMapper, Collection> filters) { - super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), - filters); + super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), filters); Assert.notNull(endpointPathMapper, "EndpointPathMapper must not be null"); this.endpointPathMapper = endpointPathMapper; } @@ -68,30 +65,28 @@ public class ServletEndpointDiscoverer @Override @Deprecated - protected ExposableServletEndpoint createEndpoint(Object endpointBean, String id, - boolean enabledByDefault, Collection operations) { - return createEndpoint(endpointBean, EndpointId.of(id), enabledByDefault, - operations); + protected ExposableServletEndpoint createEndpoint(Object endpointBean, String id, boolean enabledByDefault, + Collection operations) { + return createEndpoint(endpointBean, EndpointId.of(id), enabledByDefault, operations); } @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 = this.endpointPathMapper.getRootPath(id); - return new DiscoveredServletEndpoint(this, endpointBean, id, rootPath, - enabledByDefault); + return new DiscoveredServletEndpoint(this, endpointBean, id, rootPath, enabledByDefault); } @Override @Deprecated - protected Operation createOperation(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected Operation createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return createOperation(EndpointId.of(endpointId), operationMethod, invoker); } @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 9eeedd7fdc0..4210d730aa0 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.util.Assert; * @author Phillip Webb * @since 2.0.0 */ -public class WebEndpointDiscoverer - extends EndpointDiscoverer +public class WebEndpointDiscoverer extends EndpointDiscoverer implements WebEndpointsSupplier { private final PathMapper endpointPathMapper; @@ -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, PathMapper endpointPathMapper, Collection invokerAdvisors, Collection> filters) { @@ -70,35 +68,32 @@ public class WebEndpointDiscoverer @Override @Deprecated - protected ExposableWebEndpoint createEndpoint(Object endpointBean, String id, - boolean enabledByDefault, Collection operations) { - return createEndpoint(endpointBean, EndpointId.of(id), enabledByDefault, - operations); + protected ExposableWebEndpoint createEndpoint(Object endpointBean, String id, boolean enabledByDefault, + Collection operations) { + return createEndpoint(endpointBean, EndpointId.of(id), enabledByDefault, operations); } @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 = this.endpointPathMapper.getRootPath(id); - return new DiscoveredWebEndpoint(this, endpointBean, id, rootPath, - enabledByDefault, operations); + return new DiscoveredWebEndpoint(this, endpointBean, id, rootPath, enabledByDefault, operations); } @Override @Deprecated - protected WebOperation createOperation(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected WebOperation createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return createOperation(EndpointId.of(endpointId), operationMethod, invoker); } @Override - protected WebOperation createOperation(EndpointId endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected WebOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { String rootPath = this.endpointPathMapper.getRootPath(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 3b2d3b7d074..64f252d8210 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.web.util.pattern.PathPatternParser; * @author Phillip Webb * @since 2.0.0 */ -public abstract class AbstractWebFluxEndpointHandlerMapping - extends RequestMappingInfoHandlerMapping { +public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappingInfoHandlerMapping { private static final PathPatternParser pathPatternParser = new PathPatternParser(); @@ -88,15 +87,14 @@ public abstract class AbstractWebFluxEndpointHandlerMapping private final CorsConfiguration corsConfiguration; - private final Method linksMethod = ReflectionUtils.findMethod(getClass(), "links", + private final Method linksMethod = ReflectionUtils.findMethod(getClass(), "links", ServerWebExchange.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 handleWriteMethod = ReflectionUtils.findMethod( - WriteOperationHandler.class, "handle", ServerWebExchange.class, Map.class); - - private final Method handleReadMethod = ReflectionUtils - .findMethod(ReadOperationHandler.class, "handle", ServerWebExchange.class); - /** * Creates a new {@code AbstractWebFluxEndpointHandlerMapping} that provides mappings * for the operations of the given {@code webEndpoints}. @@ -106,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; @@ -127,22 +125,19 @@ public abstract class AbstractWebFluxEndpointHandlerMapping } } - private void registerMappingForOperation(ExposableWebEndpoint endpoint, - WebOperation operation) { + private void registerMappingForOperation(ExposableWebEndpoint endpoint, WebOperation operation) { OperationInvoker invoker = operation::invoke; if (operation.isBlocking()) { invoker = new ElasticSchedulerInvoker(invoker); } - ReactiveWebOperation reactiveWebOperation = wrapReactiveWebOperation(endpoint, - operation, new ReactiveWebOperationAdapter(invoker)); + ReactiveWebOperation reactiveWebOperation = wrapReactiveWebOperation(endpoint, operation, + new ReactiveWebOperationAdapter(invoker)); 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); } } @@ -155,40 +150,36 @@ 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); registerMapping(mapping, this, this.linksMethod); } @Override - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mapping) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } @@ -198,8 +189,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping } @Override - protected RequestMappingInfo getMappingForMethod(Method method, - Class handlerType) { + protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { return null; } @@ -227,8 +217,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) { @@ -249,8 +238,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping @FunctionalInterface protected interface ReactiveWebOperation { - Mono> handle(ServerWebExchange exchange, - Map body); + Mono> handle(ServerWebExchange exchange, Map body); } @@ -258,8 +246,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; @@ -271,8 +258,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; } @@ -281,8 +267,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))); } @@ -291,26 +276,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; } @@ -318,14 +299,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) { @@ -397,8 +376,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 89437eadf66..fd9d72d1ea7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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,44 +80,36 @@ 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()); } @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 fafc49d69c6..a321414ef4a 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. @@ -40,8 +40,7 @@ import org.springframework.web.util.UriComponentsBuilder; * @author Phillip Webb * @since 2.0.0 */ -public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping - implements InitializingBean { +public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping implements InitializingBean { private final EndpointLinksResolver linksResolver; @@ -54,8 +53,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); @@ -66,10 +64,9 @@ public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandle @Override @ResponseBody protected Map> links(ServerWebExchange exchange) { - String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()) - .replaceQuery(null).toUriString(); - return Collections.singletonMap("_links", - this.linksResolver.resolveLinks(requestUri)); + String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).replaceQuery(null) + .toUriString(); + return Collections.singletonMap("_links", this.linksResolver.resolveLinks(requestUri)); } } 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 0b0fec5b50a..b40f8fb59ed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMappi * @author Phillip Webb * @since 2.0.0 */ -public abstract class AbstractWebMvcEndpointHandlerMapping - extends RequestMappingInfoHandlerMapping +public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappingInfoHandlerMapping implements InitializingBean, MatchableHandlerMapping { private final EndpointMapping endpointMapping; @@ -80,11 +79,11 @@ public abstract class AbstractWebMvcEndpointHandlerMapping private final CorsConfiguration corsConfiguration; - private final Method linksMethod = ReflectionUtils.findMethod(getClass(), "links", - HttpServletRequest.class, HttpServletResponse.class); + private final Method linksMethod = ReflectionUtils.findMethod(getClass(), "links", HttpServletRequest.class, + HttpServletResponse.class); - 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(); @@ -96,8 +95,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); } @@ -110,8 +108,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,16 +131,14 @@ public abstract class AbstractWebMvcEndpointHandlerMapping @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() { @@ -154,13 +150,12 @@ public abstract class AbstractWebMvcEndpointHandlerMapping return config; } - private void registerMappingForOperation(ExposableWebEndpoint endpoint, - WebOperation operation) { + private void registerMappingForOperation(ExposableWebEndpoint endpoint, WebOperation operation) { OperationInvoker invoker = operation::invoke; - ServletWebOperation servletWebOperation = wrapServletWebOperation(endpoint, - operation, new ServletWebOperationAdapter(invoker)); - registerMapping(createRequestMappingInfo(operation), - new OperationHandler(servletWebOperation), this.handleMethod); + ServletWebOperation servletWebOperation = wrapServletWebOperation(endpoint, operation, + new ServletWebOperationAdapter(invoker)); + registerMapping(createRequestMappingInfo(operation), new OperationHandler(servletWebOperation), + this.handleMethod); } /** @@ -172,47 +167,40 @@ public abstract class AbstractWebMvcEndpointHandlerMapping * @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); registerMapping(mapping, this, this.linksMethod); } 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 - protected CorsConfiguration initCorsConfiguration(Object handler, Method method, - RequestMappingInfo mapping) { + protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } @@ -222,8 +210,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping } @Override - protected RequestMappingInfo getMappingForMethod(Method method, - Class handlerType) { + protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { return null; } @@ -232,8 +219,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping interceptors.add(new SkipPathExtensionContentNegotiation()); } - protected abstract Object links(HttpServletRequest request, - HttpServletResponse response); + protected abstract Object links(HttpServletRequest request, HttpServletResponse response); /** * Return the web endpoints being mapped. @@ -266,13 +252,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.invoker.invoke(new InvocationContext( - new ServletSecurityContext(request), arguments)), + this.invoker.invoke(new InvocationContext(new ServletSecurityContext(request), arguments)), HttpMethod.valueOf(request.getMethod())); } catch (InvalidEndpointRequestException ex) { @@ -280,35 +264,32 @@ public abstract class AbstractWebMvcEndpointHandlerMapping } } - 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())); } } @@ -325,8 +306,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 2c2791f5de4..fe92d97cfce 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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,44 +81,37 @@ 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()); } @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 181703e1ac1..62244c0ce5c 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); @@ -64,10 +63,8 @@ public class WebMvcEndpointHandlerMapping extends AbstractWebMvcEndpointHandlerM @Override @ResponseBody - protected Map> links(HttpServletRequest request, - HttpServletResponse response) { - return Collections.singletonMap("_links", - this.linksResolver.resolveLinks(request.getRequestURL().toString())); + protected Map> links(HttpServletRequest request, HttpServletResponse response) { + return Collections.singletonMap("_links", this.linksResolver.resolveLinks(request.getRequestURL().toString())); } } 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 9f1d8b5483a..c8bd3a340f8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,66 +86,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); } @@ -153,8 +141,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); } @@ -164,15 +151,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); } } @@ -186,11 +171,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); } } @@ -207,17 +190,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; } @@ -241,8 +220,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; } @@ -269,8 +247,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; @@ -325,8 +302,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; } @@ -351,8 +327,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 ac035009d11..4d776635893 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 4f160d89ce2..ab2f426c6a8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 67d330b23f8..2d868076c43 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 CompositeHealthIndicator implements HealthIndicator { * @param indicators a map of {@link HealthIndicator}s with the key being used as an * indicator name. */ - public CompositeHealthIndicator(HealthAggregator healthAggregator, - Map indicators) { + public CompositeHealthIndicator(HealthAggregator healthAggregator, Map indicators) { Assert.notNull(healthAggregator, "HealthAggregator must not be null"); Assert.notNull(indicators, "Indicators must not be null"); this.indicators = new LinkedHashMap<>(indicators); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactory.java index d672f4ad858..f994853861b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 CompositeHealthIndicatorFactory { private final Function healthIndicatorNameFactory; - public CompositeHealthIndicatorFactory( - Function healthIndicatorNameFactory) { + public CompositeHealthIndicatorFactory(Function healthIndicatorNameFactory) { this.healthIndicatorNameFactory = healthIndicatorNameFactory; } @@ -47,13 +46,11 @@ public class CompositeHealthIndicatorFactory { * @return a {@link HealthIndicator} that delegates to the specified * {@code healthIndicators}. */ - public CompositeHealthIndicator createHealthIndicator( - HealthAggregator healthAggregator, + public CompositeHealthIndicator createHealthIndicator(HealthAggregator healthAggregator, Map healthIndicators) { Assert.notNull(healthAggregator, "HealthAggregator must not be null"); Assert.notNull(healthIndicators, "HealthIndicators must not be null"); - CompositeHealthIndicator healthIndicator = new CompositeHealthIndicator( - healthAggregator); + CompositeHealthIndicator healthIndicator = new CompositeHealthIndicator(healthAggregator); for (Map.Entry entry : healthIndicators.entrySet()) { String name = this.healthIndicatorNameFactory.apply(entry.getKey()); healthIndicator.addHealthIndicator(name, entry.getValue()); 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 2dacfcda34c..e3e1c6d9e06 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class CompositeReactiveHealthIndicator implements ReactiveHealthIndicator Assert.notNull(indicators, "Indicators must not be null"); this.indicators = new LinkedHashMap<>(indicators); 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; } /** @@ -67,8 +67,7 @@ public class CompositeReactiveHealthIndicator implements ReactiveHealthIndicator * @param indicator the health indicator to add * @return this instance */ - public CompositeReactiveHealthIndicator addHealthIndicator(String name, - ReactiveHealthIndicator indicator) { + public CompositeReactiveHealthIndicator addHealthIndicator(String name, ReactiveHealthIndicator indicator) { this.indicators.put(name, indicator); return this; } @@ -82,21 +81,17 @@ 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; } @Override public Mono health() { - return Flux.fromIterable(this.indicators.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.indicators.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/CompositeReactiveHealthIndicatorFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactory.java index 63510d3175f..66525f7103f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 CompositeReactiveHealthIndicatorFactory { private final Function healthIndicatorNameFactory; - public CompositeReactiveHealthIndicatorFactory( - Function healthIndicatorNameFactory) { + public CompositeReactiveHealthIndicatorFactory(Function healthIndicatorNameFactory) { this.healthIndicatorNameFactory = healthIndicatorNameFactory; } @@ -55,35 +54,28 @@ public class CompositeReactiveHealthIndicatorFactory { * @return a {@link ReactiveHealthIndicator} that delegates to the specified * {@code reactiveHealthIndicators}. */ - public CompositeReactiveHealthIndicator createReactiveHealthIndicator( - HealthAggregator healthAggregator, + public CompositeReactiveHealthIndicator createReactiveHealthIndicator(HealthAggregator healthAggregator, Map reactiveHealthIndicators, Map healthIndicators) { Assert.notNull(healthAggregator, "HealthAggregator must not be null"); - Assert.notNull(reactiveHealthIndicators, - "ReactiveHealthIndicators must not be null"); - CompositeReactiveHealthIndicator healthIndicator = new CompositeReactiveHealthIndicator( - healthAggregator); - merge(reactiveHealthIndicators, healthIndicators) - .forEach((beanName, indicator) -> { - String name = this.healthIndicatorNameFactory.apply(beanName); - healthIndicator.addHealthIndicator(name, indicator); - }); + Assert.notNull(reactiveHealthIndicators, "ReactiveHealthIndicators must not be null"); + CompositeReactiveHealthIndicator healthIndicator = new CompositeReactiveHealthIndicator(healthAggregator); + merge(reactiveHealthIndicators, healthIndicators).forEach((beanName, indicator) -> { + String name = this.healthIndicatorNameFactory.apply(beanName); + healthIndicator.addHealthIndicator(name, indicator); + }); return healthIndicator; } - 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/health/HealthEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointWebExtension.java index 34ab021dbd0..53ae2da59e7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 HealthEndpointWebExtension { private final HealthWebEndpointResponseMapper responseMapper; - public HealthEndpointWebExtension(HealthIndicator delegate, - HealthWebEndpointResponseMapper responseMapper) { + public HealthEndpointWebExtension(HealthIndicator delegate, HealthWebEndpointResponseMapper responseMapper) { this.delegate = delegate; this.responseMapper = responseMapper; } @@ -50,10 +49,8 @@ public class HealthEndpointWebExtension { return this.responseMapper.map(this.delegate.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/HealthStatusHttpMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthStatusHttpMapper.java index 3491ba241a4..493b89bb035 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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); } /** @@ -102,10 +101,8 @@ public class HealthStatusHttpMapper { public int mapStatus(Status status) { String code = getUniformValue(status.getCode()); if (code != null) { - return this.statusMapping.keySet().stream() - .filter((key) -> code.equals(getUniformValue(key))) - .map(this.statusMapping::get).findFirst() - .orElse(WebEndpointResponse.STATUS_OK); + return this.statusMapping.keySet().stream().filter((key) -> code.equals(getUniformValue(key))) + .map(this.statusMapping::get).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 acd1bacb5c6..3e55261826b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; @@ -50,8 +50,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); } @@ -63,12 +62,9 @@ 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) { - if (showDetails == ShowDetails.NEVER - || (showDetails == ShowDetails.WHEN_AUTHORIZED - && (securityContext.getPrincipal() == null - || !isUserInRole(securityContext)))) { + public WebEndpointResponse map(Health health, SecurityContext securityContext, ShowDetails showDetails) { + if (showDetails == ShowDetails.NEVER || (showDetails == ShowDetails.WHEN_AUTHORIZED + && (securityContext.getPrincipal() == null || !isUserInRole(securityContext)))) { health = Health.status(health.getStatus()).build(); } Integer status = this.statusHttpMapper.mapStatus(health.getStatus()); 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 4cda2ed37fc..4a427ca2d12 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 @@ 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)); } - 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)); } } 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 1f088099b64..fbb34afd6c2 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 @@ -111,8 +109,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator String validationQuery = getValidationQuery(product); if (StringUtils.hasText(validationQuery)) { // 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("hello", 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 914deabd686..5d428146aa1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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()); @@ -88,8 +87,8 @@ public class LiquibaseEndpoint { database.setDefaultSchemaName(defaultSchema); } 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) { @@ -133,8 +132,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; } @@ -203,15 +201,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 37e6bfa5909..f212d0837c3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 559d84d4fe1..41d1a088435 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 1a0d0576fe5..14cf29cbe23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 9793026c59b..8a740d595b0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -79,11 +78,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; } @@ -91,9 +88,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) { @@ -113,20 +109,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) { @@ -136,8 +129,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) { @@ -165,8 +158,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.toCollection(ArrayList::new)); } @@ -202,8 +194,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; @@ -281,8 +273,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/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 a3073b8c192..b99cd17beee 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +30,14 @@ import org.springframework.util.StringUtils; * @author Jon Schneider * @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)); } } 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 0d2d611f4b0..da93d643479 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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; @@ -50,16 +49,16 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto private final String metricName; - MetricsClientHttpRequestInterceptor(MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider tagProvider, String metricName) { + MetricsClientHttpRequestInterceptor(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider tagProvider, + String metricName) { this.tagProvider = tagProvider; this.meterRegistry = meterRegistry; this.metricName = metricName; } @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) + throws IOException { long startTime = System.nanoTime(); ClientHttpResponse response = null; try { @@ -67,8 +66,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(); } } @@ -91,10 +90,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto }; } - private Timer.Builder getTimeBuilder(HttpRequest request, - ClientHttpResponse response) { - return Timer.builder(this.metricName) - .tags(this.tagProvider.getTags(urlTemplate.get(), request, response)) + private Timer.Builder getTimeBuilder(HttpRequest request, ClientHttpResponse response) { + return Timer.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 0755feadaa0..96425c3097b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 @@ public class MetricsRestTemplateCustomizer implements RestTemplateCustomizer { * @param tagProvider the tag provider * @param metricName the name of the recorded metric */ - public MetricsRestTemplateCustomizer(MeterRegistry meterRegistry, - RestTemplateExchangeTagsProvider tagProvider, String metricName) { - this.interceptor = new MetricsClientHttpRequestInterceptor(meterRegistry, - tagProvider, metricName); + public MetricsRestTemplateCustomizer(MeterRegistry meterRegistry, RestTemplateExchangeTagsProvider tagProvider, + String metricName) { + this.interceptor = new MetricsClientHttpRequestInterceptor(meterRegistry, tagProvider, metricName); } @Override @@ -57,8 +56,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/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 236f5f31d70..fd185d06eec 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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)); + public Iterable httpRequestTags(ServerWebExchange exchange, Throwable exception) { + return Arrays.asList(WebFluxTags.method(exchange), WebFluxTags.uri(exchange), WebFluxTags.exception(exception), + WebFluxTags.status(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 58e6e327469..699a9b985fb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +57,12 @@ public class MetricsWebFilter implements WebFilter { * {@link #MetricsWebFilter(MeterRegistry, WebFluxTagsProvider, String, boolean)} */ @Deprecated - public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, - String metricName) { + public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, String metricName) { this(registry, tagsProvider, metricName, true); } - public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, - String metricName, boolean autoTimeRequests) { + public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, String metricName, + boolean autoTimeRequests) { this.registry = registry; this.tagsProvider = tagsProvider; this.metricName = metricName; @@ -96,14 +95,12 @@ public class MetricsWebFilter implements WebFilter { private void success(ServerWebExchange exchange, long start) { Iterable tags = this.tagsProvider.httpRequestTags(exchange, null); - this.registry.timer(this.metricName, tags).record(System.nanoTime() - start, - TimeUnit.NANOSECONDS); + this.registry.timer(this.metricName, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } private void error(ServerWebExchange exchange, long start, Throwable cause) { Iterable tags = this.tagsProvider.httpRequestTags(exchange, cause); - this.registry.timer(this.metricName, tags).record(System.nanoTime() - start, - TimeUnit.NANOSECONDS); + this.registry.timer(this.metricName, tags).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/RouterFunctionMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/RouterFunctionMetrics.java index 2bf2467c57e..61de6a1ebdc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/RouterFunctionMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/RouterFunctionMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 RouterFunctionMetrics { * {@code ServerResponse} may be null * @return {@code this} for further configuration */ - public RouterFunctionMetrics defaultTags( - BiFunction> defaultTags) { + public RouterFunctionMetrics defaultTags(BiFunction> defaultTags) { return new RouterFunctionMetrics(this.registry, defaultTags); } @@ -82,13 +81,11 @@ public class RouterFunctionMetrics { return timer(name, Tags.empty()); } - public HandlerFilterFunction timer(String name, - String... tags) { + public HandlerFilterFunction timer(String name, String... tags) { return timer(name, Tags.of(tags)); } - public HandlerFilterFunction timer(String name, - Iterable tags) { + public HandlerFilterFunction timer(String name, Iterable tags) { return new MetricsFilter(name, Tags.of(tags)); } @@ -113,8 +110,7 @@ public class RouterFunctionMetrics { /** * {@link HandlerFilterFunction} to handle calling micrometer. */ - private class MetricsFilter - implements HandlerFilterFunction { + private class MetricsFilter implements HandlerFilterFunction { private final String name; @@ -126,23 +122,20 @@ public class RouterFunctionMetrics { } @Override - public Mono filter(ServerRequest request, - HandlerFunction next) { + public Mono filter(ServerRequest request, HandlerFunction next) { long start = System.nanoTime(); - return next.handle(request) - .doOnSuccess((response) -> timer(start, request, response)) + return next.handle(request).doOnSuccess((response) -> timer(start, request, response)) .doOnError((error) -> timer(start, request, null)); } - private Iterable getDefaultTags(ServerRequest request, - ServerResponse response) { + private Iterable getDefaultTags(ServerRequest request, ServerResponse response) { return RouterFunctionMetrics.this.defaultTags.apply(request, response); } private void timer(long start, ServerRequest request, ServerResponse response) { Tags allTags = this.tags.and(getDefaultTags(request, response)); - RouterFunctionMetrics.this.registry.timer(this.name, allTags) - .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); + RouterFunctionMetrics.this.registry.timer(this.name, allTags).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 39361fefc6a..53c0edac45e 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 @@ -83,8 +83,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()); } @@ -119,8 +118,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 26bbaccb503..0ca54b4c954 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,10 +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)); + 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)); } @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 088415febaf..896871c0e93 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +55,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); @@ -72,8 +71,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)); } @@ -81,15 +80,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 cb11da79319..bf5f682ae33 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,9 +72,8 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { * {@link #WebMvcMetricsFilter(MeterRegistry, WebMvcTagsProvider, String, boolean)} */ @Deprecated - public WebMvcMetricsFilter(ApplicationContext context, MeterRegistry registry, - WebMvcTagsProvider tagsProvider, String metricName, - boolean autoTimeRequests) { + public WebMvcMetricsFilter(ApplicationContext context, MeterRegistry registry, WebMvcTagsProvider tagsProvider, + String metricName, boolean autoTimeRequests) { this(registry, tagsProvider, metricName, autoTimeRequests); } @@ -86,8 +85,8 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { * @param autoTimeRequests if requests should be automatically timed * @since 2.0.7 */ - public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider, - String metricName, boolean autoTimeRequests) { + public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider, String metricName, + boolean autoTimeRequests) { this.registry = registry; this.tagsProvider = tagsProvider; this.metricName = metricName; @@ -100,15 +99,13 @@ 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 { filterAndRecordMetrics(request, response, filterChain); } - private void filterAndRecordMetrics(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws IOException, ServletException { + private void filterAndRecordMetrics(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws IOException, ServletException { TimingContext timingContext = TimingContext.get(request); if (timingContext == null) { timingContext = startAndAttachTimingContext(request); @@ -120,8 +117,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, response, request, exception); } } @@ -162,14 +158,12 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { return AnnotationUtils.getDeclaredRepeatableAnnotations(element, Timed.class); } - private void record(TimingContext timingContext, HttpServletResponse response, - HttpServletRequest request, Throwable exception) { - Object handlerObject = request - .getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE); + private void record(TimingContext timingContext, HttpServletResponse response, HttpServletRequest request, + Throwable exception) { + Object handlerObject = request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE); Set annotations = getTimedAnnotations(handlerObject); Timer.Sample timerSample = timingContext.getTimerSample(); - Supplier> tags = () -> this.tagsProvider.getTags(request, response, - handlerObject, exception); + Supplier> tags = () -> this.tagsProvider.getTags(request, response, handlerObject, exception); if (annotations.isEmpty()) { if (this.autoTimeRequests) { stop(timerSample, tags, Timer.builder(this.metricName)); @@ -182,8 +176,7 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { } } - private void stop(Timer.Sample timerSample, Supplier> tags, - Builder builder) { + private void stop(Timer.Sample timerSample, Supplier> tags, Builder builder) { timerSample.stop(builder.tags(tags.get()).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 37ca4e0884d..4a261a0520d 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. @@ -72,9 +72,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; } /** @@ -122,13 +120,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) { @@ -146,8 +142,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/mongo/MongoReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicator.java index c687947bfd1..a0eb6dbdbcd 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MongoReactiveHealthIndicator extends AbstractReactiveHealthIndicato @Override protected Mono 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 7bbf580d41d..b19194cf9c4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +37,20 @@ 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) { - ReactiveRedisConnection connection = this.connectionFactory - .getReactiveConnection(); + ReactiveRedisConnection connection = this.connectionFactory.getReactiveConnection(); return connection.serverCommands().info().map((info) -> up(builder, info)) .doFinally((signal) -> connection.close()); } 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(); } } 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 685e83f4da6..ca148e50e19 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +58,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); } @@ -78,14 +77,10 @@ public class ScheduledTasksEndpoint { private final List fixedRate; - 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()); + 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()); } public List getCron() { @@ -110,14 +105,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; @@ -125,10 +116,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) { @@ -176,8 +165,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(); @@ -261,8 +249,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 83d04be736f..24fc1b330ab 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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<>(); @@ -104,8 +101,7 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList data.put("details", event.getAuthentication().getDetails()); } 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 dbad64f1b79..f8d6038e2cf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +44,14 @@ 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 - .findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - username); + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); return new SessionsReport(sessions); } @@ -81,8 +78,7 @@ public class SessionsEndpoint { private final List sessions; public SessionsReport(Map sessions) { - this.sessions = sessions.entrySet().stream() - .map((s) -> new SessionDescriptor(s.getValue())) + this.sessions = sessions.entrySet().stream().map((s) -> new SessionDescriptor(s.getValue())) .collect(Collectors.toList()); } 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 9298f0443dc..596b2059380 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +60,11 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator { builder.up(); } else { - logger.warn(String.format( - "Free disk space below threshold. " - + "Available: %d bytes (threshold: %d bytes)", + logger.warn(String.format("Free disk space below threshold. " + "Available: %d bytes (threshold: %d bytes)", 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); } 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/web/mappings/MappingsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/MappingsEndpoint.java index 8930f757cf8..ec9180d1d53 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 080fe079354..15c53e912d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; @@ -74,14 +73,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) { @@ -91,17 +86,14 @@ 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); return chain.filter(exchange).doAfterSuccessOrError((aVoid, ex) -> { - TraceableServerHttpResponse response = new TraceableServerHttpResponse( - (ex != null) ? new CustomStatusResponseDecorator(ex, - exchange.getResponse()) : exchange.getResponse()); - this.tracer.sendingResponse(trace, response, () -> principal, - () -> getStartedSessionId(session)); + TraceableServerHttpResponse response = new TraceableServerHttpResponse((ex != null) + ? new CustomStatusResponseDecorator(ex, exchange.getResponse()) : exchange.getResponse()); + this.tracer.sendingResponse(trace, response, () -> principal, () -> getStartedSessionId(session)); this.repository.add(trace); }); } @@ -110,15 +102,13 @@ public class HttpTraceWebFilter implements WebFilter, Ordered { return (session != null && session.isStarted()) ? session.getId() : null; } - private static final class CustomStatusResponseDecorator - extends ServerHttpResponseDecorator { + private static final class CustomStatusResponseDecorator extends ServerHttpResponseDecorator { private final HttpStatus status; private CustomStatusResponseDecorator(Throwable ex, ServerHttpResponse delegate) { super(delegate); - this.status = (ex instanceof ResponseStatusException) - ? ((ResponseStatusException) ex).getStatus() + this.status = (ex instanceof ResponseStatusException) ? ((ResponseStatusException) ex).getStatus() : HttpStatus.INTERNAL_SERVER_ERROR; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequest.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequest.java index 1a1144eb6d3..00df60e3917 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequest.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/trace/reactive/ServerWebExchangeTraceableRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class ServerWebExchangeTraceableRequest implements TraceableRequest { this.method = request.getMethodValue(); this.headers = request.getHeaders(); this.uri = request.getURI(); - this.remoteAddress = (request.getRemoteAddress() != null) - ? request.getRemoteAddress().getAddress().toString() : null; + this.remoteAddress = (request.getRemoteAddress() != null) ? request.getRemoteAddress().getAddress().toString() + : null; } @Override 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 aa6badf9271..0ed00a507e9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 TraceableServerHttpResponse implements TraceableResponse { @Override public int getStatus() { - return (this.response.getStatusCode() != null) - ? this.response.getStatusCode().value() : 200; + return (this.response.getStatusCode() != null) ? this.response.getStatusCode().value() : 200; } @Override 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 40cfb276840..3422545130a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 6c7325bafd2..339db60f0ba 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); @@ -57,8 +56,7 @@ 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(); } @@ -66,8 +64,7 @@ public class AuditEventTests { public void nullTimestamp() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Timestamp must not be null"); - new AuditEvent(null, "phil", "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", (Object) "b")); } @Test @@ -81,12 +78,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 7466844e757..a1899e9a5e0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 533625a33ca..75a21d66673 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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")); } @@ -98,8 +88,7 @@ public class AuditEventsEndpointWebIntegrationTests { } 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 28befb02355..354836e2f46 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +103,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 f19f3f463bd..6fb7db67e7a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/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/context/ShutdownEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java index d0e4db6e9e3..3079b7678a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 80e5b2c58ef..d311f800e95 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 bf14eea976d..c7ae6153e19 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 2bf6d22bcf2..246822235d3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 606e7b45f8c..76d46f9c56a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 c6acb2c4f43..1f0385b3f0c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -63,8 +62,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"); }); } @@ -72,8 +70,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"); @@ -83,8 +80,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("******"); @@ -94,8 +90,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"); @@ -106,26 +101,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"); }); } @@ -133,8 +123,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); }); } @@ -142,8 +131,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); }); } @@ -151,8 +139,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"); }); } @@ -160,8 +147,7 @@ public class ConfigurationPropertiesReportEndpointTests { @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"); }); } @@ -170,8 +156,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); @@ -184,11 +169,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); @@ -197,28 +180,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 c9f1f807575..a9792d38b7d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,25 +60,22 @@ public class CouchbaseHealthIndicatorTests { @Test public void couchbaseOperationsIsUp() throws UnknownHostException { BucketInfo bucketInfo = mock(BucketInfo.class); - given(bucketInfo.nodeList()).willReturn( - Collections.singletonList(InetAddress.getByName("127.0.0.1"))); + given(bucketInfo.nodeList()).willReturn(Collections.singletonList(InetAddress.getByName("127.0.0.1"))); BucketManager bucketManager = mock(BucketManager.class); given(bucketManager.info(2000, TimeUnit.MILLISECONDS)).willReturn(bucketInfo); Bucket bucket = mock(Bucket.class); given(bucket.bucketManager()).willReturn(bucketManager); ClusterInfo clusterInfo = mock(ClusterInfo.class); - given(clusterInfo.getAllVersions()) - .willReturn(Collections.singletonList(new Version(1, 2, 3))); + given(clusterInfo.getAllVersions()).willReturn(Collections.singletonList(new Version(1, 2, 3))); CouchbaseOperations couchbaseOperations = mock(CouchbaseOperations.class); given(couchbaseOperations.getCouchbaseBucket()).willReturn(bucket); given(couchbaseOperations.getCouchbaseClusterInfo()).willReturn(clusterInfo); @SuppressWarnings("deprecation") - CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator( - couchbaseOperations, Duration.ofSeconds(2)); + CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(couchbaseOperations, + Duration.ofSeconds(2)); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnly(entry("versions", "1.2.3"), - entry("nodes", "/127.0.0.1")); + assertThat(health.getDetails()).containsOnly(entry("versions", "1.2.3"), entry("nodes", "/127.0.0.1")); verify(clusterInfo).getAllVersions(); verify(bucketInfo).nodeList(); } @@ -86,28 +83,26 @@ public class CouchbaseHealthIndicatorTests { @Test public void couchbaseOperationsTimeout() { BucketManager bucketManager = mock(BucketManager.class); - given(bucketManager.info(1500, TimeUnit.MILLISECONDS)).willThrow( - new RuntimeException(new TimeoutException("timeout, expected"))); + given(bucketManager.info(1500, TimeUnit.MILLISECONDS)) + .willThrow(new RuntimeException(new TimeoutException("timeout, expected"))); Bucket bucket = mock(Bucket.class); given(bucket.bucketManager()).willReturn(bucketManager); CouchbaseOperations couchbaseOperations = mock(CouchbaseOperations.class); given(couchbaseOperations.getCouchbaseBucket()).willReturn(bucket); @SuppressWarnings("deprecation") - CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator( - couchbaseOperations, Duration.ofMillis(1500)); + CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(couchbaseOperations, + Duration.ofMillis(1500)); Health health = healthIndicator.health(); - assertThat((String) health.getDetails().get("error")) - .contains("timeout, expected"); + assertThat((String) health.getDetails().get("error")).contains("timeout, expected"); } @Test public void couchbaseOperationsIsDown() { CouchbaseOperations couchbaseOperations = mock(CouchbaseOperations.class); - given(couchbaseOperations.getCouchbaseClusterInfo()) - .willThrow(new IllegalStateException("test, expected")); + given(couchbaseOperations.getCouchbaseClusterInfo()).willThrow(new IllegalStateException("test, expected")); @SuppressWarnings("deprecation") - CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator( - couchbaseOperations, Duration.ofSeconds(1)); + CouchbaseHealthIndicator healthIndicator = new CouchbaseHealthIndicator(couchbaseOperations, + Duration.ofSeconds(1)); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat((String) health.getDetails().get("error")).contains("test, expected"); @@ -119,18 +114,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"); + 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"); 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(); } @@ -140,21 +132,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"); + 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"); 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/elasticsearch/ElasticsearchHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicatorTests.java index 32500110f42..79e094fe508 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -85,16 +84,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); } @@ -103,8 +99,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); @@ -114,8 +109,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(); @@ -133,30 +127,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") @@ -173,10 +162,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, false)); + super("test-cluster", new String[0], new ClusterState(null, 0, null, null, RoutingTable.builder().build(), + DiscoveryNodes.builder().build(), ClusterBlocks.builder().build(), null, false)); this.status = status; } @@ -222,14 +209,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 c7db324d1b4..f4d5eedecb6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsUp() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(4, 0)); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(4, 0)); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); } @@ -59,8 +58,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); } @@ -68,15 +67,14 @@ public class ElasticsearchJestHealthIndicatorTests { @SuppressWarnings("unchecked") @Test public void elasticsearchIsOutOfService() throws IOException { - given(this.jestClient.execute(any(Action.class))) - .willReturn(createJestResult(4, 1)); + given(this.jestClient.execute(any(Action.class))).willReturn(createJestResult(4, 1)); Health health = this.healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.OUT_OF_SERVICE); } private static JestResult createJestResult(int shards, int failedShards) { - String json = String.format("{_shards: {\n" + "total: %s,\n" + "successful: %s,\n" - + "failed: %s\n" + "}}", shards, shards - failedShards, failedShards); + String json = String.format("{_shards: {\n" + "total: %s,\n" + "successful: %s,\n" + "failed: %s\n" + "}}", + shards, shards - failedShards, failedShards); SearchResult searchResult = new SearchResult(new Gson()); 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/endpoint/EndpointIdTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java index 63117791fb1..3c09bba4289 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 ff97d25187f..90cef9a2732 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 31e759d5a8d..51b25080038 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a0359c817c2..25ca65bc60f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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); } @@ -225,8 +217,8 @@ public class DiscoveredOperationsFactoryTests { @Override @Deprecated - public OperationInvoker apply(String endpointId, OperationType operationType, - OperationParameters parameters, OperationInvoker invoker) { + public OperationInvoker apply(String endpointId, OperationType operationType, OperationParameters parameters, + OperationInvoker invoker) { throw new IllegalStateException(); } 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 524bfd47ac3..46bf50963f5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 DiscovererEndpointFilterTests { @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(); } @@ -75,18 +73,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); @@ -94,11 +89,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 7c555921798..1ec9a7bbed4 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 @@ -73,32 +73,32 @@ public class EndpointDiscovererTests { public void createWhenApplicationContextIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ApplicationContext must not be null"); - new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), - Collections.emptyList(), Collections.emptyList()); + new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), Collections.emptyList(), + Collections.emptyList()); } @Test public void createWhenParameterValueMapperIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ParameterValueMapper must not be null"); - new TestEndpointDiscoverer(mock(ApplicationContext.class), null, - Collections.emptyList(), Collections.emptyList()); + new TestEndpointDiscoverer(mock(ApplicationContext.class), null, Collections.emptyList(), + Collections.emptyList()); } @Test public void createWhenInvokerAdvisorsIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("InvokerAdvisors must not be null"); - new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), null, Collections.emptyList()); + new TestEndpointDiscoverer(mock(ApplicationContext.class), mock(ParameterValueMapper.class), null, + Collections.emptyList()); } @Test public void createWhenFiltersIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Filters must not be null"); - new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), Collections.emptyList(), null); + new TestEndpointDiscoverer(mock(ApplicationContext.class), mock(ParameterValueMapper.class), + Collections.emptyList(), null); } @Test @@ -126,16 +126,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)); }); } @@ -151,27 +148,21 @@ public class EndpointDiscovererTests { @Test public void getEndpointsWhenEndpointsArePrefixedWithScopedTargetShouldRegisterOnlyOneEndpoint() { load(ScopedTargetEndpointConfiguration.class, (context) -> { - TestEndpoint expectedEndpoint = context - .getBean(ScopedTargetEndpointConfiguration.class).testEndpoint(); - Collection endpoints = new TestEndpointDiscoverer( - context).getEndpoints(); - assertThat(endpoints).flatExtracting(TestExposableEndpoint::getEndpointBean) - .containsOnly(expectedEndpoint); + TestEndpoint expectedEndpoint = context.getBean(ScopedTargetEndpointConfiguration.class).testEndpoint(); + 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 +171,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 +183,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 +201,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 +209,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 +229,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 +247,18 @@ public class EndpointDiscovererTests { String id = endpoint.getId(); return !id.equals("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 +276,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 +381,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 +441,7 @@ public class EndpointDiscovererTests { } - @EndpointExtension(endpoint = SpecializedTestEndpoint.class, - filter = SpecializedEndpointFilter.class) + @EndpointExtension(endpoint = SpecializedTestEndpoint.class, filter = SpecializedEndpointFilter.class) public static class SpecializedExtension { @ReadOperation @@ -520,49 +478,43 @@ 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, String id, - boolean enabledByDefault, Collection operations) { + protected TestExposableEndpoint createEndpoint(Object endpointBean, String id, boolean enabledByDefault, + Collection operations) { throw new IllegalStateException(); } @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(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected TestOperation createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return new TestOperation(operationMethod, invoker); } @@ -574,8 +526,8 @@ public class EndpointDiscovererTests { } - static class SpecializedEndpointDiscoverer extends - EndpointDiscoverer { + static class SpecializedEndpointDiscoverer + extends EndpointDiscoverer { SpecializedEndpointDiscoverer(ApplicationContext applicationContext) { this(applicationContext, Collections.emptyList()); @@ -583,28 +535,24 @@ 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, - String id, boolean enabledByDefault, + protected SpecializedExposableEndpoint createEndpoint(Object endpointBean, String id, boolean enabledByDefault, Collection operations) { throw new IllegalStateException(); } @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(String endpointId, - DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { + protected SpecializedOperation createOperation(String endpointId, DiscoveredOperationMethod operationMethod, + OperationInvoker invoker) { return new SpecializedOperation(operationMethod, invoker); } @@ -618,20 +566,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); } @@ -641,8 +586,7 @@ public class EndpointDiscovererTests { private final OperationInvoker invoker; - TestOperation(DiscoveredOperationMethod operationMethod, - OperationInvoker invoker) { + TestOperation(DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { super(operationMethod, invoker); this.invoker = invoker; } @@ -655,8 +599,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 abd86e9d291..0622f6d6f61 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +48,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); } @@ -63,8 +60,7 @@ 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); try { mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123"); fail("Did not throw"); @@ -79,8 +75,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(); } @@ -88,11 +83,9 @@ public class ConversionServiceParameterValueMapperTests { @Test public void createWithConversionServiceShouldNotRegisterIsoOffsetDateTimeConverter() { ConversionService conversionService = new DefaultConversionService(); - ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( - conversionService); + ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); this.thrown.expect(ParameterMappingException.class); - mapper.mapParameterValue(new TestOperationParameter(OffsetDateTime.class), - "2011-12-03T10:15:30+01:00"); + mapper.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 f9e6540faa0..08e583594b4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 aa3a639fc5d..9f29beaba23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 0dfe2e2fc20..949d82e015e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +47,9 @@ public class OperationMethodParametersTests { @Rule public ExpectedException thrown = ExpectedException.none(); - 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() { @@ -71,45 +69,43 @@ public class OperationMethodParametersTests { public void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Failed to extract parameter names"); - new OperationMethodParameters(this.exampleMethod, - mock(ParameterNameDiscoverer.class)); + new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class)); } @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 a7ccc9c7c9c..c6d88f48b5d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 OperationMethodTests { @Rule public ExpectedException thrown = ExpectedException.none(); - private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", - String.class); + private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); @Test public void createWhenMethodIsNullShouldThrowException() { @@ -57,22 +56,19 @@ public class OperationMethodTests { @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 d031e339578..ad99bfc1d96 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +53,16 @@ public class ReflectiveOperationInvokerTests { @Before 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() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Target must not be null"); - new ReflectiveOperationInvoker(null, this.operationMethod, - this.parameterValueMapper); + new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper); } @Test @@ -84,39 +81,38 @@ public class ReflectiveOperationInvokerTests { @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); + ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, + this.parameterValueMapper); this.thrown.expect(MissingParametersException.class); - invoker.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.singletonMap("name", null))); + 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 530f5ed9742..029907e1171 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +64,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); } @@ -82,8 +81,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")); } @@ -92,8 +91,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")); } @@ -107,38 +106,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(ReflectionTestUtils.getField(advised, "invoker")) - .isEqualTo(this.invoker); + assertThat(ReflectionTestUtils.getField(advised, "invoker")).isEqualTo(this.invoker); assertThat(ReflectionTestUtils.getField(advised, "timeToLive")).isEqualTo(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); } @@ -152,13 +145,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 fc9858ece9f..59a90272b4f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -87,8 +86,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); @@ -116,8 +114,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 cfeb816e0e4..60582c9f888 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 EndpointMBeanTests { @Rule public ExpectedException thrown = ExpectedException.none(); - private TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( - new TestJmxOperation()); + private TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation()); private TestJmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); @@ -85,20 +84,17 @@ 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); this.thrown.expect(MBeanException.class); this.thrown.expectCause(instanceOf(IllegalStateException.class)); @@ -109,10 +105,9 @@ public class EndpointMBeanTests { @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); this.thrown.expect(MBeanException.class); this.thrown.expectCause(instanceOf(UnsupportedOperationException.class)); @@ -121,8 +116,7 @@ public class EndpointMBeanTests { } @Test - public void invokeWhenActionNameIsNotAnOperationShouldThrowException() - throws MBeanException, ReflectionException { + public void invokeWhenActionNameIsNotAnOperationShouldThrowException() throws MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); this.thrown.expect(ReflectionException.class); this.thrown.expectCause(instanceOf(IllegalArgumentException.class)); @@ -131,24 +125,19 @@ public class EndpointMBeanTests { } @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 @@ -166,8 +155,7 @@ public class EndpointMBeanTests { } @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); @@ -176,8 +164,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); @@ -195,8 +182,8 @@ public class EndpointMBeanTests { } @Test - public void setAttributeShouldThrowException() throws AttributeNotFoundException, - InvalidAttributeValueException, MBeanException, ReflectionException { + public void setAttributeShouldThrowException() + throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); this.thrown.expect(AttributeNotFoundException.class); this.thrown.expectMessage("EndpointMBeans do not support attributes"); 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 9175a0209d4..65d877ce73c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 b0e1260688b..d6804e62d11 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JmxEndpointExporterTests { @Mock private MBeanServer mBeanServer; - private EndpointObjectNameFactory objectNameFactory = spy( - new TestEndpointObjectNameFactory()); + private EndpointObjectNameFactory objectNameFactory = spy(new TestEndpointObjectNameFactory()); private JmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); @@ -76,51 +75,45 @@ public class JmxEndpointExporterTests { @Before 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() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("MBeanServer must not be null"); - new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, - this.endpoints); + new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints); } @Test public void createWhenObjectNameFactoryIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ObjectNameFactory must not be null"); - new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, - this.endpoints); + new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints); } @Test public void createWhenResponseMapperIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ResponseMapper must not be null"); - new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, - this.endpoints); + new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints); } @Test public void createWhenEndpointsIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Endpoints must not be null"); - new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, - this.responseMapper, null); + new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null); } @Test 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 @@ -156,26 +149,23 @@ 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)); + willThrow(new MBeanRegistrationException(new RuntimeException())).given(this.mBeanServer) + .unregisterMBean(any(ObjectName.class)); this.thrown.expect(JmxException.class); this.thrown.expectMessage("Failed to unregister MBean with ObjectName 'boot"); this.exporter.destroy(); @@ -184,14 +174,11 @@ public class JmxEndpointExporterTests { /** * 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 12c90a1dc48..c27446b740a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 fbd50807c16..79b841c05c0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 69b889098c6..cd233d8deef 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 @@ -64,8 +64,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 @@ -75,29 +74,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); @@ -108,8 +102,7 @@ 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")); }); } @@ -117,9 +110,8 @@ public class JmxEndpointDiscovererTests { public void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { load(TestJmxEndpointExtension.class, (discoverer) -> { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': " - + "no endpoint found with id 'test'"); + this.thrown.expectMessage("Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': " + + "no endpoint found with id 'test'"); discoverer.getEndpoints(); }); } @@ -140,8 +132,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); @@ -156,37 +148,29 @@ 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 @@ -243,21 +227,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); @@ -265,16 +245,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); @@ -288,11 +266,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; } @@ -308,14 +284,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); } } @@ -486,16 +459,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) { @@ -503,8 +475,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 6c85eec9a6c..1e50da16c47 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 32a04311628..d72aff9cae2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 838b37f2ecf..c42c3e31f4a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +53,14 @@ public class EndpointMediaTypesTests { @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 2b741644b2a..7fada75d15f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +89,15 @@ public class EndpointServletTests { @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 @@ -119,28 +117,26 @@ public class EndpointServletTests { @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")); } 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/PathMappedEndpointsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java index fe1f2f3b0a8..720f96a98b3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +61,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 @@ -88,8 +86,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 @@ -107,8 +104,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 @@ -149,8 +145,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 5a4c4897f59..32f31ab37d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ServletEndpointRegistrarTests { @Before 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 @@ -89,37 +88,29 @@ 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")); } 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 8d79907362f..ffc7bacfab9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 00d777c3e26..81320872533 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 7e9eab92d9d..3e311d1eb3a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +57,16 @@ 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( - ApplicationContext applicationContext) { + public WebEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext) { ParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); - return new WebEndpointDiscoverer(applicationContext, parameterMapper, - endpointMediaTypes(), PathMapper.useEndpointId(), Collections.emptyList(), - Collections.emptyList()); + return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes(), + PathMapper.useEndpointId(), 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 b5f3e51b4ae..cb170e49548 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,40 +59,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); })); } @@ -101,31 +92,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); })); } @@ -134,13 +118,10 @@ 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")); })); } @@ -149,8 +130,7 @@ public class ControllerEndpointDiscovererTests { this.contextRunner.withUserConfiguration(TestControllerWithOperation.class) .run(assertDiscoverer((discoverer) -> { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "ControllerEndpoints must not declare operations"); + this.thrown.expectMessage("ControllerEndpoints must not declare operations"); discoverer.getEndpoints(); })); } @@ -158,8 +138,8 @@ public class ControllerEndpointDiscovererTests { private ContextConsumer assertDiscoverer( Consumer consumer) { return (context) -> { - ControllerEndpointDiscoverer discoverer = new ControllerEndpointDiscoverer( - context, PathMapper.useEndpointId(), Collections.emptyList()); + ControllerEndpointDiscoverer discoverer = new ControllerEndpointDiscoverer(context, + PathMapper.useEndpointId(), Collections.emptyList()); consumer.accept(discoverer); }; } @@ -170,8 +150,7 @@ public class ControllerEndpointDiscovererTests { } @Configuration - @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 0581565d80d..b085c970a7b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,37 +68,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); })); @@ -108,10 +101,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")); })); @@ -122,8 +113,7 @@ public class ServletEndpointDiscovererTests { this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class) .run(assertDiscoverer((discoverer) -> { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "ServletEndpoints must not declare operations"); + this.thrown.expectMessage("ServletEndpoints must not declare operations"); discoverer.getEndpoints(); })); } @@ -140,8 +130,7 @@ public class ServletEndpointDiscovererTests { @Test public void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { - this.contextRunner - .withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) + this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) .run(assertDiscoverer((discoverer) -> { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("must supply an EndpointServlet"); @@ -162,8 +151,8 @@ public class ServletEndpointDiscovererTests { private ContextConsumer assertDiscoverer( Consumer consumer) { return (context) -> { - ServletEndpointDiscoverer discoverer = new ServletEndpointDiscoverer(context, - PathMapper.useEndpointId(), Collections.emptyList()); + ServletEndpointDiscoverer discoverer = new ServletEndpointDiscoverer(context, PathMapper.useEndpointId(), + Collections.emptyList()); consumer.accept(discoverer); }; } @@ -223,8 +212,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 bb3d2c6399d..bd1abddf016 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +74,14 @@ 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) -> { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Invalid extension 'endpointExtension': no endpoint found with id '" - + "test'"); + this.thrown.expectMessage("Invalid extension 'endpointExtension': no endpoint found with id '" + "test'"); discoverer.getEndpoints(); }); } @@ -92,8 +89,7 @@ public class WebEndpointDiscovererTests { @Test public void getEndpointsWhenHasFilteredEndpointShouldOnlyDiscoverWebEndpoints() { load(MultipleEndpointsConfiguration.class, (discoverer) -> { - Map endpoints = mapEndpoints( - discoverer.getEndpoints()); + Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); }); } @@ -101,41 +97,34 @@ 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"))); }); } @@ -162,9 +151,9 @@ public class WebEndpointDiscovererTests { public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpointConfiguration.class, (discoverer) -> { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to map duplicate endpoint operations: " - + "[web request predicate GET to path 'test' " - + "produces: application/json] to clashingOperationsEndpoint"); + this.thrown.expectMessage( + "Unable to map duplicate endpoint operations: " + "[web request predicate GET to path 'test' " + + "produces: application/json] to clashingOperationsEndpoint"); discoverer.getEndpoints(); }); } @@ -192,85 +181,70 @@ public class WebEndpointDiscovererTests { @Test public void getEndpointsWhenHasCacheWithTtlShouldCacheReadOperationWithTtlValue() { load((id) -> 500L, (id) -> id, TestEndpointConfiguration.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(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); + 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, (id) -> id, configuration, consumer); } - private void load(Function timeToLive, - PathMapper endpointPathMapper, Class configuration, + private void load(Function timeToLive, PathMapper endpointPathMapper, Class configuration, Consumer consumer) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - configuration); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configuration); try { 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, endpointPathMapper, - Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), + WebEndpointDiscoverer discoverer = new WebEndpointDiscoverer(context, parameterMapper, mediaTypes, + endpointPathMapper, Collections.singleton(new CachingOperationInvokerAdvisor(timeToLive)), Collections.emptyList()); consumer.accept(discoverer); } @@ -279,18 +253,14 @@ public class WebEndpointDiscovererTests { } } - 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( @@ -301,8 +271,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)); @@ -681,18 +650,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 551dcce33a3..de1863d4c1c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 eb1bb2e383b..749780191db 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,56 +62,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 - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, WebFluxAutoConfiguration.class }) static class EndpointConfiguration { @@ -126,10 +118,9 @@ public class ControllerEndpointHandlerMappingIntegrationTests { } @Bean - public ControllerEndpointDiscoverer webEndpointDiscoverer( - ApplicationContext applicationContext) { - return new ControllerEndpointDiscoverer(applicationContext, - PathMapper.useEndpointId(), Collections.emptyList()); + public ControllerEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext) { + return new ControllerEndpointDiscoverer(applicationContext, PathMapper.useEndpointId(), + Collections.emptyList()); } @Bean @@ -151,8 +142,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 4a4849b7a8e..4680611fd28 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -70,8 +69,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")) @@ -98,29 +96,24 @@ public class ControllerEndpointHandlerMappingTests { 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 01d06909bc4..c93df33052e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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, @@ -72,30 +72,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); }); } @@ -123,16 +120,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())); } @@ -151,14 +145,11 @@ public class WebFluxEndpointIntegrationTests extends return new WebFilter() { @Override - public Mono filter(ServerWebExchange exchange, - WebFilterChain chain) { - return chain.filter(exchange).subscriberContext( - ReactiveSecurityContextHolder.withAuthentication( - new UsernamePasswordAuthenticationToken("Alice", - "secret", - Arrays.asList(new SimpleGrantedAuthority( - "ROLE_ACTUATOR"))))); + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + return 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 6c38ba7c511..84436135436 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,57 +61,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 - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class }) static class EndpointConfiguration { @Bean @@ -120,10 +111,9 @@ public class ControllerEndpointHandlerMappingIntegrationTests { } @Bean - public ControllerEndpointDiscoverer webEndpointDiscoverer( - ApplicationContext applicationContext) { - return new ControllerEndpointDiscoverer(applicationContext, - PathMapper.useEndpointId(), Collections.emptyList()); + public ControllerEndpointDiscoverer webEndpointDiscoverer(ApplicationContext applicationContext) { + return new ControllerEndpointDiscoverer(applicationContext, PathMapper.useEndpointId(), + Collections.emptyList()); } @Bean @@ -145,8 +135,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 46e5a2fc9e4..18b6b0a1796 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()) @@ -95,18 +94,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 a3187ec048f..621d755c4a1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 - @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 cdd8b7f0588..c1ef5f3517c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +44,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 e3aa4b11542..f88d9184651 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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); @@ -103,8 +103,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() { @@ -118,8 +117,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() { @@ -174,10 +172,9 @@ 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) { @@ -188,22 +185,20 @@ abstract class AbstractWebEndpointRunner extends BlockJUnit4ClassRunner { 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); } @@ -212,16 +207,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 d1a7e92c449..4c54e045222 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JerseyEndpointsRunner extends AbstractWebEndpointRunner { } @Configuration - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - JerseyAutoConfiguration.class }) + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, JerseyAutoConfiguration.class }) static class JerseyEndpointConfiguration { private final ApplicationContext applicationContext; @@ -96,18 +95,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, PathMapper.useEndpointId(), + 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, PathMapper.useEndpointId(), 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 eced1f65789..cc2556f7e74 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +69,8 @@ class WebFluxEndpointsRunner extends AbstractWebEndpointRunner { } @Configuration - @ImportAutoConfiguration({ JacksonAutoConfiguration.class, - WebFluxAutoConfiguration.class }) - static class WebFluxEndpointConfiguration - implements ApplicationListener { + @ImportAutoConfiguration({ JacksonAutoConfiguration.class, WebFluxAutoConfiguration.class }) + static class WebFluxEndpointConfiguration implements ApplicationListener { private final ApplicationContext applicationContext; @@ -102,18 +100,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, PathMapper.useEndpointId(), + 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, PathMapper.useEndpointId(), 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 bd0f746abd3..6fbffdaeb2d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +67,8 @@ class WebMvcEndpointRunner extends AbstractWebEndpointRunner { } @Configuration - @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; @@ -85,18 +84,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, PathMapper.useEndpointId(), + 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, PathMapper.useEndpointId(), 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 1900e1d2f69..8c4ae185fa7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 89573638329..8b3d6a8daea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 7dbe05445d9..40b74fcb307 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,28 +43,22 @@ public class FlywayEndpointTests { @Test public void flywayReportIsProduced() { - new ApplicationContextRunner().withUserConfiguration(Config.class) - .run((context) -> { - Map flywayBeans = context - .getBean(FlywayEndpoint.class).flywayBeans().getContexts() - .get(context.getId()).getFlywayBeans(); - assertThat(flywayBeans).hasSize(1); - assertThat(flywayBeans.values().iterator().next().getMigrations()) - .hasSize(3); - }); + new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> { + Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() + .getContexts().get(context.getId()).getFlywayBeans(); + assertThat(flywayBeans).hasSize(1); + assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); + }); } @Test public void whenFlywayHasBeenBaselinedFlywayReportIsProduced() { - new ApplicationContextRunner() - .withUserConfiguration(BaselinedFlywayConfig.class, Config.class) + new ApplicationContextRunner().withUserConfiguration(BaselinedFlywayConfig.class, Config.class) .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); + 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/CompositeHealthIndicatorFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactoryTests.java index abadcfef3b4..0ff87bb8c25 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthIndicatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 CompositeHealthIndicatorFactoryTests { public void upAndUpIsAggregatedToUp() { Map healthIndicators = new HashMap<>(); healthIndicators.put("up", () -> new Health.Builder().status(Status.UP).build()); - healthIndicators.put("upAgain", - () -> new Health.Builder().status(Status.UP).build()); + healthIndicators.put("upAgain", () -> new Health.Builder().status(Status.UP).build()); HealthIndicator healthIndicator = createHealthIndicator(healthIndicators); assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.UP); } @@ -46,8 +45,7 @@ public class CompositeHealthIndicatorFactoryTests { public void upAndDownIsAggregatedToDown() { Map healthIndicators = new HashMap<>(); healthIndicators.put("up", () -> new Health.Builder().status(Status.UP).build()); - healthIndicators.put("down", - () -> new Health.Builder().status(Status.DOWN).build()); + healthIndicators.put("down", () -> new Health.Builder().status(Status.DOWN).build()); HealthIndicator healthIndicator = createHealthIndicator(healthIndicators); assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.DOWN); } @@ -60,10 +58,9 @@ public class CompositeHealthIndicatorFactoryTests { assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.UNKNOWN); } - private HealthIndicator createHealthIndicator( - Map healthIndicators) { - return new CompositeHealthIndicatorFactory() - .createHealthIndicator(new OrderedHealthAggregator(), healthIndicators); + private HealthIndicator createHealthIndicator(Map healthIndicators) { + return new CompositeHealthIndicatorFactory().createHealthIndicator(new OrderedHealthAggregator(), + healthIndicators); } } 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 8b0037a3461..f0dd5822620 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +51,9 @@ public class CompositeHealthIndicatorTests { @Before 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.three.health()) - .willReturn(new Health.Builder().unknown().withDetail("3", "3").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()); + given(this.three.health()).willReturn(new Health.Builder().unknown().withDetail("3", "3").build()); this.healthAggregator = new OrderedHealthAggregator(); } @@ -66,8 +63,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", @@ -81,8 +77,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); composite.addHealthIndicator("three", this.three); Health result = composite.health(); assertThat(result.getDetails()).hasSize(3); @@ -96,8 +91,7 @@ public class CompositeHealthIndicatorTests { @Test public void createWithoutAndAdd() { - CompositeHealthIndicator composite = new CompositeHealthIndicator( - this.healthAggregator); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator); composite.addHealthIndicator("one", this.one); composite.addHealthIndicator("two", this.two); Health result = composite.health(); @@ -113,18 +107,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); + CompositeHealthIndicator innerComposite = new CompositeHealthIndicator(this.healthAggregator, indicators); + CompositeHealthIndicator composite = new CompositeHealthIndicator(this.healthAggregator); composite.addHealthIndicator("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/CompositeReactiveHealthIndicatorFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactoryTests.java index 5d8192e5272..fdad330a919 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 CompositeReactiveHealthIndicatorFactoryTests { @Test public void defaultHealthIndicatorNameFactory() { ReactiveHealthIndicator healthIndicator = new CompositeReactiveHealthIndicatorFactory() - .createReactiveHealthIndicator(new OrderedHealthAggregator(), Collections - .singletonMap("myHealthIndicator", () -> Mono.just(UP)), null); + .createReactiveHealthIndicator(new OrderedHealthAggregator(), + Collections.singletonMap("myHealthIndicator", () -> Mono.just(UP)), null); StepVerifier.create(healthIndicator.health()).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).containsOnlyKeys("my"); @@ -65,8 +65,7 @@ public class CompositeReactiveHealthIndicatorFactoryTests { @Test public void healthIndicatorIsAdapted() { ReactiveHealthIndicator healthIndicator = createHealthIndicator( - Collections.singletonMap("test", () -> Mono.just(UP)), - Collections.singletonMap("regular", () -> DOWN)); + Collections.singletonMap("test", () -> Mono.just(UP)), Collections.singletonMap("regular", () -> DOWN)); StepVerifier.create(healthIndicator.health()).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.DOWN); assertThat(h.getDetails()).containsOnlyKeys("test", "regular"); @@ -75,8 +74,7 @@ public class CompositeReactiveHealthIndicatorFactoryTests { @Test public void reactiveHealthIndicatorTakesPrecedence() { - ReactiveHealthIndicator reactiveHealthIndicator = mock( - ReactiveHealthIndicator.class); + ReactiveHealthIndicator reactiveHealthIndicator = mock(ReactiveHealthIndicator.class); given(reactiveHealthIndicator.health()).willReturn(Mono.just(UP)); HealthIndicator regularHealthIndicator = mock(HealthIndicator.class); given(regularHealthIndicator.health()).willReturn(UP); @@ -91,12 +89,10 @@ public class CompositeReactiveHealthIndicatorFactoryTests { verify(regularHealthIndicator, never()).health(); } - private ReactiveHealthIndicator createHealthIndicator( - Map reactiveHealthIndicators, + private ReactiveHealthIndicator createHealthIndicator(Map reactiveHealthIndicators, Map healthIndicators) { - return new CompositeReactiveHealthIndicatorFactory((n) -> n) - .createReactiveHealthIndicator(new OrderedHealthAggregator(), - reactiveHealthIndicators, healthIndicators); + return new CompositeReactiveHealthIndicatorFactory((n) -> n).createReactiveHealthIndicator( + new OrderedHealthAggregator(), reactiveHealthIndicators, healthIndicators); } } 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 2716c3345cf..0f9033fd42f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +31,13 @@ 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(); private OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator(); - private CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator( - this.healthAggregator); + private CompositeReactiveHealthIndicator indicator = new CompositeReactiveHealthIndicator(this.healthAggregator); @Test public void singleIndicator() { @@ -54,11 +52,10 @@ public class CompositeReactiveHealthIndicatorTests { @Test public void longHealth() { for (int i = 0; i < 50; i++) { - this.indicator.addHealthIndicator("test" + i, - new TimeoutHealth(10000, Status.UP)); + this.indicator.addHealthIndicator("test" + i, new TimeoutHealth(10000, Status.UP)); } - StepVerifier.withVirtualTime(this.indicator::health).expectSubscription() - .thenAwait(Duration.ofMillis(10000)).consumeNextWith((h) -> { + StepVerifier.withVirtualTime(this.indicator::health).expectSubscription().thenAwait(Duration.ofMillis(10000)) + .consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).hasSize(50); }).verifyComplete(); @@ -68,8 +65,7 @@ public class CompositeReactiveHealthIndicatorTests { @Test public void timeoutReachedUsesFallback() { this.indicator.addHealthIndicator("slow", new TimeoutHealth(10000, Status.UP)) - .addHealthIndicator("fast", new TimeoutHealth(10, Status.UP)) - .timeoutStrategy(100, UNKNOWN_HEALTH); + .addHealthIndicator("fast", new TimeoutHealth(10, Status.UP)).timeoutStrategy(100, UNKNOWN_HEALTH); StepVerifier.create(this.indicator.health()).consumeNextWith((h) -> { assertThat(h.getStatus()).isEqualTo(Status.UP); assertThat(h.getDetails()).containsOnlyKeys("slow", "fast"); @@ -81,10 +77,9 @@ public class CompositeReactiveHealthIndicatorTests { @Test public void timeoutNotReached() { this.indicator.addHealthIndicator("slow", new TimeoutHealth(10000, Status.UP)) - .addHealthIndicator("fast", new TimeoutHealth(10, Status.UP)) - .timeoutStrategy(20000, null); - StepVerifier.withVirtualTime(this.indicator::health).expectSubscription() - .thenAwait(Duration.ofMillis(10000)).consumeNextWith((h) -> { + .addHealthIndicator("fast", new TimeoutHealth(10, Status.UP)).timeoutStrategy(20000, null); + StepVerifier.withVirtualTime(this.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); @@ -105,8 +100,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/HealthEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java index 2f17b59b080..b1bcda7fc3b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +36,9 @@ public class HealthEndpointTests { @Test public void statusAndFullDetailsAreExposed() { Map healthIndicators = new HashMap<>(); - healthIndicators.put("up", () -> new Health.Builder().status(Status.UP) - .withDetail("first", "1").build()); - healthIndicators.put("upAgain", () -> new Health.Builder().status(Status.UP) - .withDetail("second", "2").build()); - HealthEndpoint endpoint = new HealthEndpoint( - createHealthIndicator(healthIndicators)); + healthIndicators.put("up", () -> new Health.Builder().status(Status.UP).withDetail("first", "1").build()); + healthIndicators.put("upAgain", () -> new Health.Builder().status(Status.UP).withDetail("second", "2").build()); + HealthEndpoint endpoint = new HealthEndpoint(createHealthIndicator(healthIndicators)); Health health = endpoint.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsOnlyKeys("up", "upAgain"); @@ -51,10 +48,9 @@ public class HealthEndpointTests { assertThat(upAgainHealth.getDetails()).containsOnly(entry("second", "2")); } - private HealthIndicator createHealthIndicator( - Map healthIndicators) { - return new CompositeHealthIndicatorFactory() - .createHealthIndicator(new OrderedHealthAggregator(), healthIndicators); + private HealthIndicator createHealthIndicator(Map healthIndicators) { + return new CompositeHealthIndicatorFactory().createHealthIndicator(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 bdf40c9f8f9..9c2a7d5f32e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +45,16 @@ 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() { - context.getBean("alphaHealthIndicator", TestHealthIndicator.class) - .setHealth(Health.down().build()); - client.get().uri("/actuator/health").exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status") - .isEqualTo("DOWN").jsonPath("details.alpha.status").isEqualTo("DOWN") + context.getBean("alphaHealthIndicator", TestHealthIndicator.class).setHealth(Health.down().build()); + client.get().uri("/actuator/health").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody().jsonPath("status").isEqualTo("DOWN").jsonPath("details.alpha.status").isEqualTo("DOWN") .jsonPath("details.bravo.status").isEqualTo("UP"); } @@ -64,21 +62,17 @@ public class HealthEndpointWebIntegrationTests { public static class TestConfiguration { @Bean - public HealthEndpoint healthEndpoint( - Map healthIndicators) { - return new HealthEndpoint( - new CompositeHealthIndicatorFactory().createHealthIndicator( - new OrderedHealthAggregator(), healthIndicators)); + public HealthEndpoint healthEndpoint(Map healthIndicators) { + return new HealthEndpoint(new CompositeHealthIndicatorFactory() + .createHealthIndicator(new OrderedHealthAggregator(), healthIndicators)); } @Bean - public HealthEndpointWebExtension healthWebEndpointExtension( - Map healthIndicators) { + public HealthEndpointWebExtension healthWebEndpointExtension(Map healthIndicators) { return new HealthEndpointWebExtension( - new CompositeHealthIndicatorFactory().createHealthIndicator( - new OrderedHealthAggregator(), healthIndicators), - new HealthWebEndpointResponseMapper(new HealthStatusHttpMapper(), - ShowDetails.ALWAYS, + new CompositeHealthIndicatorFactory().createHealthIndicator(new OrderedHealthAggregator(), + healthIndicators), + 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 636e6f7f8f0..800d5dd7fa7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 d817aad98ba..6d978e46f5c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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().get("a")).isEqualTo("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); @@ -74,17 +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().get("a")).isEqualTo("b"); - assertThat(health.getDetails().get("error")) - .isEqualTo("java.lang.RuntimeException: bang"); + assertThat(health.getDetails().get("error")).isEqualTo("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().get("a")).isEqualTo("b"); assertThat(health.getDetails().get("c")).isEqualTo("d"); } @@ -122,8 +116,7 @@ public class HealthTests { RuntimeException ex = new RuntimeException("bang"); Health health = Health.down(ex).build(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); - assertThat(health.getDetails().get("error")) - .isEqualTo("java.lang.RuntimeException: bang"); + assertThat(health.getDetails().get("error")).isEqualTo("java.lang.RuntimeException: bang"); } @Test 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 e09a70b4fc6..399a5803014 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/influx/InfluxDbHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/influx/InfluxDbHealthIndicatorTests.java index 205b1eb7671..1fee33d6b89 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 927c840b33a..429a4082205 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 069d23f230d..582b81638b6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 e3f85323551..54247335237 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 7fea6e05d37..1446a1a499e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 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 d131d49e83b..54b4c92cfad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 DataSourceHealthIndicatorTests { @Before 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()); } @@ -73,8 +72,7 @@ public class DataSourceHealthIndicatorTests { @Test public void customQuery() { this.indicator.setDataSource(this.dataSource); - 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.setQuery("SELECT COUNT(*) from FOO"); Health health = this.indicator.health(); System.err.println(health); @@ -96,8 +94,7 @@ public class DataSourceHealthIndicatorTests { public void connectionClosed() 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 bfae6e33174..8f63d6975c1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 51be62d3082..2382452a4be 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 b713ca21f22..3d74d5fcdaa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +43,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) -> assertThat( - context.getBean(LiquibaseEndpoint.class).liquibaseBeans() - .getContexts().get(context.getId()).getLiquibaseBeans()) - .hasSize(1)); + .run((context) -> assertThat(context.getBean(LiquibaseEndpoint.class).liquibaseBeans().getContexts() + .get(context.getId()).getLiquibaseBeans()).hasSize(1)); } @Test @@ -61,10 +59,8 @@ public class LiquibaseEndpointTests { this.contextRunner.withUserConfiguration(Config.class) .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA", "spring.datasource.schema=classpath:/db/create-custom-schema.sql") - .run((context) -> assertThat( - context.getBean(LiquibaseEndpoint.class).liquibaseBeans() - .getContexts().get(context.getId()).getLiquibaseBeans()) - .hasSize(1)); + .run((context) -> assertThat(context.getBean(LiquibaseEndpoint.class).liquibaseBeans().getContexts() + .get(context.getId()).getLiquibaseBeans()).hasSize(1)); } @Test 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 d9dfe94b77b..d5346493ebb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,18 +72,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 443bfd3b936..5cb6954af5e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +65,9 @@ public class LogFileWebEndpointWebIntegrationTests { @Test public void getRequestProducesResponseWithLogFile() { - TestPropertyValues.of("logging.file:" + this.logFile.getAbsolutePath()) - .applyTo(context); - client.get().uri("/actuator/logfile").exchange().expectStatus().isOk() - .expectBody(String.class).isEqualTo("--TEST--"); + TestPropertyValues.of("logging.file:" + this.logFile.getAbsolutePath()).applyTo(context); + client.get().uri("/actuator/logfile").exchange().expectStatus().isOk().expectBody(String.class) + .isEqualTo("--TEST--"); } @Configuration 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 68d5514f14c..74473aac557 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 0f43928d3a9..077fce4a91f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 220c030db83..4d226b1a474 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 MailHealthIndicatorTests { @Before 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 d59abc41c31..82a304936f5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 2a41079dcfc..882abda3ff2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 28cd052bab3..893006522b5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 0ed1ea8ab45..11f63dd257b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MetricsEndpointTests { @Rule public ExpectedException thrown = ExpectedException.none(); - 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); @@ -63,8 +62,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 @@ -85,8 +83,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); @@ -108,8 +105,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); @@ -126,8 +122,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(); } @@ -135,10 +130,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"); } @@ -174,8 +167,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(); } @@ -195,24 +187,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 f619cdf6ceb..c7088927b86 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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; @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 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 dc0205cd06f..0a5e89c7604 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 044193be6a0..aa4973a7d5e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 2e4fc437572..b08af4b5d57 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 71ba2ac3a5c..3428bfecd5e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 2ae0a0fcf5c..338f19b8c7f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 473f9331afa..2d048f12aaa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/PrometheusScrapeEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java index a445b596e8d..9af4e015f2e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 b44ad314eb7..f9817ebef89 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 05eda2e0596..5b5630d91ec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,13 @@ 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( - StreamSupport.stream(m.getId().getTags().spliterator(), false) - .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(StreamSupport.stream(m.getId().getTags().spliterator(), false).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 +90,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 +99,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/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 83bca94ed80..c2e1fd08135 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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, true); + this.webFilter = new MetricsWebFilter(this.registry, new DefaultWebFluxTagsProvider(), REQUEST_METRICS_NAME, + true); } @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"); @@ -67,12 +64,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(); @@ -87,13 +80,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()); @@ -101,12 +92,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"); @@ -114,16 +103,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 148c1aa452f..f9c9fa918ca 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 @@ -50,8 +50,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 22bfca4ad5a..418f7de4ff9 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 @@ -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 63e3987a646..e8028926672 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 WebMvcMetricsFilterAutoTimedTests { @Before 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()); - 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); } @Configuration @@ -93,10 +91,8 @@ public class WebMvcMetricsFilterAutoTimedTests { } @Bean - public WebMvcMetricsFilter webMetricsFilter(WebApplicationContext context, - MeterRegistry registry) { - return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), - "http.server.requests", true); + public WebMvcMetricsFilter webMetricsFilter(WebApplicationContext context, MeterRegistry registry) { + return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), "http.server.requests", 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 e3d086c8474..a569b8ddeec 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 @@ -129,74 +129,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 @@ -206,8 +197,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"); } @@ -216,26 +206,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 @@ -245,9 +233,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 @@ -268,23 +255,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); } @@ -334,16 +319,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; } } @@ -369,10 +353,8 @@ public class WebMvcMetricsFilterTests { } @Bean - WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, - WebApplicationContext ctx) { - return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), - "http.server.requests", true); + WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, WebApplicationContext ctx) { + return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), "http.server.requests", true); } } @@ -396,8 +378,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(); @@ -414,8 +395,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 { @@ -450,8 +430,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") { }; } @@ -465,8 +444,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; } @@ -519,9 +497,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 cde7d3d3575..37b39364e67 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 @@ -72,25 +72,21 @@ public class WebMvcMetricsIntegrationTests { @Before 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 @@ -108,10 +104,8 @@ public class WebMvcMetricsIntegrationTests { } @Bean - public WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, - WebApplicationContext ctx) { - return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), - "http.server.requests", true); + public WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry, WebApplicationContext ctx) { + return new WebMvcMetricsFilter(registry, new DefaultWebMvcTagsProvider(), "http.server.requests", true); } @Configuration @@ -152,8 +146,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 84927860061..d3557af184c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 be6646f7e6c..274283a09ac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 93e717a8c76..09db436ddf3 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 @@ -60,8 +60,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); @@ -77,11 +76,9 @@ public class Neo4jHealthIndicatorTests { @Test public void neo4jDown() { - CypherException cypherException = new CypherException( - "Neo.ClientError.Statement.SyntaxError", + CypherException cypherException = new CypherException("Neo.ClientError.Statement.SyntaxError", "Unable to execute invalid Cypher"); - given(this.session.query(Neo4jHealthIndicator.CYPHER, Collections.emptyMap())) - .willThrow(cypherException); + 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 b25dd768703..f22e28aab37 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a69c162e58a..521b555100c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 RedisReactiveHealthIndicatorTests { ReactiveRedisConnection redisConnection = mock(ReactiveRedisConnection.class); 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); @@ -65,38 +64,30 @@ 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); - 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).close(); } @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 35605df344b..2228aeb4dca 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 @@ -55,11 +55,9 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedDelay()).isEmpty(); assertThat(tasks.getFixedRate()).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"); }); } @@ -69,11 +67,9 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getFixedRate()).isEmpty(); assertThat(tasks.getFixedDelay()).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()); }); } @@ -83,8 +79,7 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedRate()).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()) @@ -98,12 +93,10 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedRate()).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()); }); } @@ -113,8 +106,7 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedDelay()).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()) @@ -128,18 +120,16 @@ public class ScheduledTasksEndpointTests { assertThat(tasks.getCron()).isEmpty(); assertThat(tasks.getFixedDelay()).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()); }); } 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 @@ -147,8 +137,7 @@ public class ScheduledTasksEndpointTests { static class BaseConfiguration { @Bean - public ScheduledTasksEndpoint endpoint( - Collection scheduledTaskHolders) { + public ScheduledTasksEndpoint endpoint(Collection scheduledTaskHolders) { return new ScheduledTasksEndpoint(scheduledTaskHolders); } @@ -208,8 +197,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 1277b38931f..af3a71610d0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 AuthenticationAuditListenerTests { private final AuthenticationAuditListener listener = new AuthenticationAuditListener(); - private final ApplicationEventPublisher publisher = mock( - ApplicationEventPublisher.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @Before 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,43 +70,33 @@ 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 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 0020f9e551b..4cc96183dd5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 AuthorizationAuditListenerTests { private final AuthorizationAuditListener listener = new AuthorizationAuditListener(); - private final ApplicationEventPublisher publisher = mock( - ApplicationEventPublisher.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); @Before 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 32a8d8f5402..c60e2cbb74a 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,27 +41,21 @@ 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); @Test public void sessionsForUsername() { - given(this.repository.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "user")) - .willReturn(Collections.singletonMap(session.getId(), session)); - List result = this.endpoint.sessionsForUsername("user") - .getSessions(); + given(this.repository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, + "user")).willReturn(Collections.singletonMap(session.getId(), session)); + 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()); } @@ -73,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 708165bd6c0..89d128e2831 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,38 +52,30 @@ 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.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "user")) - .willReturn(Collections.emptyMap()); - client.get() - .uri((builder) -> builder.path("/actuator/sessions") - .queryParam("username", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("sessions") - .isEmpty(); + given(repository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, + "user")).willReturn(Collections.emptyMap()); + 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.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "user")) - .willReturn(Collections.singletonMap(session.getId(), session)); - client.get() - .uri((builder) -> builder.path("/actuator/sessions") - .queryParam("username", "user").build()) + given(repository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, + "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 9ff28b225b0..253e70065f0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/system/DiskSpaceHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java index 69e45a6cc25..23cfeb270d7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DiskSpaceHealthIndicatorTests { MockitoAnnotations.initMocks(this); given(this.fileMock.exists()).willReturn(true); given(this.fileMock.canRead()).willReturn(true); - this.healthIndicator = new DiskSpaceHealthIndicator(this.fileMock, - THRESHOLD_BYTES); + this.healthIndicator = new DiskSpaceHealthIndicator(this.fileMock, THRESHOLD_BYTES); } @Test 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 533f287a35a..2e69557ab52 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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(), () -> createPrincipal(), null); + new HttpExchangeTracer(EnumSet.noneOf(Include.class)).sendingResponse(trace, createResponse(), + () -> createPrincipal(), null); assertThat(trace.getPrincipal()).isNull(); } @Test public void principalCanBeIncluded() { HttpTrace trace = new HttpTrace(createRequest()); - new HttpExchangeTracer(EnumSet.of(Include.PRINCIPAL)).sendingResponse(trace, - createResponse(), () -> createPrincipal(), null); + new HttpExchangeTracer(EnumSet.of(Include.PRINCIPAL)).sendingResponse(trace, createResponse(), + () -> 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 9ffdf4df1cc..351312d783d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 e0ae7535363..c1cfffd20ff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 +51,14 @@ 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() throws ServletException, IOException { - this.filter.filter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), + this.filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), new WebFilterChain() { @Override @@ -74,17 +71,13 @@ public class HttpTraceWebFilterTests { } @Test - public void filterCapturesSessionIdWhenSessionIsUsed() - throws ServletException, IOException { - this.filter.filter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), + public void filterCapturesSessionIdWhenSessionIsUsed() throws ServletException, IOException { + this.filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), new WebFilterChain() { @Override public Mono filter(ServerWebExchange exchange) { - exchange.getSession().block(Duration.ofSeconds(30)) - .getAttributes().put("a", "alpha"); + exchange.getSession().block(Duration.ofSeconds(30)).getAttributes().put("a", "alpha"); return Mono.empty(); } @@ -96,11 +89,8 @@ public class HttpTraceWebFilterTests { } @Test - public void filterDoesNotCaptureIdOfUnusedSession() - throws ServletException, IOException { - this.filter.filter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), + public void filterDoesNotCaptureIdOfUnusedSession() throws ServletException, IOException { + this.filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), new WebFilterChain() { @Override @@ -119,8 +109,8 @@ public class HttpTraceWebFilterTests { public void filterCapturesPrincipal() throws ServletException, IOException { Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); - this.filter.filter(new ServerWebExchangeDecorator(MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com"))) { + this.filter.filter(new ServerWebExchangeDecorator( + MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com"))) { @Override public Mono getPrincipal() { @@ -131,26 +121,22 @@ public class HttpTraceWebFilterTests { @Override public Mono filter(ServerWebExchange 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"); } @Test - public void statusIsAssumedToBe500WhenChainFails() - throws ServletException, IOException { + public void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { try { - this.filter.filter( - MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), + this.filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), new WebFilterChain() { @Override @@ -163,8 +149,7 @@ public class HttpTraceWebFilterTests { } catch (Exception 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); } } 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 ae4d45be991..985b1efc47d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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,25 +90,22 @@ 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 { + public void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { try { - this.filter.doFilter(new MockHttpServletRequest(), - new MockHttpServletResponse(), new MockFilterChain(new HttpServlet() { + this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), + new MockFilterChain(new HttpServlet() { @Override - protected void service(HttpServletRequest req, - HttpServletResponse resp) + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { throw new IOException(); } @@ -122,8 +115,7 @@ public class HttpTraceFilterTests { } catch (IOException 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); } } @@ -131,8 +123,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 d98ad266ee7..a43b6dd2a6d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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-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 974bb25d758..292c3a4ea40 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,7 +53,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 52a3f216b53..42d1e7fef75 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. @@ -66,14 +66,12 @@ 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 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"; @@ -93,8 +91,7 @@ public class AutoConfigurationImportSelector AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); 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); @@ -111,9 +108,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; } @@ -127,12 +122,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; } @@ -153,13 +145,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; } @@ -172,12 +162,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); } } @@ -196,9 +184,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)); } /** @@ -208,8 +196,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"))); @@ -220,16 +207,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]; @@ -256,15 +241,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) { @@ -276,12 +259,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); @@ -290,15 +271,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); @@ -354,8 +333,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 ClassLoader beanClassLoader; @@ -381,8 +360,7 @@ public class AutoConfigurationImportSelector } @Override - public void process(AnnotationMetadata annotationMetadata, - DeferredImportSelector deferredImportSelector) { + public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) { String[] imports = deferredImportSelector.selectImports(annotationMetadata); for (String importClassName : imports) { this.entries.put(importClassName, annotationMetadata); @@ -392,8 +370,7 @@ public class AutoConfigurationImportSelector @Override public Iterable selectImports() { return sortAutoConfigurations().stream() - .map((importClassName) -> new Entry(this.entries.get(importClassName), - importClassName)) + .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)) .collect(Collectors.toList()); } @@ -404,14 +381,13 @@ public class AutoConfigurationImportSelector } AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader .loadMetadata(this.beanClassLoader); - return new AutoConfigurationSorter(getMetadataReaderFactory(), - autoConfigurationMetadata).getInPriorityOrder(autoConfigurations); + return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata) + .getInPriorityOrder(autoConfigurations); } private MetadataReaderFactory getMetadataReaderFactory() { try { - return this.beanFactory.getBean( - SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, + return this.beanFactory.getBean(SharedMetadataReaderFactoryContextInitializer.BEAN_NAME, MetadataReaderFactory.class); } catch (NoSuchBeanDefinitionException ex) { 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 4289f13e720..c33da4672c3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -68,8 +68,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<>(); @@ -81,9 +80,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); } @@ -104,10 +102,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() { @@ -115,12 +111,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); @@ -166,8 +161,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; @@ -188,33 +182,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() { @@ -223,8 +212,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(); } @@ -237,13 +226,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 ebbe65d79dd..9d9a871672f 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.toCollection(ArrayList::new)); + List names = classes.stream().map(Class::getName).collect(Collectors.toCollection(ArrayList::new)); 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 166a8b992c0..960f876118d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 @@ 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 { - private static final AtomicBoolean preinitializationStarted = new AtomicBoolean( - false); + private static final AtomicBoolean preinitializationStarted = new AtomicBoolean(false); private static final CountDownLatch preinitializationComplete = new CountDownLatch(1); @Override public void onApplicationEvent(SpringApplicationEvent event) { - if (event instanceof ApplicationStartingEvent - && preinitializationStarted.compareAndSet(false, true)) { + if (event instanceof ApplicationStartingEvent && 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 a56666d1950..9cd5a795093 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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; @@ -70,26 +69,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); } @@ -97,20 +93,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()); @@ -119,8 +111,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)); } @@ -129,21 +120,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 ec69869740c..9ced8e8ce1b 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SharedMetadataReaderFactoryContextInitializer @Override public void initialize(ConfigurableApplicationContext applicationContext) { - applicationContext.addBeanFactoryPostProcessor( - new CachingMetadataReaderFactoryPostProcessor()); + applicationContext.addBeanFactoryPostProcessor(new CachingMetadataReaderFactoryPostProcessor()); } /** @@ -73,30 +72,25 @@ class SharedMetadataReaderFactoryContextInitializer } @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) { - RootBeanDefinition definition = new RootBeanDefinition( - SharedMetadataReaderFactoryBean.class); + RootBeanDefinition definition = new RootBeanDefinition(SharedMetadataReaderFactoryBean.class); 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) { } @@ -108,20 +102,18 @@ class SharedMetadataReaderFactoryContextInitializer * {@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 ceadaedc7e1..6b24bdb729a 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 @@ -49,10 +49,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) }) 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 013cbb84ffd..c656d6c062c 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 @@ -43,8 +43,8 @@ import org.springframework.jmx.export.MBeanExporter; */ @Configuration @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 { /** @@ -62,18 +62,16 @@ public class SpringApplicationAdminJmxAutoConfiguration { private final Environment environment; - public SpringApplicationAdminJmxAutoConfiguration( - ObjectProvider> mbeanExporters, Environment environment) { + public SpringApplicationAdminJmxAutoConfiguration(ObjectProvider> mbeanExporters, + Environment environment) { this.mbeanExporters = mbeanExporters.getIfAvailable(); this.environment = environment; } @Bean @ConditionalOnMissingBean - public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar() - throws MalformedObjectNameException { - String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY, - DEFAULT_JMX_NAME); + public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar() throws MalformedObjectNameException { + String jmxName = this.environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (this.mbeanExporters != null) { // Make sure to not register that MBean twice for (MBeanExporter mbeanExporter : this.mbeanExporters) { mbeanExporter.addExcludedBean(jmxName); 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 fc0500e4a89..6132d85cf4b 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. @@ -104,14 +104,13 @@ public abstract class AbstractRabbitListenerContainerFactoryConfigurer builder = (retryConfig.isStateless() - ? RetryInterceptorBuilder.stateless() + RetryInterceptorBuilder builder = (retryConfig.isStateless() ? RetryInterceptorBuilder.stateless() : RetryInterceptorBuilder.stateful()); builder.maxAttempts(retryConfig.getMaxAttempts()); - builder.backOffOptions(retryConfig.getInitialInterval().toMillis(), - retryConfig.getMultiplier(), retryConfig.getMaxInterval().toMillis()); - MessageRecoverer recoverer = (this.messageRecoverer != null) - ? this.messageRecoverer : new RejectAndDontRequeueRecoverer(); + builder.backOffOptions(retryConfig.getInitialInterval().toMillis(), retryConfig.getMultiplier(), + retryConfig.getMaxInterval().toMillis()); + 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 4c0661dd922..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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 8ce6dbc8649..b4a8bd8a8d8 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 @@ -48,8 +48,7 @@ class RabbitAnnotationDrivenConfiguration { private final RabbitProperties properties; RabbitAnnotationDrivenConfiguration(ObjectProvider messageConverter, - ObjectProvider messageRecoverer, - RabbitProperties properties) { + ObjectProvider messageRecoverer, RabbitProperties properties) { this.messageConverter = messageConverter; this.messageRecoverer = messageRecoverer; this.properties = properties; @@ -67,11 +66,10 @@ class RabbitAnnotationDrivenConfiguration { @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; @@ -89,11 +87,9 @@ class RabbitAnnotationDrivenConfiguration { @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; @@ -101,8 +97,7 @@ class RabbitAnnotationDrivenConfiguration { @Configuration @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 ab20550b04a..bd587fcbacf 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 @@ -96,14 +96,11 @@ public class RabbitAutoConfiguration { // Only available in rabbitmq-java-client 5.4.0 + private static final boolean CAN_ENABLE_HOSTNAME_VERIFICATION = ReflectionUtils - .findMethod(com.rabbitmq.client.ConnectionFactory.class, - "enableHostnameVerification") != null; + .findMethod(com.rabbitmq.client.ConnectionFactory.class, "enableHostnameVerification") != null; @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()); @@ -114,30 +111,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); @@ -148,16 +139,15 @@ 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).when(Objects::nonNull) - .to(factory::setEnableHostnameVerification); + map.from(ssl::isValidateServerCertificate) + .to((validate) -> factory.setSkipServerCertificateValidation(!validate)); + map.from(ssl::getVerifyHostname).when(Objects::nonNull).to(factory::setEnableHostnameVerification); if (ssl.getVerifyHostname() == null && CAN_ENABLE_HOSTNAME_VERIFICATION) { factory.setEnableHostnameVerification(true); } } - 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; } @@ -172,8 +162,7 @@ public class RabbitAutoConfiguration { private final RabbitProperties properties; - public RabbitTemplateConfiguration( - ObjectProvider messageConverter, + public RabbitTemplateConfiguration(ObjectProvider messageConverter, RabbitProperties properties) { this.messageConverter = messageConverter; this.properties = properties; @@ -196,8 +185,7 @@ public class RabbitAutoConfiguration { } map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) .to(template::setReceiveTimeout); - map.from(properties::getReplyTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReplyTimeout); + map.from(properties::getReplyTimeout).whenNonNull().as(Duration::toMillis).to(template::setReplyTimeout); map.from(properties::getExchange).to(template::setExchange); map.from(properties::getRoutingKey).to(template::setRoutingKey); return template; @@ -218,16 +206,14 @@ public class RabbitAutoConfiguration { 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); return template; } @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); @@ -243,8 +229,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/SimpleRabbitListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/SimpleRabbitListenerContainerFactoryConfigurer.java index 870c4b5a204..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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 5e7ef09c51a..e5bda02d8e9 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 @@ -40,24 +40,22 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; * @see EnableAspectJAutoProxy */ @Configuration -@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 @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 @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 977ffdafceb..3d8433af60c 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 a27ca8448df..c83a9bb498c 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 @@ -79,21 +79,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); @@ -110,8 +105,7 @@ public class BatchAutoConfiguration { @Bean @ConditionalOnMissingBean(JobOperator.class) public SimpleJobOperator jobOperator(JobExplorer jobExplorer, JobLauncher jobLauncher, - ListableJobLocator jobRegistry, JobRepository jobRepository) - throws Exception { + 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 d581f4c9794..3a3e1348308 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 85635151cf1..7eef157b036 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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(); @@ -103,8 +101,7 @@ public class JobLauncherCommandLineRunner * parameters when running a job (which is not possible with the job explorer). */ @Deprecated - public JobLauncherCommandLineRunner(JobLauncher jobLauncher, - JobExplorer jobExplorer) { + public JobLauncherCommandLineRunner(JobLauncher jobLauncher, JobExplorer jobExplorer) { this.jobLauncher = jobLauncher; this.jobExplorer = jobExplorer; this.jobRepository = null; @@ -117,8 +114,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"); @@ -166,15 +162,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(","); @@ -187,8 +181,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) { @@ -207,9 +200,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) { @@ -218,25 +210,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; @@ -248,8 +236,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 b6ae88b3015..a6f69bd6c20 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,16 +72,15 @@ public class CacheAutoConfiguration { } @Bean - public CacheManagerValidator cacheAutoConfigurationValidator( - CacheProperties cacheProperties, ObjectProvider cacheManager) { + public CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties, + ObjectProvider cacheManager) { return new CacheManagerValidator(cacheProperties, cacheManager); } @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class CacheManagerJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class CacheManagerJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public CacheManagerJpaDependencyConfiguration() { super("cacheManager"); @@ -99,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; } @@ -108,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 67ad530e772..6b53e546acb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ class CaffeineCacheConfiguration { private final CacheLoader cacheLoader; - CaffeineCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, - ObjectProvider> caffeine, - ObjectProvider caffeineSpec, + CaffeineCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, + ObjectProvider> caffeine, ObjectProvider caffeineSpec, ObjectProvider> cacheLoader) { this.cacheProperties = cacheProperties; this.customizers = customizers; 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 e2e15cc3bfe..751e2af947f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ public class CouchbaseCacheConfiguration { private final Bucket bucket; - public CouchbaseCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, Bucket bucket) { + public CouchbaseCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, + Bucket bucket) { this.cacheProperties = cacheProperties; this.customizers = customizers; this.bucket = bucket; @@ -65,8 +65,8 @@ public class CouchbaseCacheConfiguration { List cacheNames = this.cacheProperties.getCacheNames(); CacheBuilder builder = CacheBuilder.newInstance(this.bucket); Couchbase couchbase = this.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 this.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 d4f3cc3c043..7f682a21b11 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.core.io.Resource; @Configuration @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 { private final CacheProperties cacheProperties; private final CacheManagerCustomizers customizers; - EhCacheCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers) { + EhCacheCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers) { this.cacheProperties = cacheProperties; this.customizers = customizers; } @@ -63,8 +61,7 @@ class EhCacheCacheConfiguration { @Bean @ConditionalOnMissingBean public CacheManager ehCacheCacheManager() { - Resource location = this.cacheProperties - .resolveConfigLocation(this.cacheProperties.getEhcache().getConfig()); + Resource location = this.cacheProperties.resolveConfigLocation(this.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/HazelcastCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/HazelcastCacheConfiguration.java index 740c56131d7..837d10bbcfb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ class HazelcastCacheConfiguration { } @Bean - public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance) - throws IOException { - HazelcastCacheManager cacheManager = new HazelcastCacheManager( - existingHazelcastInstance); + public HazelcastCacheManager cacheManager(HazelcastInstance existingHazelcastInstance) throws IOException { + HazelcastCacheManager cacheManager = new HazelcastCacheManager(existingHazelcastInstance); return this.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 0c6b40afe75..9ea63c1d472 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 HazelcastJCacheCustomizationConfiguration { return new HazelcastPropertiesCustomizer(hazelcastInstance.getIfUnique()); } - private static class HazelcastPropertiesCustomizer - implements JCachePropertiesCustomizer { + private static class HazelcastPropertiesCustomizer implements JCachePropertiesCustomizer { private final HazelcastInstance hazelcastInstance; @@ -54,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); @@ -71,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 bb5037b54a4..2ed87be9bcc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 InfinispanCacheConfiguration { private final ConfigurationBuilder defaultConfigurationBuilder; - public InfinispanCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, + public InfinispanCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, ObjectProvider defaultConfigurationBuilder) { this.cacheProperties = cacheProperties; this.customizers = customizers; @@ -64,10 +63,8 @@ public class InfinispanCacheConfiguration { } @Bean - public SpringEmbeddedCacheManager cacheManager( - EmbeddedCacheManager embeddedCacheManager) { - SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager( - embeddedCacheManager); + public SpringEmbeddedCacheManager cacheManager(EmbeddedCacheManager embeddedCacheManager) { + SpringEmbeddedCacheManager cacheManager = new SpringEmbeddedCacheManager(embeddedCacheManager); return this.customizers.customize(cacheManager); } @@ -77,8 +74,8 @@ public class InfinispanCacheConfiguration { EmbeddedCacheManager cacheManager = createEmbeddedCacheManager(); List cacheNames = this.cacheProperties.getCacheNames(); if (!CollectionUtils.isEmpty(cacheNames)) { - cacheNames.forEach((cacheName) -> cacheManager.defineConfiguration(cacheName, - getDefaultCacheConfiguration())); + cacheNames.forEach( + (cacheName) -> cacheManager.defineConfiguration(cacheName, getDefaultCacheConfiguration())); } return cacheManager; } 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 0d9509abcc1..eef637d352f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.StringUtils; @Configuration @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 { @@ -76,8 +75,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { private ClassLoader beanClassLoader; - JCacheCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizers, + JCacheCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, ObjectProvider> defaultCacheConfiguration, ObjectProvider> cacheManagerCustomizers, ObjectProvider> cachePropertiesCustomizers) { @@ -114,14 +112,12 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { } private CacheManager createCacheManager() throws IOException { - CachingProvider cachingProvider = getCachingProvider( - this.cacheProperties.getJcache().getProvider()); + CachingProvider cachingProvider = getCachingProvider(this.cacheProperties.getJcache().getProvider()); Properties properties = createCacheManagerProperties(); Resource configLocation = this.cacheProperties .resolveConfigLocation(this.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); } @@ -192,28 +188,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 2273478ae99..ce47e797e09 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class RedisCacheConfiguration { private final org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration; - RedisCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizerInvoker, + RedisCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker, ObjectProvider redisCacheConfiguration) { this.cacheProperties = cacheProperties; this.customizerInvoker = customizerInvoker; @@ -70,8 +69,7 @@ class RedisCacheConfiguration { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { - RedisCacheManagerBuilder builder = RedisCacheManager - .builder(redisConnectionFactory) + RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(determineConfiguration(resourceLoader.getClassLoader())); List cacheNames = this.cacheProperties.getCacheNames(); if (!cacheNames.isEmpty()) { @@ -88,8 +86,8 @@ class RedisCacheConfiguration { Redis redisProperties = this.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/cache/SimpleCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java index af9c0174c9a..11943c6406d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/SimpleCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SimpleCacheConfiguration { private final CacheManagerCustomizers customizerInvoker; - SimpleCacheConfiguration(CacheProperties cacheProperties, - CacheManagerCustomizers customizerInvoker) { + SimpleCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizerInvoker) { this.cacheProperties = cacheProperties; this.customizerInvoker = customizerInvoker; } 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 3b5836308a9..b350da5fc1a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +64,21 @@ public class CassandraAutoConfiguration { public Cluster cassandraCluster() { PropertyMapper map = PropertyMapper.get(); CassandraProperties properties = this.properties; - 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); - map.from(properties::getLoadBalancingPolicy).whenNonNull() - .as(BeanUtils::instantiateClass).to(builder::withLoadBalancingPolicy); + map.from(properties::getLoadBalancingPolicy).whenNonNull().as(BeanUtils::instantiateClass) + .to(builder::withLoadBalancingPolicy); map.from(this::getQueryOptions).to(builder::withQueryOptions); - map.from(properties::getReconnectionPolicy).whenNonNull() - .as(BeanUtils::instantiateClass).to(builder::withReconnectionPolicy); - map.from(properties::getRetryPolicy).whenNonNull().as(BeanUtils::instantiateClass) - .to(builder::withRetryPolicy); + map.from(properties::getReconnectionPolicy).whenNonNull().as(BeanUtils::instantiateClass) + .to(builder::withReconnectionPolicy); + map.from(properties::getRetryPolicy).whenNonNull().as(BeanUtils::instantiateClass).to(builder::withRetryPolicy); map.from(this::getSocketOptions).to(builder::withSocketOptions); map.from(properties::isSsl).whenTrue().toCall(builder::withSSL); map.from(this::getPoolingOptions).to(builder::withPoolingOptions); - map.from(properties::getContactPoints) - .as((list) -> StringUtils.toStringArray(list)) + map.from(properties::getContactPoints).as((list) -> StringUtils.toStringArray(list)) .to(builder::addContactPoints); customize(builder); return builder.build(); @@ -99,10 +96,8 @@ public class CassandraAutoConfiguration { PropertyMapper map = PropertyMapper.get(); QueryOptions options = new QueryOptions(); CassandraProperties properties = this.properties; - 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; } @@ -110,8 +105,8 @@ public class CassandraAutoConfiguration { private SocketOptions getSocketOptions() { PropertyMapper map = PropertyMapper.get(); SocketOptions options = new SocketOptions(); - map.from(this.properties::getConnectTimeout).whenNonNull() - .asInt(Duration::toMillis).to(options::setConnectTimeoutMillis); + map.from(this.properties::getConnectTimeout).whenNonNull().asInt(Duration::toMillis) + .to(options::setConnectTimeoutMillis); map.from(this.properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) .to(options::setReadTimeoutMillis); return options; @@ -123,10 +118,9 @@ public class CassandraAutoConfiguration { PoolingOptions options = new PoolingOptions(); map.from(properties::getIdleTimeout).whenNonNull().asInt(Duration::getSeconds) .to(options::setIdleTimeoutSeconds); - map.from(properties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis) - .to(options::setPoolTimeoutMillis); - map.from(properties::getHeartbeatInterval).whenNonNull() - .asInt(Duration::getSeconds).to(options::setHeartbeatIntervalSeconds); + map.from(properties::getPoolTimeout).whenNonNull().asInt(Duration::toMillis).to(options::setPoolTimeoutMillis); + map.from(properties::getHeartbeatInterval).whenNonNull().asInt(Duration::getSeconds) + .to(options::setHeartbeatIntervalSeconds); map.from(properties::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 0566e417c39..49320801f6d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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. @@ -192,8 +191,7 @@ public class CassandraProperties { return this.loadBalancingPolicy; } - public void setLoadBalancingPolicy( - Class loadBalancingPolicy) { + public void setLoadBalancingPolicy(Class loadBalancingPolicy) { this.loadBalancingPolicy = loadBalancingPolicy; } @@ -225,8 +223,7 @@ public class CassandraProperties { return this.reconnectionPolicy; } - public void setReconnectionPolicy( - Class reconnectionPolicy) { + public void setReconnectionPolicy(Class reconnectionPolicy) { this.reconnectionPolicy = reconnectionPolicy; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java index 16d4fd7c6d6..60175836995 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfiguration.java @@ -50,8 +50,7 @@ import org.springframework.core.Ordered; @AutoConfigureOrder(CloudAutoConfiguration.ORDER) @ConditionalOnClass(CloudScanConfiguration.class) @ConditionalOnMissingBean(Cloud.class) -@ConditionalOnProperty(prefix = "spring.cloud", name = "enabled", havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.cloud", name = "enabled", havingValue = "true", matchIfMissing = true) @Import(CloudScanConfiguration.class) public class CloudAutoConfiguration { 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 c637362d7ad..77c4f792f9f 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,16 +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, 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 { @@ -112,14 +109,12 @@ public abstract class AbstractNestedCondition extends SpringBootCondition MemberConditions(ConditionContext context, 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); } - private Map> getMemberConditions( - String[] members) { + private Map> getMemberConditions(String[] members) { MultiValueMap memberConditions = new LinkedMultiValueMap<>(); for (String member : members) { AnnotationMetadata metadata = getMetadata(member); @@ -135,8 +130,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); @@ -145,23 +139,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); } @@ -175,8 +167,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()); @@ -185,24 +176,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<>(); @@ -210,11 +196,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 d2c4d47e81c..b97aaf0206c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,7 @@ 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 bd = new RootBeanDefinition(BeanTypeRegistry.class); bd.getConstructorArgumentValues().addIndexedArgumentValue(0, beanFactory); @@ -112,10 +111,8 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { Set getNamesForType(Class type) { updateTypesIfNecessary(); return this.beanTypes.entrySet().stream() - .filter((entry) -> entry.getValue() != null - && type.isAssignableFrom(entry.getValue())) - .map(Map.Entry::getKey) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .filter((entry) -> entry.getValue() != null && type.isAssignableFrom(entry.getValue())) + .map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new)); } /** @@ -130,10 +127,9 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { Set getNamesForAnnotation(Class annotation) { updateTypesIfNecessary(); return this.beanTypes.entrySet().stream() - .filter((entry) -> entry.getValue() != null && AnnotationUtils - .findAnnotation(entry.getValue(), annotation) != null) - .map(Map.Entry::getKey) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .filter((entry) -> entry.getValue() != null + && AnnotationUtils.findAnnotation(entry.getValue(), annotation) != null) + .map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new)); } @Override @@ -184,18 +180,14 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } } - private void addBeanTypeForNonAliasDefinition(String name, - RootBeanDefinition beanDefinition) { + private void addBeanTypeForNonAliasDefinition(String name, RootBeanDefinition beanDefinition) { try { - if (!beanDefinition.isAbstract() - && !requiresEagerInit(beanDefinition.getFactoryBeanName())) { + if (!beanDefinition.isAbstract() && !requiresEagerInit(beanDefinition.getFactoryBeanName())) { String factoryName = BeanFactory.FACTORY_BEAN_PREFIX + name; if (this.beanFactory.isFactoryBean(factoryName)) { - Class factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, - beanDefinition); + Class factoryBeanGeneric = getFactoryBeanGeneric(this.beanFactory, beanDefinition); this.beanTypes.put(name, factoryBeanGeneric); - this.beanTypes.put(factoryName, - this.beanFactory.getType(factoryName)); + this.beanTypes.put(factoryName, this.beanFactory.getType(factoryName)); } else { this.beanTypes.put(name, this.beanFactory.getType(name)); @@ -237,8 +229,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { * @param definition the bean definition * @return the generic type of the {@link FactoryBean} or {@code null} */ - private Class getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, - BeanDefinition definition) { + private Class getFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) { try { return doGetFactoryBeanGeneric(beanFactory, definition); } @@ -247,8 +238,7 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { } } - private Class doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, - BeanDefinition definition) + private Class doGetFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) throws Exception, ClassNotFoundException, LinkageError { if (StringUtils.hasLength(definition.getFactoryBeanName()) && StringUtils.hasLength(definition.getFactoryMethodName())) { @@ -260,32 +250,25 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return null; } - private Class getConfigurationClassFactoryBeanGeneric( - ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) - throws Exception { + private Class getConfigurationClassFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, + BeanDefinition definition) throws Exception { Method method = getFactoryMethod(beanFactory, definition); - Class generic = ResolvableType.forMethodReturnType(method) - .as(FactoryBean.class).resolveGeneric(); - if ((generic == null || generic.equals(Object.class)) - && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { - generic = getTypeFromAttribute( - definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); + Class generic = ResolvableType.forMethodReturnType(method).as(FactoryBean.class).resolveGeneric(); + if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { + generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; } - 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); @@ -306,10 +289,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()); } @@ -322,23 +303,17 @@ final class BeanTypeRegistry implements SmartInitializingSingleton { return Arrays.equals(candidate.getParameterTypes(), current.getParameterTypes()); } - private Class getDirectFactoryBeanGeneric( - ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) + private Class getDirectFactoryBeanGeneric(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition) throws ClassNotFoundException, LinkageError { - Class factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), - beanFactory.getBeanClassLoader()); - Class generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class) - .resolveGeneric(); - if ((generic == null || generic.equals(Object.class)) - && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { - generic = getTypeFromAttribute( - definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); + Class factoryBeanClass = ClassUtils.forName(definition.getBeanClassName(), beanFactory.getBeanClassLoader()); + Class generic = ResolvableType.forClass(factoryBeanClass).as(FactoryBean.class).resolveGeneric(); + if ((generic == null || generic.equals(Object.class)) && definition.hasAttribute(FACTORY_BEAN_OBJECT_TYPE)) { + generic = getTypeFromAttribute(definition.getAttribute(FACTORY_BEAN_OBJECT_TYPE)); } return generic; } - private Class getTypeFromAttribute(Object attribute) - throws ClassNotFoundException, LinkageError { + private Class getTypeFromAttribute(Object attribute) throws ClassNotFoundException, LinkageError { if (attribute instanceof Class) { return (Class) attribute; } 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 4ec207dc66c..f4be55325d2 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. @@ -73,8 +73,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"); @@ -125,8 +124,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); } }); @@ -161,8 +160,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)) { @@ -177,12 +175,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); } } @@ -190,12 +185,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); @@ -269,8 +261,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 bfc7b3e0159..def4148325e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(" " + this.singular); } else if (StringUtils.hasLength(this.plural)) { message.append(" " + this.plural); } if (items != null && !items.isEmpty()) { - message.append( - " " + StringUtils.collectionToDelimitedString(items, ", ")); + message.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/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 609c1106a50..2c573b1855c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,20 +72,17 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } @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())) { @@ -93,50 +90,41 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit 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.namesOfAllMatches); + matchMessage = matchMessage.andCondition(ConditionalOnSingleCandidate.class, spec) + .found("a primary bean from beans").items(Style.QUOTE, matchResult.namesOfAllMatches); } 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); } private String createOnBeanNoMatchReason(MatchResult matchResult) { StringBuilder reason = new StringBuilder(); - appendMessageForNoMatches(reason, matchResult.unmatchedAnnotations, - "annotated with"); + appendMessageForNoMatches(reason, matchResult.unmatchedAnnotations, "annotated with"); appendMessageForNoMatches(reason, matchResult.unmatchedTypes, "of type"); appendMessageForNoMatches(reason, matchResult.unmatchedNames, "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 "); @@ -157,14 +145,13 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit reason.append(" and "); } reason.append("found beans named "); - reason.append(StringUtils - .collectionToDelimitedString(matchResult.matchedNames, ", ")); + reason.append(StringUtils.collectionToDelimitedString(matchResult.matchedNames, ", ")); } 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) { @@ -184,17 +171,16 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit 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; - List beansIgnoredByType = getNamesOfBeansIgnoredByType( - beans.getIgnoredTypes(), beanFactory, context, considerHierarchy); + List beansIgnoredByType = getNamesOfBeansIgnoredByType(beans.getIgnoredTypes(), beanFactory, context, + considerHierarchy); for (String type : beans.getTypes()) { - Collection typeMatches = getBeanNamesForType(beanFactory, type, - context.getClassLoader(), considerHierarchy); + Collection typeMatches = getBeanNamesForType(beanFactory, type, context.getClassLoader(), + considerHierarchy); typeMatches.removeAll(beansIgnoredByType); if (typeMatches.isEmpty()) { matchResult.recordUnmatchedType(type); @@ -204,9 +190,8 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } } 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); @@ -216,8 +201,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } } 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 { @@ -227,32 +211,29 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit return matchResult; } - private List getNamesOfBeansIgnoredByType(List ignoredTypes, - ListableBeanFactory beanFactory, ConditionContext context, - boolean considerHierarchy) { + private List getNamesOfBeansIgnoredByType(List ignoredTypes, ListableBeanFactory beanFactory, + ConditionContext context, boolean considerHierarchy) { List beanNames = new ArrayList<>(); for (String ignoredType : ignoredTypes) { - beanNames.addAll(getBeanNamesForType(beanFactory, ignoredType, - context.getClassLoader(), considerHierarchy)); + beanNames + .addAll(getBeanNamesForType(beanFactory, ignoredType, 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, ClassLoader classLoader, boolean considerHierarchy) - throws LinkageError { + private Collection getBeanNamesForType(ListableBeanFactory beanFactory, String type, + ClassLoader classLoader, boolean considerHierarchy) throws LinkageError { try { Set result = new LinkedHashSet<>(); - collectBeanNamesForType(result, beanFactory, - ClassUtils.forName(type, classLoader), considerHierarchy); + collectBeanNamesForType(result, beanFactory, ClassUtils.forName(type, classLoader), considerHierarchy); return result; } catch (ClassNotFoundException | NoClassDefFoundError ex) { @@ -260,29 +241,25 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } } - private void collectBeanNamesForType(Set result, - ListableBeanFactory beanFactory, Class type, boolean considerHierarchy) { + private void collectBeanNamesForType(Set result, ListableBeanFactory beanFactory, Class type, + boolean considerHierarchy) { result.addAll(BeanTypeRegistry.get(beanFactory).getNamesForType(type)); if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory) { - BeanFactory parent = ((HierarchicalBeanFactory) beanFactory) - .getParentBeanFactory(); + BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory(); if (parent instanceof ListableBeanFactory) { - collectBeanNamesForType(result, (ListableBeanFactory) parent, type, - considerHierarchy); + collectBeanNamesForType(result, (ListableBeanFactory) parent, type, considerHierarchy); } } } - 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 @@ -290,35 +267,27 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit return StringUtils.toStringArray(names); } - private void collectBeanNamesForAnnotation(Set names, - ListableBeanFactory beanFactory, Class annotationType, - boolean considerHierarchy) { - names.addAll( - BeanTypeRegistry.get(beanFactory).getNamesForAnnotation(annotationType)); + private void collectBeanNamesForAnnotation(Set names, ListableBeanFactory beanFactory, + Class annotationType, boolean considerHierarchy) { + names.addAll(BeanTypeRegistry.get(beanFactory).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 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); } @@ -326,15 +295,14 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit 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; @@ -354,19 +322,17 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit private final SearchStrategy strategy; - BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, - Class annotationType) { + BeanSearchSpec(ConditionContext context, AnnotatedTypeMetadata metadata, Class annotationType) { 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); collect(attributes, "annotation", this.annotations); collect(attributes, "ignored", this.ignoredTypes); collect(attributes, "ignoredType", this.ignoredTypes); - this.strategy = (SearchStrategy) metadata - .getAnnotationAttributes(annotationType.getName()).get("search"); + this.strategy = (SearchStrategy) metadata.getAnnotationAttributes(annotationType.getName()).get("search"); BeanTypeDeductionException deductionException = null; try { if (this.types.isEmpty() && this.names.isEmpty()) { @@ -381,13 +347,11 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit protected void validate(BeanTypeDeductionException ex) { if (!hasAtLeastOne(this.types, this.names, this.annotations)) { - String message = annotationName() - + " did not specify a bean using type, name or annotation"; + String message = annotationName() + " 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); } } @@ -404,8 +368,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit 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) { @@ -419,27 +382,23 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit } } - 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 { // We should be safe to load at this point since we are in the // REGISTER_BEAN phase - Class returnType = ClassUtils.forName(metadata.getReturnTypeName(), - context.getClassLoader()); + Class returnType = ClassUtils.forName(metadata.getReturnTypeName(), context.getClassLoader()); beanTypes.add(returnType.getName()); } catch (Throwable ex) { - throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), - metadata.getMethodName(), ex); + throw new BeanTypeDeductionException(metadata.getDeclaringClassName(), metadata.getMethodName(), ex); } } @@ -488,32 +447,29 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit 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, () -> annotationName() - + " annotations must specify only one type (got " + getTypes() + ")"); + Assert.isTrue(getTypes().size() == 1, + () -> annotationName() + " annotations must specify only one type (got " + getTypes() + ")"); } } 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); } } @@ -543,8 +499,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit 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); } 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 67e6a21c4c7..37e299e9cf9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +57,16 @@ class OnClassCondition extends SpringBootCondition private ClassLoader beanClassLoader; @Override - public boolean[] match(String[] autoConfigurationClasses, - AutoConfigurationMetadata autoConfigurationMetadata) { + public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { ConditionEvaluationReport report = getConditionEvaluationReport(); - ConditionOutcome[] outcomes = getOutcomes(autoConfigurationClasses, - autoConfigurationMetadata); + 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]); } } } @@ -77,10 +74,8 @@ class OnClassCondition extends SpringBootCondition } private ConditionEvaluationReport getConditionEvaluationReport() { - if (this.beanFactory != null - && this.beanFactory instanceof ConfigurableBeanFactory) { - return ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory); + if (this.beanFactory != null && this.beanFactory instanceof ConfigurableBeanFactory) { + return ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory); } return null; } @@ -91,11 +86,10 @@ class OnClassCondition extends SpringBootCondition // additional thread seems to offer the best performance. More threads make // things worse int split = autoConfigurationClasses.length / 2; - OutcomesResolver firstHalfResolver = createOutcomesResolver( - autoConfigurationClasses, 0, split, autoConfigurationMetadata); - OutcomesResolver secondHalfResolver = new StandardOutcomesResolver( - autoConfigurationClasses, split, autoConfigurationClasses.length, - autoConfigurationMetadata, this.beanClassLoader); + OutcomesResolver firstHalfResolver = createOutcomesResolver(autoConfigurationClasses, 0, split, + autoConfigurationMetadata); + OutcomesResolver secondHalfResolver = new StandardOutcomesResolver(autoConfigurationClasses, split, + autoConfigurationClasses.length, autoConfigurationMetadata, this.beanClassLoader); ConditionOutcome[] secondHalf = secondHalfResolver.resolveOutcomes(); ConditionOutcome[] firstHalf = firstHalfResolver.resolveOutcomes(); ConditionOutcome[] outcomes = new ConditionOutcome[autoConfigurationClasses.length]; @@ -104,11 +98,10 @@ class OnClassCondition extends SpringBootCondition return outcomes; } - private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, - int start, int end, AutoConfigurationMetadata autoConfigurationMetadata) { - OutcomesResolver outcomesResolver = new StandardOutcomesResolver( - autoConfigurationClasses, start, end, autoConfigurationMetadata, - this.beanClassLoader); + private OutcomesResolver createOutcomesResolver(String[] autoConfigurationClasses, int start, int end, + AutoConfigurationMetadata autoConfigurationMetadata) { + OutcomesResolver outcomesResolver = new StandardOutcomesResolver(autoConfigurationClasses, start, end, + autoConfigurationMetadata, this.beanClassLoader); try { return new ThreadedOutcomesResolver(outcomesResolver); } @@ -118,45 +111,36 @@ class OnClassCondition extends SpringBootCondition } @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 = getMatches(onClasses, MatchType.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, - getMatches(onClasses, MatchType.PRESENT, classLoader)); + .found("required class", "required classes") + .items(Style.QUOTE, getMatches(onClasses, MatchType.PRESENT, classLoader)); } - List onMissingClasses = getCandidates(metadata, - ConditionalOnMissingClass.class); + List onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class); if (onMissingClasses != null) { - List present = getMatches(onMissingClasses, MatchType.PRESENT, - classLoader); + List present = getMatches(onMissingClasses, MatchType.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, - getMatches(onMissingClasses, MatchType.MISSING, classLoader)); + .didNotFind("unwanted class", "unwanted classes") + .items(Style.QUOTE, getMatches(onMissingClasses, MatchType.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 Collections.emptyList(); } @@ -174,8 +158,7 @@ class OnClassCondition extends SpringBootCondition } } - private List getMatches(Collection candidates, MatchType matchType, - ClassLoader classLoader) { + private List getMatches(Collection candidates, MatchType matchType, ClassLoader classLoader) { List matches = new ArrayList<>(candidates.size()); for (String candidate : candidates) { if (matchType.matches(candidate, classLoader)) { @@ -228,8 +211,7 @@ class OnClassCondition 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); } @@ -253,8 +235,7 @@ class OnClassCondition extends SpringBootCondition 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(); } @@ -283,9 +264,8 @@ class OnClassCondition extends SpringBootCondition 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; @@ -295,17 +275,15 @@ class OnClassCondition extends SpringBootCondition @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]; - Set candidates = autoConfigurationMetadata - .getSet(autoConfigurationClass, "ConditionalOnClass"); + Set candidates = autoConfigurationMetadata.getSet(autoConfigurationClass, "ConditionalOnClass"); if (candidates != null) { outcomes[i - start] = getOutcome(candidates); } @@ -315,13 +293,10 @@ class OnClassCondition extends SpringBootCondition private ConditionOutcome getOutcome(Set candidates) { try { - List missing = getMatches(candidates, MatchType.MISSING, - this.beanClassLoader); + List missing = getMatches(candidates, MatchType.MISSING, this.beanClassLoader); 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)); } } catch (Exception ex) { 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 fe88bd36e81..cfa82646461 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. @@ -46,10 +46,8 @@ class OnWebApplicationCondition extends SpringBootCondition { + "support.GenericWebApplicationContext"; @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()); @@ -60,8 +58,8 @@ class OnWebApplicationCondition extends SpringBootCondition { 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); @@ -72,30 +70,25 @@ class OnWebApplicationCondition extends SpringBootCondition { } } - 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 (!ClassUtils.isPresent(WEB_CONTEXT_CLASS, context.getClassLoader())) { - return ConditionOutcome - .noMatch(message.didNotFind("web application classes").atAll()); + return ConditionOutcome.noMatch(message.didNotFind("web application classes").atAll()); } if (context.getBeanFactory() != null) { String[] scopes = context.getBeanFactory().getRegisteredScopeNames(); @@ -104,8 +97,7 @@ class OnWebApplicationCondition extends SpringBootCondition { } } 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")); @@ -116,20 +108,16 @@ class OnWebApplicationCondition extends SpringBootCondition { private ConditionOutcome isReactiveWebApplication(ConditionContext context) { ConditionMessage.Builder message = ConditionMessage.forCondition(""); 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 3f393c52c38..ac5ecf23325 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class MessageSourceAutoConfiguration { MessageSourceProperties properties = messageSourceProperties(); 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()); @@ -89,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); @@ -101,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 e8916c4bd0a..464af1dad0c 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 @@ -76,8 +76,7 @@ public class CouchbaseAutoConfiguration { @Bean @Primary public Cluster couchbaseCluster() throws Exception { - return CouchbaseCluster.create(couchbaseEnvironment(), - this.properties.getBootstrapHosts()); + return CouchbaseCluster.create(couchbaseEnvironment(), this.properties.getBootstrapHosts()); } @Bean @@ -85,8 +84,7 @@ public class CouchbaseAutoConfiguration { @DependsOn("couchbaseClient") public ClusterInfo couchbaseClusterInfo() throws Exception { return couchbaseCluster() - .clusterManager(this.properties.getBucket().getName(), - this.properties.getBucket().getPassword()) + .clusterManager(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()) .info(); } @@ -102,17 +100,14 @@ public class CouchbaseAutoConfiguration { * @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 CouchbaseAutoConfiguration { 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()); @@ -143,21 +137,18 @@ public class CouchbaseAutoConfiguration { @SuppressWarnings("deprecation") private QueryServiceConfig getQueryServiceConfig(Endpoints endpoints) { - return getServiceConfig(endpoints.getQueryservice(), endpoints.getQuery(), - QueryServiceConfig::create); + return getServiceConfig(endpoints.getQueryservice(), endpoints.getQuery(), QueryServiceConfig::create); } @SuppressWarnings("deprecation") private ViewServiceConfig getViewServiceConfig(Endpoints endpoints) { - return getServiceConfig(endpoints.getViewservice(), endpoints.getView(), - ViewServiceConfig::create); + return getServiceConfig(endpoints.getViewservice(), endpoints.getView(), ViewServiceConfig::create); } private T getServiceConfig(CouchbaseService service, Integer fallback, BiFunction factory) { if (service.getMinEndpoints() != 1 || service.getMaxEndpoints() != 1) { - return factory.apply(service.getMinEndpoints(), - service.getMaxEndpoints()); + return factory.apply(service.getMinEndpoints(), service.getMaxEndpoints()); } int endpoints = (fallback != null) ? fallback : 1; return factory.apply(endpoints, endpoints); @@ -184,8 +175,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/CouchbaseProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseProperties.java index dc3b1a648d2..0dca8c7a7ea 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 @@ -147,8 +147,7 @@ public class CouchbaseProperties { } @Deprecated - @DeprecatedConfigurationProperty( - replacement = "spring.couchbase.env.endpoints.queryservice.max-endpoints") + @DeprecatedConfigurationProperty(replacement = "spring.couchbase.env.endpoints.queryservice.max-endpoints") public Integer getQuery() { return this.query; } @@ -163,8 +162,7 @@ public class CouchbaseProperties { } @Deprecated - @DeprecatedConfigurationProperty( - replacement = "spring.couchbase.env.endpoints.viewservice.max-endpoints") + @DeprecatedConfigurationProperty(replacement = "spring.couchbase.env.endpoints.viewservice.max-endpoints") public Integer getView() { return this.view; } @@ -229,8 +227,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 690ffbaff71..3673cb5d995 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 f9b956f7568..23fea8da725 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.util.Streamable; * @author Oliver Gierke */ public abstract class AbstractRepositoryConfigurationSourceSupport - implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, - EnvironmentAware { + implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { private ResourceLoader resourceLoader; @@ -54,23 +53,19 @@ public abstract class AbstractRepositoryConfigurationSourceSupport private Environment environment; @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { - new RepositoryConfigurationDelegate(getConfigurationSource(registry), - this.resourceLoader, this.environment).registerRepositoriesIn(registry, - getRepositoryConfigurationExtension()); + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + new RepositoryConfigurationDelegate(getConfigurationSource(registry), this.resourceLoader, this.environment) + .registerRepositoriesIn(registry, getRepositoryConfigurationExtension()); } private AnnotationRepositoryConfigurationSource getConfigurationSource( BeanDefinitionRegistry beanDefinitionRegistry) { - StandardAnnotationMetadata metadata = new StandardAnnotationMetadata( - getConfiguration(), true); - return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), - this.resourceLoader, this.environment, beanDefinitionRegistry) { + StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getConfiguration(), true); + return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader, + this.environment, beanDefinitionRegistry) { @Override public Streamable getBasePackages() { - return AbstractRepositoryConfigurationSourceSupport.this - .getBasePackages(); + return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages(); } }; } 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 2e29bd66e26..6c3ca57deff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class CassandraDataAutoConfiguration { private final Environment environment; - public CassandraDataAutoConfiguration(BeanFactory beanFactory, - CassandraProperties properties, Cluster cluster, Environment environment) { + public CassandraDataAutoConfiguration(BeanFactory beanFactory, CassandraProperties properties, Cluster cluster, + Environment environment) { this.beanFactory = beanFactory; this.properties = properties; this.cluster = cluster; @@ -81,19 +81,18 @@ public class CassandraDataAutoConfiguration { @Bean @ConditionalOnMissingBean - public CassandraMappingContext cassandraMapping( - CassandraCustomConversions conversions) throws ClassNotFoundException { + public CassandraMappingContext cassandraMapping(CassandraCustomConversions conversions) + throws ClassNotFoundException { CassandraMappingContext context = new CassandraMappingContext(); - 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); } 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; } @@ -113,22 +112,19 @@ public class CassandraDataAutoConfiguration { @Bean @ConditionalOnMissingBean(Session.class) - public CassandraSessionFactoryBean cassandraSession(CassandraConverter converter) - throws Exception { + public CassandraSessionFactoryBean cassandraSession(CassandraConverter converter) throws Exception { CassandraSessionFactoryBean session = new CassandraSessionFactoryBean(); session.setCluster(this.cluster); session.setConverter(converter); session.setKeyspaceName(this.properties.getKeyspaceName()); Binder binder = Binder.get(this.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) throws Exception { + public CassandraTemplate cassandraTemplate(Session session, CassandraConverter converter) throws Exception { 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 02aefab2aec..731d5ffc4de 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/CassandraReactiveRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigureRegistrar.java index 30f69f5fd18..eafd56ca06a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 2.0.0 */ -class CassandraReactiveRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CassandraReactiveRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java index 20519614c7c..28f73926f2e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 1.3.0 */ -class CassandraRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class CassandraRepositoriesAutoConfigureRegistrar 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 d13b13c6b8d..1d3dd051ab7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 568f02db024..5bbd8069bc3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.data.couchbase.repository.CouchbaseRepository; */ @Configuration @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 @@ -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 2a65c17464a..e37e3f47dd7 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 @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 25f79111b04..8d37e68a4ed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ElasticsearchDataAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(Client.class) - public ElasticsearchTemplate elasticsearchTemplate(Client client, - ElasticsearchConverter converter) { + public ElasticsearchTemplate elasticsearchTemplate(Client client, ElasticsearchConverter converter) { try { return new ElasticsearchTemplate(client, converter); } @@ -63,8 +62,7 @@ public class ElasticsearchDataAutoConfiguration { @Bean @ConditionalOnMissingBean - public ElasticsearchConverter elasticsearchConverter( - SimpleElasticsearchMappingContext mappingContext) { + public ElasticsearchConverter elasticsearchConverter(SimpleElasticsearchMappingContext mappingContext) { return new MappingElasticsearchConverter(mappingContext); } 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 2abe02f67ed..0345109522d 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 @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/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 fce201f5f9c..9bff846d921 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 @@ -54,10 +54,9 @@ import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; @Configuration @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(JpaRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(HibernateJpaAutoConfiguration.class) public class JpaRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java index 44aabd733bf..a4146df2d6f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.repository.config.RepositoryConfigurationExtensi * @author Phillip Webb * @author Dave Syer */ -class JpaRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class JpaRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { 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 8e35f1cd691..83ad585baf4 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 @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 db94c2ddf7a..9c65621f08c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MongoDataAutoConfiguration { private final MongoProperties properties; - public MongoDataAutoConfiguration(ApplicationContext applicationContext, - MongoProperties properties) { + public MongoDataAutoConfiguration(ApplicationContext applicationContext, MongoProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @@ -94,33 +93,28 @@ public class MongoDataAutoConfiguration { @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 MongoMappingContext mongoMappingContext(MongoCustomConversions conversions) - throws ClassNotFoundException { + public MongoMappingContext mongoMappingContext(MongoCustomConversions conversions) throws ClassNotFoundException { MongoMappingContext context = new MongoMappingContext(); - context.setInitialEntitySet(new EntityScanner(this.applicationContext) - .scan(Document.class, Persistent.class)); + context.setInitialEntitySet(new EntityScanner(this.applicationContext).scan(Document.class, Persistent.class)); Class strategyClass = this.properties.getFieldNamingStrategy(); if (strategyClass != null) { - context.setFieldNamingStrategy( - (FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass)); + context.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass)); } context.setSimpleTypeHolder(conversions.getSimpleTypeHolder()); return context; @@ -128,10 +122,8 @@ public class MongoDataAutoConfiguration { @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/MongoReactiveDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.java index 5adbeed7b7b..7f74bf4ff09 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.data.mongodb.core.convert.MongoConverter; @Configuration @ConditionalOnClass({ MongoClient.class, ReactiveMongoTemplate.class }) @EnableConfigurationProperties(MongoProperties.class) -@AutoConfigureAfter({ MongoReactiveAutoConfiguration.class, - MongoDataAutoConfiguration.class }) +@AutoConfigureAfter({ MongoReactiveAutoConfiguration.class, MongoDataAutoConfiguration.class }) public class MongoReactiveDataAutoConfiguration { private final MongoProperties properties; @@ -60,16 +59,14 @@ public class MongoReactiveDataAutoConfiguration { @Bean @ConditionalOnMissingBean(ReactiveMongoDatabaseFactory.class) - public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory( - MongoClient mongo) { + public SimpleReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory(MongoClient mongo) { String database = this.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); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigureRegistrar.java index 9a286595b57..bedca2fb8a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.repository.config.RepositoryConfigurationExtensi * @author Mark Paluch * @since 2.0.0 */ -class MongoReactiveRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class MongoReactiveRepositoriesAutoConfigureRegistrar 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 d221559c593..495edf415b2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.mongodb.repository.support.MongoRepositoryFactor */ @Configuration @ConditionalOnClass({ MongoClient.class, MongoRepository.class }) -@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, - MongoRepositoryConfigurationExtension.class }) +@ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, MongoRepositoryConfigurationExtension.class }) @ConditionalOnRepositoryType(store = "mongodb", type = RepositoryType.IMPERATIVE) @Import(MongoRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(MongoDataAutoConfiguration.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java index cc82ea13a86..9a575d03fcd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 Dave Syer */ -class MongoRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class MongoRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { 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/Neo4jDataAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfiguration.java index cb57ea1291e..ad4f1a0de09 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 @@ -55,8 +55,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * @since 1.4.0 */ @Configuration -@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, - PlatformTransactionManager.class }) +@ConditionalOnClass({ SessionFactory.class, Neo4jTransactionManager.class, PlatformTransactionManager.class }) @ConditionalOnMissingBean(SessionFactory.class) @EnableConfigurationProperties(Neo4jProperties.class) public class Neo4jDataAutoConfiguration { @@ -69,10 +68,8 @@ 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)); List providedEventListeners = eventListeners.getIfAvailable(); if (providedEventListeners != null) { for (EventListener eventListener : providedEventListeners) { @@ -84,11 +81,9 @@ public class Neo4jDataAutoConfiguration { @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, @@ -100,8 +95,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); } @@ -112,15 +106,14 @@ 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 { @Configuration protected static class Neo4jWebMvcConfiguration implements WebMvcConfigurer { - private static final Log logger = LogFactory - .getLog(Neo4jWebMvcConfiguration.class); + private static final Log logger = LogFactory.getLog(Neo4jWebMvcConfiguration.class); private final Neo4jProperties neo4jProperties; 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 9c18ac545fa..d2754cfb9f9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -149,8 +149,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 097396c0412..783bf0a7168 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 @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(Neo4jRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(Neo4jDataAutoConfiguration.class) public class Neo4jRepositoriesAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java index d51ad88be37..dae95bbe46d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 Michael Hunger */ -class Neo4jRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class Neo4jRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { 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 063874feb66..444e4dbb93f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { ObjectProvider> builderCustomizers) { super(properties, sentinelConfiguration, clusterConfiguration); this.properties = properties; - this.builderCustomizers = builderCustomizers - .getIfAvailable(Collections::emptyList); + this.builderCustomizers = builderCustomizers.getIfAvailable(Collections::emptyList); } @Bean @@ -75,15 +74,13 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { 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() { - JedisClientConfigurationBuilder builder = applyProperties( - JedisClientConfiguration.builder()); + JedisClientConfigurationBuilder builder = applyProperties(JedisClientConfiguration.builder()); RedisProperties.Pool pool = this.properties.getJedis().getPool(); if (pool != null) { applyPooling(pool, builder); @@ -95,8 +92,7 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { return builder.build(); } - private JedisClientConfigurationBuilder applyProperties( - JedisClientConfigurationBuilder builder) { + private JedisClientConfigurationBuilder applyProperties(JedisClientConfigurationBuilder builder) { if (this.properties.isSsl()) { builder.useSsl(); } @@ -123,16 +119,14 @@ class JedisConnectionConfiguration extends RedisConnectionConfiguration { return config; } - private void customizeConfigurationFromUrl( - JedisClientConfiguration.JedisClientConfigurationBuilder builder) { + private void customizeConfigurationFromUrl(JedisClientConfiguration.JedisClientConfigurationBuilder builder) { ConnectionInfo connectionInfo = parseUrl(this.properties.getUrl()); if (connectionInfo.isUseSsl()) { builder.useSsl(); } } - private void customize( - JedisClientConfiguration.JedisClientConfigurationBuilder builder) { + private void customize(JedisClientConfiguration.JedisClientConfigurationBuilder builder) { for (JedisClientConfigurationBuilderCustomizer customizer : this.builderCustomizers) { customizer.customize(builder); } 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 3f50a218445..11a4f7effeb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 LettuceConnectionConfiguration extends RedisConnectionConfiguration { ObjectProvider> builderCustomizers) { super(properties, sentinelConfigurationProvider, clusterConfigurationProvider); this.properties = properties; - this.builderCustomizers = builderCustomizers - .getIfAvailable(Collections::emptyList); + this.builderCustomizers = builderCustomizers.getIfAvailable(Collections::emptyList); } @Bean(destroyMethod = "shutdown") @@ -72,27 +71,24 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { @Bean @ConditionalOnMissingBean(RedisConnectionFactory.class) - public LettuceConnectionFactory redisConnectionFactory( - ClientResources clientResources) throws UnknownHostException { - LettuceClientConfiguration clientConfig = getLettuceClientConfiguration( - clientResources, this.properties.getLettuce().getPool()); + public LettuceConnectionFactory redisConnectionFactory(ClientResources clientResources) + throws UnknownHostException { + LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(clientResources, + this.properties.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); } - private LettuceClientConfiguration getLettuceClientConfiguration( - ClientResources clientResources, Pool pool) { + private LettuceClientConfiguration getLettuceClientConfiguration(ClientResources clientResources, Pool pool) { LettuceClientConfigurationBuilder builder = createBuilder(pool); applyProperties(builder); if (StringUtils.hasText(this.properties.getUrl())) { @@ -120,25 +116,21 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { } if (this.properties.getLettuce() != null) { RedisProperties.Lettuce lettuce = this.properties.getLettuce(); - if (lettuce.getShutdownTimeout() != null - && !lettuce.getShutdownTimeout().isZero()) { - builder.shutdownTimeout( - this.properties.getLettuce().getShutdownTimeout()); + if (lettuce.getShutdownTimeout() != null && !lettuce.getShutdownTimeout().isZero()) { + builder.shutdownTimeout(this.properties.getLettuce().getShutdownTimeout()); } } return builder; } - private void customizeConfigurationFromUrl( - LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { + private void customizeConfigurationFromUrl(LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { ConnectionInfo connectionInfo = parseUrl(this.properties.getUrl()); if (connectionInfo.isUseSsl()) { builder.useSsl(); } } - private void customize( - LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { + private void customize(LettuceClientConfiguration.LettuceClientConfigurationBuilder builder) { for (LettuceClientConfigurationBuilderCustomizer customizer : this.builderCustomizers) { customizer.customize(builder); } @@ -150,8 +142,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) { 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 ed458e24057..31035655477 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 9cc5e9b4de9..e0a87ba8bc1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -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()); } @@ -120,8 +119,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 cd77d75b7b0..e141b56b27e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.redis.serializer.RedisSerializationContext; * @since 2.0.0 */ @Configuration -@ConditionalOnClass({ ReactiveRedisConnectionFactory.class, ReactiveRedisTemplate.class, - Flux.class }) +@ConditionalOnClass({ ReactiveRedisConnectionFactory.class, ReactiveRedisTemplate.class, Flux.class }) @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisReactiveAutoConfiguration { @@ -49,15 +48,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); } } 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 5c2711cdce2..847484a9e18 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 @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(RedisRepositoriesAutoConfigureRegistrar.class) @AutoConfigureAfter(RedisAutoConfiguration.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java index 30fb43990b2..4f52d714b36 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigureRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.data.repository.config.RepositoryConfigurationExtensi * @author Eddú Meléndez * @since 1.4.0 */ -class RedisRepositoriesAutoConfigureRegistrar - extends AbstractRepositoryConfigurationSourceSupport { +class RedisRepositoriesAutoConfigureRegistrar extends AbstractRepositoryConfigurationSourceSupport { @Override protected Class getAnnotation() { 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 6c5e93e207b..4807add7b95 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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 b6261393432..f148712c142 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 @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 a1eab8f9bae..d42e1f353ff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableSpringDataWebSupport @ConditionalOnWebApplication(type = Type.SERVLET) -@ConditionalOnClass({ PageableHandlerMethodArgumentResolver.class, - WebMvcConfigurer.class }) +@ConditionalOnClass({ PageableHandlerMethodArgumentResolver.class, WebMvcConfigurer.class }) @ConditionalOnMissingBean(PageableHandlerMethodArgumentResolver.class) @EnableConfigurationProperties(SpringDataWebProperties.class) @AutoConfigureAfter(RepositoryRestMvcAutoConfiguration.class) @@ -70,8 +69,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()); }; } @@ -79,8 +77,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 ce385fd2f37..fc279947aa5 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); } @@ -137,25 +128,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()); } @@ -170,14 +157,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; } @@ -185,8 +171,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())); } } } @@ -200,8 +185,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))); } } } @@ -212,8 +196,7 @@ class NoSuchBeanDefinitionFailureAnalyzer if (unsatisfiedDependencyException == null) { return Collections.emptyList(); } - return Arrays.asList( - unsatisfiedDependencyException.getInjectionPoint().getAnnotations()); + return Arrays.asList(unsatisfiedDependencyException.getInjectionPoint().getAnnotations()); } private class Source { @@ -246,8 +229,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()); @@ -266,23 +248,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)) { @@ -301,8 +279,7 @@ class NoSuchBeanDefinitionFailureAnalyzer } try { Class returnType = ClassUtils.forName(returnTypeName, - NoSuchBeanDefinitionFailureAnalyzer.this.beanFactory - .getBeanClassLoader()); + NoSuchBeanDefinitionFailureAnalyzer.this.beanFactory.getBeanClassLoader()); return type.isAssignableFrom(returnType); } catch (Throwable ex) { @@ -323,16 +300,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()); } @@ -354,9 +329,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 ad60b2b3be3..a4e9ecc6f2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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,17 +139,15 @@ 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<>(); packagesToScan.addAll(Arrays.asList(basePackages)); for (Class basePackageClass : basePackageClasses) { @@ -162,8 +155,7 @@ public class EntityScanPackages { } 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 4d408dd1573..647ccbe7706 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,11 +72,10 @@ public class JestAutoConfiguration { } protected HttpClientConfig createHttpClientConfig() { - HttpClientConfig.Builder builder = new HttpClientConfig.Builder( - this.properties.getUris()); + HttpClientConfig.Builder builder = new HttpClientConfig.Builder(this.properties.getUris()); PropertyMapper map = PropertyMapper.get(); - map.from(this.properties::getUsername).whenHasText().to((username) -> builder - .defaultCredentials(username, this.properties.getPassword())); + map.from(this.properties::getUsername).whenHasText() + .to((username) -> builder.defaultCredentials(username, this.properties.getPassword())); Proxy proxy = this.properties.getProxy(); map.from(proxy::getHost).whenHasText().to((host) -> { Assert.notNull(proxy.getPort(), "Proxy port must not be null"); @@ -84,10 +83,9 @@ public class JestAutoConfiguration { }); map.from(this.gsonProvider::getIfUnique).whenNonNull().to(builder::gson); map.from(this.properties::isMultiThreaded).to(builder::multiThreaded); - map.from(this.properties::getConnectionTimeout).whenNonNull() - .asInt(Duration::toMillis).to(builder::connTimeout); - map.from(this.properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::readTimeout); + map.from(this.properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) + .to(builder::connTimeout); + map.from(this.properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis).to(builder::readTimeout); 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/flyway/FlywayAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java index d5675517505..4145e8b9f9e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ import org.springframework.util.StringUtils; @ConditionalOnClass(Flyway.class) @ConditionalOnBean(DataSource.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 @@ -89,10 +89,8 @@ public class FlywayAutoConfiguration { } @Bean - public FlywaySchemaManagementProvider flywayDefaultDdlModeProvider( - ObjectProvider> flyways) { - return new FlywaySchemaManagementProvider( - flyways.getIfAvailable(Collections::emptyList)); + public FlywaySchemaManagementProvider flywayDefaultDdlModeProvider(ObjectProvider> flyways) { + return new FlywaySchemaManagementProvider(flyways.getIfAvailable(Collections::emptyList)); } @Configuration @@ -114,9 +112,8 @@ public class FlywayAutoConfiguration { private List flywayCallbacks; - public FlywayConfiguration(FlywayProperties properties, - DataSourceProperties dataSourceProperties, ResourceLoader resourceLoader, - ObjectProvider dataSource, + public FlywayConfiguration(FlywayProperties properties, DataSourceProperties dataSourceProperties, + ResourceLoader resourceLoader, ObjectProvider dataSource, @FlywayDataSource ObjectProvider flywayDataSource, ObjectProvider migrationStrategy, ObjectProvider> flywayCallbacks) { @@ -134,14 +131,10 @@ public class FlywayAutoConfiguration { public Flyway flyway() { Flyway flyway = new SpringBootFlyway(); if (this.properties.isCreateDataSource()) { - String url = getProperty(this.properties::getUrl, - this.dataSourceProperties::getUrl); - String user = getProperty(this.properties::getUser, - this.dataSourceProperties::getUsername); - String password = getProperty(this.properties::getPassword, - this.dataSourceProperties::getPassword); - flyway.setDataSource(url, user, password, - StringUtils.toStringArray(this.properties.getInitSqls())); + String url = getProperty(this.properties::getUrl, this.dataSourceProperties::getUrl); + String user = getProperty(this.properties::getUser, this.dataSourceProperties::getUsername); + String password = getProperty(this.properties::getPassword, this.dataSourceProperties::getPassword); + flyway.setDataSource(url, user, password, StringUtils.toStringArray(this.properties.getInitSqls())); } else if (this.flywayDataSource != null) { flyway.setDataSource(this.flywayDataSource); @@ -159,19 +152,16 @@ public class FlywayAutoConfiguration { return flyway; } - 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 void checkLocationExists(String... locations) { if (this.properties.isCheckLocation()) { - Assert.state(locations.length != 0, - "Migration script locations not configured"); + Assert.state(locations.length != 0, "Migration script locations not configured"); boolean exists = hasAtLeastOneLocation(locations); - Assert.state(exists, () -> "Cannot find migrations location in: " - + Arrays.asList(locations) + Assert.state(exists, () -> "Cannot find migrations location in: " + Arrays.asList(locations) + " (please add migrations or check your Flyway configuration)"); } } @@ -236,8 +226,7 @@ public class FlywayAutoConfiguration { @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class FlywayJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class FlywayJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public FlywayJpaDependencyConfiguration() { super("flyway"); @@ -252,8 +241,7 @@ public class FlywayAutoConfiguration { @Configuration @ConditionalOnClass(JdbcOperations.class) @ConditionalOnBean(JdbcOperations.class) - protected static class FlywayJdbcOperationsDependencyConfiguration - extends JdbcOperationsDependsOnPostProcessor { + protected static class FlywayJdbcOperationsDependencyConfiguration extends JdbcOperationsDependsOnPostProcessor { public FlywayJdbcOperationsDependencyConfiguration() { super("flyway"); @@ -265,8 +253,7 @@ public class FlywayAutoConfiguration { @Override public void setLocations(String... locations) { - super.setLocations( - new LocationResolver(getDataSource()).resolveLocations(locations)); + super.setLocations(new LocationResolver(getDataSource()).resolveLocations(locations)); } } @@ -293,14 +280,12 @@ public class FlywayAutoConfiguration { return locations; } - private String[] replaceVendorLocations(String[] locations, - DatabaseDriver databaseDriver) { + private String[] replaceVendorLocations(String[] locations, DatabaseDriver databaseDriver) { if (databaseDriver == DatabaseDriver.UNKNOWN) { return locations; } String vendor = databaseDriver.getId(); - return Arrays.stream(locations) - .map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor)) + return Arrays.stream(locations).map((location) -> location.replace(VENDOR_PLACEHOLDER, vendor)) .toArray(String[]::new); } @@ -329,8 +314,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; @@ -347,8 +331,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); } 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/FlywayProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java index c42e8dee3fd..0efaab4ab65 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 FlywayProperties { * The 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")); /** * Whether to check that migration scripts location exists. 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 b3b4c9802e1..f8652aa67b7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 @@ import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory; * @since 1.1.0 */ @Configuration -@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 fb2a8ca257d..d200b73cae1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a6ba5d1e6ee..a8be209d1a7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 8348209f151..47e5938a47a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @ConditionalOnClass(GroovyMarkupConfigurer.class) @@ -76,8 +75,7 @@ public class GroovyTemplateAutoConfiguration { private final MarkupTemplateEngine templateEngine; - public GroovyMarkupConfiguration(ApplicationContext applicationContext, - GroovyTemplateProperties properties, + public GroovyMarkupConfiguration(ApplicationContext applicationContext, GroovyTemplateProperties properties, ObjectProvider templateEngine) { this.applicationContext = applicationContext; this.properties = properties; @@ -87,13 +85,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)"); } } } @@ -107,11 +103,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; @@ -137,8 +131,7 @@ public class GroovyTemplateAutoConfiguration { } @Configuration - @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 { 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 50331bf2287..277b79535d7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +57,11 @@ public class GsonAutoConfiguration { } @Bean - public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer( - GsonProperties gsonProperties) { + public StandardGsonBuilderCustomizer standardGsonBuilderCustomizer(GsonProperties gsonProperties) { return new StandardGsonBuilderCustomizer(gsonProperties); } - private static final class StandardGsonBuilderCustomizer - implements GsonBuilderCustomizer, Ordered { + private static final class StandardGsonBuilderCustomizer implements GsonBuilderCustomizer, Ordered { private final GsonProperties properties; @@ -80,22 +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).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::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 8ddebd04931..df959b89cfc 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 @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 { @@ -54,8 +53,7 @@ public class H2ConsoleAutoConfiguration { public ServletRegistrationBean h2Console() { String path = this.properties.getPath(); String urlMapping = path.endsWith("/") ? path + "*" : path + "/*"; - ServletRegistrationBean registration = new ServletRegistrationBean<>( - new WebServlet(), urlMapping); + ServletRegistrationBean registration = new ServletRegistrationBean<>(new WebServlet(), urlMapping); H2ConsoleProperties.Settings settings = this.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 1841f353315..509c8bcf644 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.web.bind.annotation.RequestMapping; @ConditionalOnClass({ Resource.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 aa2f1d806eb..5fb54e65141 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 55c28802c48..7cb7e0c1067 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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,8 +77,7 @@ class HazelcastClientConfiguration { static class ConfigAvailableCondition extends HazelcastConfigResourceCondition { ConfigAvailableCondition() { - super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast-client.xml", - "classpath:/hazelcast-client.xml"); + super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast-client.xml", "classpath:/hazelcast-client.xml"); } } 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 77a197b2ef6..f774f0cc5eb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 HazelcastClientFactory { this.clientConfig = clientConfig; } - private ClientConfig getClientConfig(Resource clientConfigLocation) - throws IOException { + private ClientConfig getClientConfig(Resource clientConfigLocation) throws IOException { URL configUrl = clientConfigLocation.getURL(); return new XmlClientConfigBuilder(configUrl).build(); } @@ -68,8 +67,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 44c8d93d303..7ebffd3cc70 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; * @since 1.3.2 */ @Configuration -@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 9cae5d2db1e..3f5edb6e9ef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); + super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", "classpath:/hazelcast.xml"); } } 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 a91395877d5..e6bf58deae5 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 4cc1b7dd0f3..96c69b260fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class HttpMessageConverters implements Iterable> static { List> nonReplacingConverters = new ArrayList<>(); - addClassIfExists(nonReplacingConverters, "org.springframework.hateoas.mvc." - + "TypeConstrainedMappingJackson2HttpMessageConverter"); + addClassIfExists(nonReplacingConverters, + "org.springframework.hateoas.mvc." + "TypeConstrainedMappingJackson2HttpMessageConverter"); NON_REPLACING_CONVERTERS = Collections.unmodifiableList(nonReplacingConverters); } @@ -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 bbefaf6ab4d..ba8baf7c2c2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.http.converter.StringHttpMessageConverter; */ @Configuration @ConditionalOnClass(HttpMessageConverter.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 { @@ -60,16 +58,14 @@ public class HttpMessageConvertersAutoConfiguration { private final List> converters; - public HttpMessageConvertersAutoConfiguration( - ObjectProvider>> convertersProvider) { + public HttpMessageConvertersAutoConfiguration(ObjectProvider>> convertersProvider) { this.converters = convertersProvider.getIfAvailable(); } @Bean @ConditionalOnMissingBean public HttpMessageConverters messageConverters() { - return new HttpMessageConverters( - (this.converters != null) ? this.converters : Collections.emptyList()); + return new HttpMessageConverters((this.converters != null) ? this.converters : Collections.emptyList()); } @Configuration @@ -79,16 +75,14 @@ public class HttpMessageConvertersAutoConfiguration { private final HttpEncodingProperties encodingProperties; - protected StringHttpMessageConverterConfiguration( - HttpEncodingProperties encodingProperties) { + protected StringHttpMessageConverterConfiguration(HttpEncodingProperties encodingProperties) { this.encodingProperties = encodingProperties; } @Bean @ConditionalOnMissingBean public StringHttpMessageConverter stringHttpMessageConverter() { - StringHttpMessageConverter converter = new StringHttpMessageConverter( - this.encodingProperties.getCharset()); + StringHttpMessageConverter converter = new StringHttpMessageConverter(this.encodingProperties.getCharset()); converter.setWriteAcceptCharset(false); return converter; } 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 85a37dd2a74..8913496c19e 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,18 +41,15 @@ class JacksonHttpMessageConvertersConfiguration { @Configuration @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 { @Bean @ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, - ignoredType = { - "org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", + ignoredType = { "org.springframework.hateoas.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 +64,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 a7ec417061c..f64bbf1fa1f 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 f0a57f147f9..f436da57e6c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 32e7c718259..95991f93b23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 InfluxDbAutoConfiguration { private final OkHttpClient.Builder builder; - public InfluxDbAutoConfiguration(InfluxDbProperties properties, - ObjectProvider builder) { + public InfluxDbAutoConfiguration(InfluxDbProperties properties, ObjectProvider builder) { this.properties = properties; this.builder = builder.getIfAvailable(OkHttpClient.Builder::new); } @@ -56,8 +55,8 @@ public class InfluxDbAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnProperty("spring.influx.url") public InfluxDB influxDb() { - return new InfluxDBImpl(this.properties.getUrl(), this.properties.getUser(), - this.properties.getPassword(), this.builder); + return new InfluxDBImpl(this.properties.getUrl(), this.properties.getUser(), this.properties.getPassword(), + this.builder); } } 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 c4daafdc6dc..221f4aeadd8 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 @@ -63,13 +63,11 @@ public class ProjectInfoAutoConfiguration { return new GitProperties(loadFrom(this.properties.getGit().getLocation(), "git")); } - @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")); + return new BuildProperties(loadFrom(this.properties.getBuild().getLocation(), "build")); } protected Properties loadFrom(Resource location, String prefix) throws IOException { @@ -89,8 +87,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(); @@ -98,14 +95,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 ee32686a52e..883c9280205 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); public Resource getLocation() { return this.location; 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 5f0c977dc1f..112cad6afc2 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 @@ -78,13 +78,10 @@ public class IntegrationAutoConfiguration { */ @Configuration @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) - protected static class IntegrationJmxConfiguration - implements EnvironmentAware, BeanFactoryAware { + @ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) + protected static class IntegrationJmxConfiguration implements EnvironmentAware, BeanFactoryAware { private BeanFactory beanFactory; @@ -103,13 +100,11 @@ public class IntegrationAutoConfiguration { @Bean public IntegrationMBeanExporter integrationMbeanExporter() { IntegrationMBeanExporter exporter = new IntegrationMBeanExporter(); - String defaultDomain = this.environment - .getProperty("spring.jmx.default-domain"); + String defaultDomain = this.environment.getProperty("spring.jmx.default-domain"); if (StringUtils.hasLength(defaultDomain)) { exporter.setDefaultDomain(defaultDomain); } - String serverBean = this.environment.getProperty("spring.jmx.server", - "mbeanServer"); + String serverBean = this.environment.getProperty("spring.jmx.server", "mbeanServer"); exporter.setServer(this.beanFactory.getBean(serverBean, MBeanServer.class)); return exporter; } @@ -122,8 +117,7 @@ public class IntegrationAutoConfiguration { @Configuration @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 @@ -154,11 +148,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 31847b7c440..9b914dd6e4c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.integration.config.IntegrationComponentScanRegistrar; * @author Artem Bilan * @author Phillip Webb */ -class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScanRegistrar - implements BeanFactoryAware { +class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScanRegistrar implements BeanFactoryAware { private BeanFactory beanFactory; @@ -49,15 +48,14 @@ class IntegrationAutoConfigurationScanRegistrar extends IntegrationComponentScan @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, final BeanDefinitionRegistry registry) { - super.registerBeanDefinitions(new StandardAnnotationMetadata( - IntegrationComponentScanConfiguration.class, true), registry); + super.registerBeanDefinitions(new StandardAnnotationMetadata(IntegrationComponentScanConfiguration.class, true), + 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 9a147bce8e8..980258f2656 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +106,11 @@ public class JacksonAutoConfiguration { } @Configuration - @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); private final JacksonProperties jacksonProperties; @@ -124,30 +123,26 @@ public class JacksonAutoConfiguration { SimpleModule module = new SimpleModule(); JacksonJodaDateFormat jacksonJodaFormat = getJacksonJodaDateFormat(); if (jacksonJodaFormat != null) { - module.addSerializer(DateTime.class, - new DateTimeSerializer(jacksonJodaFormat, 0)); + module.addSerializer(DateTime.class, new DateTimeSerializer(jacksonJodaFormat, 0)); } return module; } private JacksonJodaDateFormat getJacksonJodaDateFormat() { if (this.jacksonProperties.getJodaDateTimeFormat() != null) { - return new JacksonJodaDateFormat(DateTimeFormat - .forPattern(this.jacksonProperties.getJodaDateTimeFormat()) - .withZoneUTC()); + return new JacksonJodaDateFormat( + DateTimeFormat.forPattern(this.jacksonProperties.getJodaDateTimeFormat()).withZoneUTC()); } if (this.jacksonProperties.getDateFormat() != null) { try { - return new JacksonJodaDateFormat(DateTimeFormat - .forPattern(this.jacksonProperties.getDateFormat()) - .withZoneUTC()); + return new JacksonJodaDateFormat( + DateTimeFormat.forPattern(this.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."); } } } @@ -204,10 +199,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); } private static final class StandardJackson2ObjectMapperBuilderCustomizer @@ -217,8 +210,7 @@ public class JacksonAutoConfiguration { private final JacksonProperties jacksonProperties; - StandardJackson2ObjectMapperBuilderCustomizer( - ApplicationContext applicationContext, + StandardJackson2ObjectMapperBuilderCustomizer(ApplicationContext applicationContext, JacksonProperties jacksonProperties) { this.applicationContext = applicationContext; this.jacksonProperties = jacksonProperties; @@ -233,8 +225,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()); @@ -251,8 +242,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 +262,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 +279,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 +287,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 +295,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 +317,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 +328,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 39ebbb37026..96a32b4cd0f 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. @@ -62,14 +62,12 @@ public class JacksonProperties { /** * Jackson on/off features that affect the way Java objects are serialized. */ - private Map serialization = new EnumMap<>( - SerializationFeature.class); + private Map serialization = new EnumMap<>(SerializationFeature.class); /** * Jackson on/off features that affect the way Java objects are deserialized. */ - private Map deserialization = new EnumMap<>( - DeserializationFeature.class); + private Map deserialization = new EnumMap<>(DeserializationFeature.class); /** * Jackson general purpose on/off features. @@ -79,14 +77,12 @@ public class JacksonProperties { /** * Jackson on/off features for parsers. */ - private Map parser = new EnumMap<>( - JsonParser.Feature.class); + private Map parser = new EnumMap<>(JsonParser.Feature.class); /** * Jackson on/off features for generators. */ - private Map generator = new EnumMap<>( - JsonGenerator.Feature.class); + private Map generator = new EnumMap<>(JsonGenerator.Feature.class); /** * Controls the inclusion of properties during serialization. Configured with one of @@ -153,8 +149,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 c460a6be3e6..ce88f3884b2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }) @EnableConfigurationProperties(DataSourceProperties.class) -@Import({ DataSourcePoolMetadataProvidersConfiguration.class, - DataSourceInitializationConfiguration.class }) +@Import({ DataSourcePoolMetadataProvidersConfiguration.class, DataSourceInitializationConfiguration.class }) public class DataSourceAutoConfiguration { @Configuration @@ -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 e3b924fedcb..f7bd44b302f 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 @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 @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 @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 4256be6d702..541a04ee606 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.core.type.AnnotationMetadata; * @author Stephane Nicoll */ @Configuration -@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 a8274dadfa3..8cf2fa55cd5 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 -@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 f1d5b7e137c..3b3caebe812 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +59,13 @@ public class DataSourceTransactionManagerAutoConfiguration { DataSourceTransactionManagerConfiguration(DataSource dataSource, ObjectProvider transactionManagerCustomizers) { this.dataSource = dataSource; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @ConditionalOnMissingBean(PlatformTransactionManager.class) - public DataSourceTransactionManager transactionManager( - DataSourceProperties properties) { - DataSourceTransactionManager transactionManager = new DataSourceTransactionManager( - this.dataSource); + public DataSourceTransactionManager transactionManager(DataSourceProperties properties) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(this.dataSource); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(transactionManager); } 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 79c6a1e81e6..a90ed2f1d1a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 class JdbcTemplateAutoConfiguration { jdbcTemplate.setFetchSize(template.getFetchSize()); jdbcTemplate.setMaxRows(template.getMaxRows()); if (template.getQueryTimeout() != null) { - jdbcTemplate - .setQueryTimeout((int) template.getQueryTimeout().getSeconds()); + jdbcTemplate.setQueryTimeout((int) template.getQueryTimeout().getSeconds()); } return jdbcTemplate; } @@ -87,8 +86,7 @@ public class JdbcTemplateAutoConfiguration { @Primary @ConditionalOnSingleCandidate(JdbcTemplate.class) @ConditionalOnMissingBean(NamedParameterJdbcOperations.class) - 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/JndiDataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.java index cb043959e7b..634e2397201 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.jmx.support.JmxUtils; * @since 1.2.0 */ @Configuration -@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) @@ -64,8 +63,7 @@ public class JndiDataSourceAutoConfiguration { } private void excludeMBeanIfNecessary(Object candidate, String beanName) { - for (MBeanExporter mbeanExporter : this.context - .getBeansOfType(MBeanExporter.class).values()) { + for (MBeanExporter mbeanExporter : this.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/XADataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfiguration.java index c74d22add16..889cf575c47 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.StringUtils; @Configuration @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 { @@ -89,11 +88,9 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware { private XADataSource createXaDataSource() { String className = this.properties.getXa().getDataSourceClassName(); if (!StringUtils.hasLength(className)) { - className = DatabaseDriver.fromJdbcUrl(this.properties.determineUrl()) - .getXaDataSourceClassName(); + className = DatabaseDriver.fromJdbcUrl(this.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, this.properties); return dataSource; @@ -107,19 +104,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", this.properties.determineUsername()); source.put("password", this.properties.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 72cf2b8b867..c01dd934567 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 5795caa1015..b956ae3f1cc 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 @@ -79,8 +79,8 @@ import org.springframework.web.filter.RequestContextFilter; * @author Stephane Nicoll */ @Configuration -@ConditionalOnClass(name = { "org.glassfish.jersey.server.spring.SpringComponentProvider", - "javax.servlet.ServletRegistration" }) +@ConditionalOnClass( + name = { "org.glassfish.jersey.server.spring.SpringComponentProvider", "javax.servlet.ServletRegistration" }) @ConditionalOnBean(type = "org.glassfish.jersey.server.ResourceConfig") @ConditionalOnWebApplication(type = Type.SERVLET) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @@ -128,8 +128,8 @@ public class JerseyAutoConfiguration implements ServletContextAware { if (StringUtils.hasLength(this.jersey.getApplicationPath())) { return this.jersey.getApplicationPath(); } - return findApplicationPath(AnnotationUtils.findAnnotation( - this.config.getApplication().getClass(), ApplicationPath.class)); + return findApplicationPath( + AnnotationUtils.findAnnotation(this.config.getApplication().getClass(), ApplicationPath.class)); } @Bean @@ -144,17 +144,13 @@ public class JerseyAutoConfiguration implements ServletContextAware { @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)); @@ -170,10 +166,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); @@ -201,20 +195,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 { @@ -233,19 +224,16 @@ public class JerseyAutoConfiguration implements ServletContextAware { private static final String JAXB_ANNOTATION_INTROSPECTOR_CLASS_NAME = "com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector"; @Bean - public ResourceConfigCustomizer resourceConfigCustomizer( - final ObjectMapper objectMapper) { + public ResourceConfigCustomizer resourceConfigCustomizer(final ObjectMapper objectMapper) { addJaxbAnnotationIntrospectorIfPresent(objectMapper); return (ResourceConfig config) -> { config.register(JacksonFeature.class); - config.register(new ObjectMapperContextResolver(objectMapper), - ContextResolver.class); + config.register(new ObjectMapperContextResolver(objectMapper), ContextResolver.class); }; } private void addJaxbAnnotationIntrospectorIfPresent(ObjectMapper objectMapper) { - if (ClassUtils.isPresent(JAXB_ANNOTATION_INTROSPECTOR_CLASS_NAME, - getClass().getClassLoader())) { + if (ClassUtils.isPresent(JAXB_ANNOTATION_INTROSPECTOR_CLASS_NAME, getClass().getClassLoader())) { new ObjectMapperCustomizer().addJaxbAnnotationIntrospector(objectMapper); } } @@ -256,22 +244,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 c0c66a0836b..b05a87f27ef 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 @@ -51,10 +51,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; @@ -75,8 +74,7 @@ class JmsAnnotationDrivenConfiguration { @Bean @ConditionalOnMissingBean(name = "jmsListenerContainerFactory") public DefaultJmsListenerContainerFactory jmsListenerContainerFactory( - DefaultJmsListenerContainerFactoryConfigurer configurer, - ConnectionFactory connectionFactory) { + DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; @@ -84,8 +82,7 @@ class JmsAnnotationDrivenConfiguration { @Configuration @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 0cc58456b18..2964012d24d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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); } 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 a79bc4ffc34..a42023575be 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. @@ -128,8 +128,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)); } @@ -221,8 +220,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 6190735067f..f0007d0f340 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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" }; private final JmsProperties properties; @@ -64,8 +63,7 @@ public class JndiConnectionFactoryAutoConfiguration { @Bean public ConnectionFactory connectionFactory() throws NamingException { if (StringUtils.hasLength(this.properties.getJndiName())) { - return new JndiLocatorDelegate().lookup(this.properties.getJndiName(), - ConnectionFactory.class); + return new JndiLocatorDelegate().lookup(this.properties.getJndiName(), ConnectionFactory.class); } return findJndiConnectionFactory(); } @@ -80,8 +78,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 27f0505f234..e204645a587 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 org.springframework.context.annotation.Import; @ConditionalOnClass({ ConnectionFactory.class, ActiveMQConnectionFactory.class }) @ConditionalOnMissingBean(ConnectionFactory.class) @EnableConfigurationProperties(ActiveMQProperties.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 3a8bd45688b..4b882d3fe47 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 @@ -45,13 +45,12 @@ import org.springframework.context.annotation.Configuration; class ActiveMQConnectionFactoryConfiguration { @Bean - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "false", matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "false", + matchIfMissing = true) public ActiveMQConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers) { - return new ActiveMQConnectionFactoryFactory(properties, - factoryCustomizers.getIfAvailable()) - .createConnectionFactory(ActiveMQConnectionFactory.class); + return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable()) + .createConnectionFactory(ActiveMQConnectionFactory.class); } @Configuration @@ -59,42 +58,33 @@ class ActiveMQConnectionFactoryConfiguration { static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") - @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", - havingValue = "true", matchIfMissing = false) - public PooledConnectionFactory pooledJmsConnectionFactory( - ActiveMQProperties properties, + @ConditionalOnProperty(prefix = "spring.activemq.pool", name = "enabled", havingValue = "true", + matchIfMissing = false) + public PooledConnectionFactory pooledJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers) { PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory( - new ActiveMQConnectionFactoryFactory(properties, - factoryCustomizers.getIfAvailable()).createConnectionFactory( - ActiveMQConnectionFactory.class)); + new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable()) + .createConnectionFactory(ActiveMQConnectionFactory.class)); ActiveMQProperties.Pool pool = properties.getPool(); pooledConnectionFactory.setBlockIfSessionPoolIsFull(pool.isBlockIfFull()); if (pool.getBlockIfFullTimeout() != null) { - pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout( - pool.getBlockIfFullTimeout().toMillis()); + pooledConnectionFactory.setBlockIfSessionPoolIsFullTimeout(pool.getBlockIfFullTimeout().toMillis()); } - pooledConnectionFactory - .setCreateConnectionOnStartup(pool.isCreateConnectionOnStartup()); + pooledConnectionFactory.setCreateConnectionOnStartup(pool.isCreateConnectionOnStartup()); if (pool.getExpiryTimeout() != null) { - pooledConnectionFactory - .setExpiryTimeout(pool.getExpiryTimeout().toMillis()); + pooledConnectionFactory.setExpiryTimeout(pool.getExpiryTimeout().toMillis()); } if (pool.getIdleTimeout() != null) { - pooledConnectionFactory - .setIdleTimeout((int) pool.getIdleTimeout().toMillis()); + pooledConnectionFactory.setIdleTimeout((int) pool.getIdleTimeout().toMillis()); } pooledConnectionFactory.setMaxConnections(pool.getMaxConnections()); - pooledConnectionFactory.setMaximumActiveSessionPerConnection( - pool.getMaximumActiveSessionPerConnection()); - pooledConnectionFactory - .setReconnectOnException(pool.isReconnectOnException()); + pooledConnectionFactory.setMaximumActiveSessionPerConnection(pool.getMaximumActiveSessionPerConnection()); + pooledConnectionFactory.setReconnectOnException(pool.isReconnectOnException()); if (pool.getTimeBetweenExpirationCheck() != null) { - pooledConnectionFactory.setTimeBetweenExpirationCheckMillis( - pool.getTimeBetweenExpirationCheck().toMillis()); + pooledConnectionFactory + .setTimeBetweenExpirationCheckMillis(pool.getTimeBetweenExpirationCheck().toMillis()); } - pooledConnectionFactory - .setUseAnonymousProducers(pool.isUseAnonymousProducers()); + pooledConnectionFactory.setUseAnonymousProducers(pool.isUseAnonymousProducers()); return pooledConnectionFactory; } 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/ActiveMQProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java index 4732117ca0a..49b017265fa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/activemq/ActiveMQProperties.java @@ -267,8 +267,7 @@ public class ActiveMQProperties { return this.maximumActiveSessionPerConnection; } - public void setMaximumActiveSessionPerConnection( - int maximumActiveSessionPerConnection) { + public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) { this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection; } 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 f793d93f14d..a4bc9c5a116 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 @@ -52,21 +52,18 @@ class ActiveMQXAConnectionFactoryConfiguration { public ConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider> factoryCustomizers, XAConnectionFactoryWrapper wrapper) throws Exception { - ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory( - properties, factoryCustomizers.getIfAvailable()) - .createConnectionFactory(ActiveMQXAConnectionFactory.class); + ActiveMQXAConnectionFactory connectionFactory = new ActiveMQConnectionFactoryFactory(properties, + factoryCustomizers.getIfAvailable()).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.getIfAvailable()) - .createConnectionFactory(ActiveMQConnectionFactory.class); + return new ActiveMQConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable()) + .createConnectionFactory(ActiveMQConnectionFactory.class); } } 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 725a0ef9cc1..4a14875c132 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.context.annotation.Import; @ConditionalOnClass({ ConnectionFactory.class, ActiveMQConnectionFactory.class }) @ConditionalOnMissingBean(ConnectionFactory.class) @EnableConfigurationProperties(ArtemisProperties.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/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 da42d1fabd2..e91f3a4f2f3 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)); + return new CoreAddressConfiguration().setName(name).addRoutingType(RoutingType.ANYCAST) + .addQueueConfiguration(new CoreQueueConfiguration().setName(name).setRoutingType(RoutingType.ANYCAST)); } 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 ee492ef16e4..46b8d540641 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 @@ -44,8 +44,8 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator; */ @Configuration @ConditionalOnClass(name = ArtemisConnectionFactoryFactory.EMBEDDED_JMS_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; @@ -69,14 +69,12 @@ 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) { EmbeddedJMS server = new EmbeddedJMS(); customize(configuration); @@ -86,8 +84,7 @@ class ArtemisEmbeddedServerConfiguration { return server; } - private void customize( - org.apache.activemq.artemis.core.config.Configuration configuration) { + private void customize(org.apache.activemq.artemis.core.config.Configuration configuration) { if (this.configurationCustomizers != null) { AnnotationAwareOrderComparator.sort(this.configurationCustomizers); for (ArtemisConfigurationCustomizer customizer : this.configurationCustomizers) { 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 5e0aafddb58..28f8a54c8b9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 6496f3aa5c0..137bea9d10d 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 @@ -52,8 +52,7 @@ import org.springframework.util.StringUtils; */ @Configuration @ConditionalOnClass({ MBeanExporter.class }) -@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.jmx", name = "enabled", havingValue = "true", matchIfMissing = true) public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware { private Environment environment; @@ -72,14 +71,12 @@ public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware @Bean @Primary - @ConditionalOnMissingBean(value = MBeanExporter.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = MBeanExporter.class, search = SearchStrategy.CURRENT) public AnnotationMBeanExporter mbeanExporter(ObjectNamingStrategy namingStrategy) { 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(this.beanFactory.getBean(serverBean, MBeanServer.class)); } @@ -87,11 +84,9 @@ public class JmxAutoConfiguration implements EnvironmentAware, BeanFactoryAware } @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); 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 8092a39895f..4aaf80e6a19 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +58,18 @@ import org.springframework.transaction.PlatformTransactionManager; @Configuration @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); } @@ -109,12 +105,10 @@ public class JooqAutoConfiguration { private final TransactionListenerProvider[] transactionListenerProviders; - public DslContextConfiguration(JooqProperties properties, - ConnectionProvider connectionProvider, DataSource dataSource, - ObjectProvider transactionProvider, + public DslContextConfiguration(JooqProperties properties, ConnectionProvider connectionProvider, + DataSource dataSource, ObjectProvider transactionProvider, ObjectProvider recordMapperProvider, - ObjectProvider recordUnmapperProvider, - ObjectProvider settings, + ObjectProvider recordUnmapperProvider, ObjectProvider settings, ObjectProvider recordListenerProviders, ExecuteListenerProvider[] executeListenerProviders, ObjectProvider visitListenerProviders, @@ -129,8 +123,7 @@ public class JooqAutoConfiguration { this.recordListenerProviders = recordListenerProviders.getIfAvailable(); this.executeListenerProviders = executeListenerProviders; this.visitListenerProviders = visitListenerProviders.getIfAvailable(); - this.transactionListenerProviders = transactionListenerProviders - .getIfAvailable(); + this.transactionListenerProviders = transactionListenerProviders.getIfAvailable(); } @Bean @@ -159,8 +152,7 @@ public class JooqAutoConfiguration { configuration.set(this.recordListenerProviders); configuration.set(this.executeListenerProviders); configuration.set(this.visitListenerProviders); - configuration - .setTransactionListenerProvider(this.transactionListenerProviders); + configuration.setTransactionListenerProvider(this.transactionListenerProviders); 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 6444f000d38..ab5e4cc441b 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 @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 560c04989f4..3bc68a51f35 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,24 +72,20 @@ 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(); Listener properties = this.properties.getListener(); map.from(properties::getConcurrency).whenNonNull().to(factory::setConcurrency); - map.from(() -> this.messageConverter).whenNonNull() - .to(factory::setMessageConverter); + map.from(() -> this.messageConverter).whenNonNull().to(factory::setMessageConverter); map.from(() -> this.replyTemplate).whenNonNull().to(factory::setReplyTemplate); - map.from(properties::getType).whenEqualTo(Listener.Type.BATCH) - .toCall(() -> factory.setBatchListener(true)); + map.from(properties::getType).whenEqualTo(Listener.Type.BATCH).toCall(() -> factory.setBatchListener(true)); } private void configureContainer(ContainerProperties container) { @@ -98,18 +94,14 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { map.from(properties::getAckMode).whenNonNull().to(container::setAckMode); map.from(properties::getClientId).whenNonNull().to(container::setClientId); map.from(properties::getAckCount).whenNonNull().to(container::setAckCount); - map.from(properties::getAckTime).whenNonNull().as(Duration::toMillis) - .to(container::setAckTime); - map.from(properties::getPollTimeout).whenNonNull().as(Duration::toMillis) - .to(container::setPollTimeout); - map.from(properties::getNoPollThreshold).whenNonNull() - .to(container::setNoPollThreshold); + map.from(properties::getAckTime).whenNonNull().as(Duration::toMillis).to(container::setAckTime); + map.from(properties::getPollTimeout).whenNonNull().as(Duration::toMillis).to(container::setPollTimeout); + map.from(properties::getNoPollThreshold).whenNonNull().to(container::setNoPollThreshold); map.from(properties::getIdleEventInterval).whenNonNull().as(Duration::toMillis) .to(container::setIdleEventInterval); - map.from(properties::getMonitorInterval).whenNonNull().as(Duration::getSeconds) - .as(Number::intValue).to(container::setMonitorInterval); - map.from(properties::getLogContainerConfig).whenNonNull() - .to(container::setLogContainerConfig); + map.from(properties::getMonitorInterval).whenNonNull().as(Duration::getSeconds).as(Number::intValue) + .to(container::setMonitorInterval); + map.from(properties::getLogContainerConfig).whenNonNull().to(container::setLogContainerConfig); } } 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 792643207d6..ce6cdafedcb 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 @@ -75,8 +75,7 @@ class KafkaAnnotationDrivenConfiguration { @Configuration @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 7b15ab416f2..7ba75a9a3e2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +59,16 @@ public class KafkaAutoConfiguration { private final RecordMessageConverter messageConverter; - public KafkaAutoConfiguration(KafkaProperties properties, - ObjectProvider messageConverter) { + public KafkaAutoConfiguration(KafkaProperties properties, ObjectProvider messageConverter) { this.properties = properties; this.messageConverter = messageConverter.getIfUnique(); } @Bean @ConditionalOnMissingBean(KafkaTemplate.class) - public KafkaTemplate kafkaTemplate( - ProducerFactory kafkaProducerFactory, + public KafkaTemplate kafkaTemplate(ProducerFactory kafkaProducerFactory, ProducerListener kafkaProducerListener) { - KafkaTemplate kafkaTemplate = new KafkaTemplate<>( - kafkaProducerFactory); + KafkaTemplate kafkaTemplate = new KafkaTemplate<>(kafkaProducerFactory); if (this.messageConverter != null) { kafkaTemplate.setMessageConverter(this.messageConverter); } @@ -89,8 +86,7 @@ public class KafkaAutoConfiguration { @Bean @ConditionalOnMissingBean(ConsumerFactory.class) public ConsumerFactory kafkaConsumerFactory() { - return new DefaultKafkaConsumerFactory<>( - this.properties.buildConsumerProperties()); + return new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()); } @Bean @@ -98,8 +94,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); } @@ -109,8 +104,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 78c8cd2820a..4f2e80cf484 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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. @@ -138,8 +137,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); @@ -377,27 +375,19 @@ 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) - .to(properties.in(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)); + map.from(this::getFetchMinSize).to(properties.in(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)); 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); } @@ -558,21 +548,14 @@ 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) - .to(properties.in(ProducerConfig.BATCH_SIZE_CONFIG)); - map.from(this::getBootstrapServers) - .to(properties.in(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); - map.from(this::getBufferMemory) - .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::getBatchSize).to(properties.in(ProducerConfig.BATCH_SIZE_CONFIG)); + map.from(this::getBootstrapServers).to(properties.in(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); + map.from(this::getBufferMemory).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::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); } @@ -624,8 +607,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); } @@ -922,20 +904,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; } @@ -945,8 +922,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); } } @@ -994,8 +970,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/ldap/LdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java index 1a37d66bc7c..30f2ef0313f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 LdapAutoConfiguration { source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly()); source.setBase(this.properties.getBase()); source.setUrls(this.properties.determineUrls(this.environment)); - source.setBaseEnvironmentProperties( - Collections.unmodifiableMap(this.properties.getBaseEnvironment())); + source.setBaseEnvironmentProperties(Collections.unmodifiableMap(this.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 40a8eef718e..36f815a4a64 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +89,8 @@ public class EmbeddedLdapAutoConfiguration { private InMemoryDirectoryServer server; - public EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties, - LdapProperties properties, ConfigurableApplicationContext applicationContext, - Environment environment) { + public EmbeddedLdapAutoConfiguration(EmbeddedLdapProperties embeddedProperties, LdapProperties properties, + ConfigurableApplicationContext applicationContext, Environment environment) { this.embeddedProperties = embeddedProperties; this.properties = properties; this.applicationContext = applicationContext; @@ -116,13 +115,12 @@ public class EmbeddedLdapAutoConfiguration { 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(); @@ -149,14 +147,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() throws LDAPException { @@ -178,8 +174,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) { @@ -210,16 +206,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 bc13d7c4fe4..688e7cab7f0 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 @@ -65,23 +65,19 @@ import org.springframework.util.Assert; @Configuration @ConditionalOnClass({ SpringLiquibase.class, DatabaseChange.class }) @ConditionalOnBean(DataSource.class) -@ConditionalOnProperty(prefix = "spring.liquibase", name = "enabled", - matchIfMissing = true) -@AutoConfigureAfter({ DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class }) +@ConditionalOnProperty(prefix = "spring.liquibase", name = "enabled", matchIfMissing = true) +@AutoConfigureAfter({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class LiquibaseAutoConfiguration { @Bean public LiquibaseSchemaManagementProvider liquibaseDefaultDdlModeProvider( ObjectProvider> liquibases) { - return new LiquibaseSchemaManagementProvider( - liquibases.getIfAvailable(Collections::emptyList)); + return new LiquibaseSchemaManagementProvider(liquibases.getIfAvailable(Collections::emptyList)); } @Configuration @ConditionalOnMissingBean(SpringLiquibase.class) - @EnableConfigurationProperties({ DataSourceProperties.class, - LiquibaseProperties.class }) + @EnableConfigurationProperties({ DataSourceProperties.class, LiquibaseProperties.class }) @Import(LiquibaseJpaDependencyConfiguration.class) public static class LiquibaseConfiguration { @@ -95,9 +91,8 @@ public class LiquibaseAutoConfiguration { private final DataSource liquibaseDataSource; - public LiquibaseConfiguration(LiquibaseProperties properties, - DataSourceProperties dataSourceProperties, ResourceLoader resourceLoader, - ObjectProvider dataSource, + public LiquibaseConfiguration(LiquibaseProperties properties, DataSourceProperties dataSourceProperties, + ResourceLoader resourceLoader, ObjectProvider dataSource, @LiquibaseDataSource ObjectProvider liquibaseDataSource) { this.properties = properties; this.dataSourceProperties = dataSourceProperties; @@ -109,12 +104,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)"); } } @@ -155,18 +147,13 @@ public class LiquibaseAutoConfiguration { } private DataSource createNewDataSource() { - String url = getProperty(this.properties::getUrl, - this.dataSourceProperties::getUrl); - String user = getProperty(this.properties::getUser, - this.dataSourceProperties::getUsername); - String password = getProperty(this.properties::getPassword, - this.dataSourceProperties::getPassword); - return DataSourceBuilder.create().url(url).username(user).password(password) - .build(); + String url = getProperty(this.properties::getUrl, this.dataSourceProperties::getUrl); + String user = getProperty(this.properties::getUser, this.dataSourceProperties::getUsername); + String password = getProperty(this.properties::getPassword, this.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(); } @@ -180,8 +167,7 @@ public class LiquibaseAutoConfiguration { @Configuration @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) - protected static class LiquibaseJpaDependencyConfiguration - extends EntityManagerFactoryDependsOnPostProcessor { + protected static class LiquibaseJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor { public LiquibaseJpaDependencyConfiguration() { super("liquibase"); @@ -196,8 +182,7 @@ public class LiquibaseAutoConfiguration { @Configuration @ConditionalOnClass(JdbcOperations.class) @ConditionalOnBean(JdbcOperations.class) - protected static class LiquibaseJdbcOperationsDependencyConfiguration - extends JdbcOperationsDependsOnPostProcessor { + protected static class LiquibaseJdbcOperationsDependencyConfiguration extends JdbcOperationsDependsOnPostProcessor { public LiquibaseJdbcOperationsDependencyConfiguration() { super("liquibase"); 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/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 4ff136e122c..6670e2dd96a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +63,7 @@ class MailSenderJndiConfiguration { return new JndiLocatorDelegate().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 415a9e4c18b..8d1384d2946 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MongoAutoConfiguration { private MongoClient mongo; - public MongoAutoConfiguration(MongoProperties properties, - ObjectProvider options, Environment environment) { + public MongoAutoConfiguration(MongoProperties properties, ObjectProvider options, + Environment environment) { this.options = options.getIfAvailable(); this.factory = new MongoClientFactory(properties, environment); } 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 67d6183f6ec..d2fcbfec701 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +65,10 @@ public class MongoReactiveAutoConfiguration { @Bean @ConditionalOnMissingBean - public MongoClient reactiveStreamsMongoClient(MongoProperties properties, - Environment environment, + public MongoClient reactiveStreamsMongoClient(MongoProperties properties, Environment environment, ObjectProvider> builderCustomizers) { - ReactiveMongoClientFactory factory = new ReactiveMongoClientFactory(properties, - environment, builderCustomizers.getIfAvailable()); + ReactiveMongoClientFactory factory = new ReactiveMongoClientFactory(properties, environment, + builderCustomizers.getIfAvailable()); this.mongo = factory.createMongoClient(this.settings); return this.mongo; } @@ -84,8 +83,7 @@ public class MongoReactiveAutoConfiguration { ObjectProvider settings) { return (builder) -> { if (!isStreamFactoryFactoryDefined(settings.getIfAvailable())) { - builder.streamFactoryFactory( - NettyStreamFactoryFactory.builder().build()); + builder.streamFactoryFactory(NettyStreamFactoryFactory.builder().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 8878a86f683..b29c4379092 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. @@ -54,8 +54,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(); } /** @@ -83,11 +82,9 @@ 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"; + String host = (this.properties.getHost() != null) ? this.properties.getHost() : "localhost"; ClusterSettings clusterSettings = ClusterSettings.builder() .hosts(Collections.singletonList(new ServerAddress(host, port))).build(); builder.clusterSettings(clusterSettings); @@ -98,14 +95,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); @@ -113,17 +109,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.clusterSettings(ClusterSettings.builder() - .hosts(Collections.singletonList(serverAddress)).build()); + builder.clusterSettings(ClusterSettings.builder().hosts(Collections.singletonList(serverAddress)).build()); 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()))); } @@ -136,8 +130,7 @@ public class ReactiveMongoClientFactory { return MongoClients.create(builder.build()); } - private Builder createBuilder(MongoClientSettings settings, - ConnectionString connection) { + private Builder createBuilder(MongoClientSettings settings, ConnectionString connection) { Builder builder = builder(settings); builder.clusterSettings(getClusterSettings(connection)); builder.connectionPoolSettings(getConnectionPoolSettings(connection)); @@ -167,8 +160,7 @@ public class ReactiveMongoClientFactory { return ClusterSettings.builder().applyConnectionString(connection).build(); } - private ConnectionPoolSettings getConnectionPoolSettings( - ConnectionString connection) { + private ConnectionPoolSettings getConnectionPoolSettings(ConnectionString connection) { return ConnectionPoolSettings.builder().applyConnectionString(connection).build(); } @@ -195,8 +187,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 f2d1e9da290..69f1e0ed8d0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; @@ -95,9 +94,8 @@ public class EmbeddedMongoAutoConfiguration { private final IRuntimeConfig runtimeConfig; - public EmbeddedMongoAutoConfiguration(MongoProperties properties, - EmbeddedMongoProperties embeddedProperties, ApplicationContext context, - IRuntimeConfig runtimeConfig) { + public EmbeddedMongoAutoConfiguration(MongoProperties properties, EmbeddedMongoProperties embeddedProperties, + ApplicationContext context, IRuntimeConfig runtimeConfig) { this.properties = properties; this.embeddedProperties = embeddedProperties; this.context = context; @@ -106,8 +104,7 @@ public class EmbeddedMongoAutoConfiguration { @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean - public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig) - throws IOException { + public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig) throws IOException { Integer configuredPort = this.properties.getPort(); if (configuredPort == null || configuredPort == 0) { setEmbeddedPort(mongodConfig.net().getPort()); @@ -127,10 +124,8 @@ public class EmbeddedMongoAutoConfiguration { @ConditionalOnMissingBean public IMongodConfig embeddedMongoConfiguration() throws IOException { IFeatureAwareVersion featureAwareVersion = new ToStringFriendlyFeatureAwareVersion( - this.embeddedProperties.getVersion(), - this.embeddedProperties.getFeatures()); - MongodConfigBuilder builder = new MongodConfigBuilder() - .version(featureAwareVersion); + this.embeddedProperties.getVersion(), this.embeddedProperties.getFeatures()); + MongodConfigBuilder builder = new MongodConfigBuilder().version(featureAwareVersion); EmbeddedMongoProperties.Storage storage = this.embeddedProperties.getStorage(); if (storage != null) { String databaseDir = storage.getDatabaseDir(); @@ -140,20 +135,18 @@ public class EmbeddedMongoAutoConfiguration { } 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 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()); } @@ -164,8 +157,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) { @@ -190,22 +183,17 @@ public class EmbeddedMongoAutoConfiguration { @Bean public IRuntimeConfig embeddedMongoRuntimeConfig() { - 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)) - .build(); + 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)).build(); } private ArtifactStoreBuilder getArtifactStore(Logger logger) { - return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD) - .download(new DownloadConfigBuilder() - .defaultsForCommand(Command.MongoD) - .progressListener(new Slf4jProgressListener(logger)).build()); + return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD).download(new DownloadConfigBuilder() + .defaultsForCommand(Command.MongoD).progressListener(new Slf4jProgressListener(logger)).build()); } } @@ -216,8 +204,7 @@ public class EmbeddedMongoAutoConfiguration { */ @Configuration @ConditionalOnClass({ MongoClient.class, MongoClientFactoryBean.class }) - protected static class EmbeddedMongoDependencyConfiguration - extends MongoClientDependsOnBeanFactoryPostProcessor { + protected static class EmbeddedMongoDependencyConfiguration extends MongoClientDependsOnBeanFactoryPostProcessor { public EmbeddedMongoDependencyConfiguration() { super("embeddedMongoServer"); @@ -230,8 +217,7 @@ public class EmbeddedMongoAutoConfiguration { * {@code embeddedMongoServer} bean. */ @Configuration - @ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class, - ReactiveMongoClientFactoryBean.class }) + @ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class, ReactiveMongoClientFactoryBean.class }) protected static class EmbeddedReactiveMongoDependencyConfiguration extends ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor { @@ -245,15 +231,13 @@ public class EmbeddedMongoAutoConfiguration { * A workaround for the lack of a {@code toString} implementation on * {@code GenericFeatureAwareVersion}. */ - private static final class ToStringFriendlyFeatureAwareVersion - implements IFeatureAwareVersion { + private static final class ToStringFriendlyFeatureAwareVersion implements IFeatureAwareVersion { private final String version; private final Set features; - private ToStringFriendlyFeatureAwareVersion(String version, - Set features) { + private ToStringFriendlyFeatureAwareVersion(String version, Set features) { Assert.notNull(version, "version must not be null"); this.version = version; this.features = (features != null) ? features : Collections.emptySet(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java index 4e41a443b44..880ee028023 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 EmbeddedMongoProperties { /** * Comma-separated list of features to enable. */ - private Set features = new HashSet<>( - Collections.singletonList(Feature.SYNC_DELAY)); + private Set features = new HashSet<>(Collections.singletonList(Feature.SYNC_DELAY)); public String getVersion() { return this.version; 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 e6a64f51e96..88e482cf0f1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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)"); } } @@ -79,8 +78,7 @@ public class MustacheAutoConfiguration { @Bean @ConditionalOnMissingBean public Mustache.Compiler mustacheCompiler(TemplateLoader mustacheTemplateLoader) { - return Mustache.compiler().withLoader(mustacheTemplateLoader) - .withCollector(collector()); + return Mustache.compiler().withLoader(mustacheTemplateLoader).withCollector(collector()); } private Collector collector() { @@ -92,8 +90,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 365433f2cfc..18dc0111588 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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/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/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 b2a0674ab04..830d6fa335c 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. @@ -51,14 +51,12 @@ class DataSourceInitializedPublisher implements BeanPostProcessor { private JpaProperties properties; @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) { // Normally this will be the right DataSource this.dataSource = (DataSource) bean; @@ -75,24 +73,21 @@ 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 != null && dataSource instanceof DataSource) - ? (DataSource) dataSource : this.dataSource; + Object dataSource = entityManagerFactory.getProperties().get("javax.persistence.nonJtaDataSource"); + return (dataSource != null && dataSource instanceof DataSource) ? (DataSource) dataSource : this.dataSource; } private boolean isInitializingDatabase(DataSource dataSource) { if (this.properties == null) { return true; // better safe than sorry } - Supplier defaultDdlAuto = () -> (EmbeddedDatabaseConnection - .isEmbedded(dataSource) ? "create-drop" : "none"); + Supplier defaultDdlAuto = () -> (EmbeddedDatabaseConnection.isEmbedded(dataSource) ? "create-drop" + : "none"); Map hibernate = this.properties .getHibernateProperties(new HibernateSettings().ddlAuto(defaultDdlAuto)); if (hibernate.containsKey("hibernate.hbm2ddl.auto")) { 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 d10002c3fa7..1f3461a71a3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 d53cabd35c5..9223ba89779 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,27 +95,22 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { ObjectProvider physicalNamingStrategy, ObjectProvider implicitNamingStrategy, ObjectProvider> hibernatePropertiesCustomizers) { - super(dataSource, jpaProperties, jtaTransactionManager, - transactionManagerCustomizers); + super(dataSource, jpaProperties, jtaTransactionManager, transactionManagerCustomizers); this.defaultDdlAutoProvider = new HibernateDefaultDdlAutoProvider( providers.getIfAvailable(Collections::emptyList)); - this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider( - metadataProviders.getIfAvailable()); + this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(metadataProviders.getIfAvailable()); this.hibernatePropertiesCustomizers = determineHibernatePropertiesCustomizers( - physicalNamingStrategy.getIfAvailable(), - implicitNamingStrategy.getIfAvailable(), + physicalNamingStrategy.getIfAvailable(), implicitNamingStrategy.getIfAvailable(), hibernatePropertiesCustomizers.getIfAvailable(Collections::emptyList)); } private List determineHibernatePropertiesCustomizers( - PhysicalNamingStrategy physicalNamingStrategy, - ImplicitNamingStrategy implicitNamingStrategy, + PhysicalNamingStrategy physicalNamingStrategy, ImplicitNamingStrategy implicitNamingStrategy, List hibernatePropertiesCustomizers) { if (physicalNamingStrategy != null || implicitNamingStrategy != null) { - LinkedList customizers = new LinkedList<>( - hibernatePropertiesCustomizers); - customizers.addFirst(new NamingStrategiesHibernatePropertiesCustomizer( - physicalNamingStrategy, implicitNamingStrategy)); + LinkedList customizers = new LinkedList<>(hibernatePropertiesCustomizers); + customizers.addFirst( + new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); return customizers; } return hibernatePropertiesCustomizers; @@ -128,12 +123,9 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { @Override protected Map getVendorProperties() { - Supplier defaultDdlMode = () -> this.defaultDdlAutoProvider - .getDefaultDdlAuto(getDataSource()); - return new LinkedHashMap<>( - getProperties().getHibernateProperties(new HibernateSettings() - .ddlAuto(defaultDdlMode).hibernatePropertiesCustomizers( - this.hibernatePropertiesCustomizers))); + Supplier defaultDdlMode = () -> this.defaultDdlAutoProvider.getDefaultDdlAuto(getDataSource()); + return new LinkedHashMap<>(getProperties().getHibernateProperties(new HibernateSettings() + .ddlAuto(defaultDdlMode).hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); } @Override @@ -147,8 +139,7 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { } } - private void configureJtaPlatform(Map vendorProperties) - throws LinkageError { + private void configureJtaPlatform(Map vendorProperties) throws LinkageError { JtaTransactionManager jtaTransactionManager = getJtaTransactionManager(); if (jtaTransactionManager != null) { if (runningOnWebSphere()) { @@ -166,28 +157,23 @@ 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 configureWebSphereTransactionPlatform( - Map vendorProperties) { + private void configureWebSphereTransactionPlatform(Map vendorProperties) { vendorProperties.put(JTA_PLATFORM, getWebSphereJtaPlatformManager()); } @@ -198,15 +184,13 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { 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 @@ -241,15 +225,13 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { throw new IllegalStateException("Could not configure JTA platform"); } - 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; @@ -258,12 +240,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/HibernateSettings.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateSettings.java index fba2f32cd96..13df839b771 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. @@ -55,8 +55,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 3d01169c3b2..37606499537 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 @@ -89,8 +89,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { this.dataSource = dataSource; this.properties = properties; this.jtaTransactionManager = jtaTransactionManager.getIfAvailable(); - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @@ -117,27 +116,22 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Bean @ConditionalOnMissingBean @SuppressWarnings("deprecation") - public EntityManagerFactoryBuilder entityManagerFactoryBuilder( - JpaVendorAdapter jpaVendorAdapter, + public EntityManagerFactoryBuilder entityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, ObjectProvider persistenceUnitManager) { - EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder( - jpaVendorAdapter, this.properties.getProperties(), - persistenceUnitManager.getIfAvailable()); + EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(jpaVendorAdapter, + this.properties.getProperties(), persistenceUnitManager.getIfAvailable()); builder.setCallback(getVendorCallback()); 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(); @@ -158,8 +152,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); } @@ -168,8 +161,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); } /** @@ -212,10 +204,8 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass(WebMvcConfigurer.class) - @ConditionalOnMissingBean({ OpenEntityManagerInViewInterceptor.class, - OpenEntityManagerInViewFilter.class }) - @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", - havingValue = "true", matchIfMissing = true) + @ConditionalOnMissingBean({ OpenEntityManagerInViewInterceptor.class, OpenEntityManagerInViewFilter.class }) + @ConditionalOnProperty(prefix = "spring.jpa", name = "open-in-view", havingValue = "true", matchIfMissing = true) protected static class JpaWebConfiguration { // Defined as a nested config to ensure WebMvcConfigurerAdapter is not read when @@ -223,8 +213,7 @@ public abstract class JpaBaseConfiguration implements BeanFactoryAware { @Configuration protected static class JpaWebMvcConfiguration implements WebMvcConfigurer { - private static final Log logger = LogFactory - .getLog(JpaWebMvcConfiguration.class); + private static final Log logger = LogFactory.getLog(JpaWebMvcConfiguration.class); private final JpaProperties jpaProperties; @@ -237,8 +226,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/orm/jpa/JpaProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java index 0753df1b296..58f4003d403 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -168,8 +168,7 @@ public class JpaProperties { public static class Hibernate { - private static final String USE_NEW_ID_GENERATOR_MAPPINGS = "hibernate.id." - + "new_generator_mappings"; + private static final String USE_NEW_ID_GENERATOR_MAPPINGS = "hibernate.id." + "new_generator_mappings"; /** * DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" @@ -208,8 +207,7 @@ public class JpaProperties { return this.naming; } - private Map getAdditionalProperties(Map existing, - HibernateSettings settings) { + private Map getAdditionalProperties(Map existing, HibernateSettings settings) { Map result = new HashMap<>(existing); applyNewIdGeneratorMappings(result); getNaming().applyNamingStrategies(result); @@ -220,8 +218,7 @@ public class JpaProperties { else { result.remove("hibernate.hbm2ddl.auto"); } - Collection customizers = settings - .getHibernatePropertiesCustomizers(); + Collection customizers = settings.getHibernatePropertiesCustomizers(); if (!ObjectUtils.isEmpty(customizers)) { customizers.forEach((customizer) -> customizer.customize(result)); } @@ -230,16 +227,14 @@ public class JpaProperties { private void applyNewIdGeneratorMappings(Map result) { if (this.useNewIdGeneratorMappings != null) { - result.put(USE_NEW_ID_GENERATOR_MAPPINGS, - this.useNewIdGeneratorMappings.toString()); + result.put(USE_NEW_ID_GENERATOR_MAPPINGS, this.useNewIdGeneratorMappings.toString()); } else if (!result.containsKey(USE_NEW_ID_GENERATOR_MAPPINGS)) { result.put(USE_NEW_ID_GENERATOR_MAPPINGS, "true"); } } - private String determineDdlAuto(Map existing, - Supplier defaultDdlAuto) { + private String determineDdlAuto(Map existing, Supplier defaultDdlAuto) { String ddlAuto = existing.get("hibernate.hbm2ddl.auto"); if (ddlAuto != null) { return ddlAuto; @@ -282,14 +277,14 @@ public class JpaProperties { } private void applyNamingStrategies(Map properties) { - applyNamingStrategy(properties, "hibernate.implicit_naming_strategy", - this.implicitStrategy, DEFAULT_IMPLICIT_STRATEGY); - applyNamingStrategy(properties, "hibernate.physical_naming_strategy", - this.physicalStrategy, DEFAULT_PHYSICAL_STRATEGY); + applyNamingStrategy(properties, "hibernate.implicit_naming_strategy", this.implicitStrategy, + DEFAULT_IMPLICIT_STRATEGY); + applyNamingStrategy(properties, "hibernate.physical_naming_strategy", this.physicalStrategy, + DEFAULT_PHYSICAL_STRATEGY); } - 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/quartz/QuartzAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfiguration.java index 7b3caacad9d..df0971b51c6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +53,9 @@ import org.springframework.transaction.PlatformTransactionManager; * @since 2.0.0 */ @Configuration -@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 { private final QuartzProperties properties; @@ -73,10 +71,9 @@ public class QuartzAutoConfiguration { private final ApplicationContext applicationContext; public QuartzAutoConfiguration(QuartzProperties properties, - ObjectProvider> customizers, - ObjectProvider jobDetails, - ObjectProvider> calendars, - ObjectProvider triggers, ApplicationContext applicationContext) { + ObjectProvider> customizers, ObjectProvider jobDetails, + ObjectProvider> calendars, ObjectProvider triggers, + ApplicationContext applicationContext) { this.properties = properties; this.customizers = customizers.getIfAvailable(); this.jobDetails = jobDetails.getIfAvailable(); @@ -89,11 +86,10 @@ public class QuartzAutoConfiguration { @ConditionalOnMissingBean public SchedulerFactoryBean quartzScheduler() { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); - schedulerFactoryBean.setJobFactory(new AutowireCapableBeanJobFactory( - this.applicationContext.getAutowireCapableBeanFactory())); + schedulerFactoryBean.setJobFactory( + new AutowireCapableBeanJobFactory(this.applicationContext.getAutowireCapableBeanFactory())); if (!this.properties.getProperties().isEmpty()) { - schedulerFactoryBean - .setQuartzProperties(asProperties(this.properties.getProperties())); + schedulerFactoryBean.setQuartzProperties(asProperties(this.properties.getProperties())); } if (this.jobDetails != null && this.jobDetails.length > 0) { schedulerFactoryBean.setJobDetails(this.jobDetails); @@ -128,17 +124,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); } @@ -146,21 +139,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 @@ -172,8 +162,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/security/SecurityDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java index 6261e9c3141..881d9a7433b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SecurityDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.security.data.repository.query.SecurityEvaluationCont * @since 1.3 */ @Configuration -@ConditionalOnClass({ SecurityEvaluationContextExtension.class, - EvaluationContextExtensionSupport.class }) +@ConditionalOnClass({ SecurityEvaluationContextExtension.class, EvaluationContextExtensionSupport.class }) public class SecurityDataConfiguration { @Bean 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 0fe03d994a4..13f0a712e7a 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 = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 100; + public static final int DEFAULT_FILTER_ORDER = FilterRegistrationBean.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/OAuth2ClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientAutoConfiguration.java index 911524bba39..17b17740095 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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/OAuth2ClientPropertiesRegistrationAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java index d21ff1d93b1..3bdd84c6a37 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. @@ -43,40 +43,35 @@ 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()))); return clientRegistrations; } - private static ClientRegistration getClientRegistration(String registrationId, - Registration properties, Map providers) { + private static ClientRegistration getClientRegistration(String registrationId, Registration properties, + Map providers) { Builder 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); map.from(properties::getRedirectUriTemplate).to(builder::redirectUriTemplate); - map.from(properties::getScope).as((scope) -> StringUtils.toStringArray(scope)) - .to(builder::scope); + map.from(properties::getScope).as((scope) -> StringUtils.toStringArray(scope)).to(builder::scope); map.from(properties::getClientName).to(builder::clientName); return builder.build(); } 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); @@ -86,12 +81,9 @@ 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) { @@ -106,8 +98,7 @@ 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/OAuth2ClientRegistrationRepositoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfiguration.java index f4dfbc1c1d7..c290e965919 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 OAuth2ClientRegistrationRepositoryConfiguration { @ConditionalOnMissingBean(ClientRegistrationRepository.class) public InMemoryClientRegistrationRepository clientRegistrationRepository() { List registrations = new ArrayList<>( - OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(this.properties).values()); + OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(this.properties).values()); return new InMemoryClientRegistrationRepository(registrations); } @@ -73,29 +72,23 @@ class OAuth2ClientRegistrationRepositoryConfiguration { */ static class ClientsConfiguredCondition extends SpringBootCondition { - private static final Bindable> BINDABLE_REGISTRATION = Bindable - .mapOf(String.class, OAuth2ClientProperties.Registration.class); + private static final Bindable> BINDABLE_REGISTRATION = Bindable.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 = this - .getRegistrations(context.getEnvironment()); + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth2 Clients Configured Condition"); + Map registrations = this.getRegistrations(context.getEnvironment()); if (!registrations.isEmpty()) { - return ConditionOutcome.match(message.foundExactly( - "registered clients " + registrations.values().stream() - .map(OAuth2ClientProperties.Registration::getClientId) + 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", - BINDABLE_REGISTRATION) + return Binder.get(environment).bind("spring.security.oauth2.client.registration", BINDABLE_REGISTRATION) .orElse(Collections.emptyMap()); } 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 f87470ab380..6c840afb285 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.security.web.server.WebFilterChainProxy; */ @Configuration @EnableConfigurationProperties(SecurityProperties.class) -@ConditionalOnClass({ Flux.class, EnableWebFluxSecurity.class, - WebFilterChainProxy.class }) +@ConditionalOnClass({ Flux.class, EnableWebFluxSecurity.class, WebFilterChainProxy.class }) public class ReactiveSecurityAutoConfiguration { @Configuration 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 5ed1b0fa0ab..74bb330653b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,41 +47,33 @@ import org.springframework.util.StringUtils; */ @Configuration @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 f06417b2e85..2ecabaefa90 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 59d4e08c979..a5d3c33d01c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.security.web.context.AbstractSecurityWebApplicationIn @Configuration @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 eee378ec93d..004faff6b1f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 671cf5c79b9..aa45f7b5e58 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 @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 3dfbf8dbeae..b47babb5d54 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 SendGridAutoConfiguration { @ConditionalOnMissingBean public SendGrid sendGrid() { if (this.properties.isProxyConfigured()) { - HttpHost proxy = new HttpHost(this.properties.getProxy().getHost(), - this.properties.getProxy().getPort()); + HttpHost proxy = new HttpHost(this.properties.getProxy().getHost(), this.properties.getProxy().getPort()); return new SendGrid(this.properties.getApiKey(), new Client(HttpClientBuilder.create().setProxy(proxy).build())); } 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 04f83d61744..7f799177bf8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 9d6b457a462..510ab74ff9a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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 3b4a47edad7..0b4b9c1ac5b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 0b1560106a6..01b7ee24e6e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.session.data.mongo.config.annotation.web.reactive.Rea * @author Andy Wilkinson */ @Configuration -@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 530396f1342..0eaccd16848 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 aeb152d779b..1b7f2ed6479 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.session.data.redis.config.annotation.web.server.Redis * @author Andy Wilkinson */ @Configuration -@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 1c710899e1b..df83bf9be34 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 4ecd4bd8246..eafa8d61c92 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +77,19 @@ import org.springframework.util.StringUtils; @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 { @Configuration @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(); @@ -101,8 +98,7 @@ 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())); + map.from(cookie::getMaxAge).to((maxAge) -> cookieSerializer.setCookieMaxAge((int) maxAge.getSeconds())); return cookieSerializer; } @@ -165,8 +161,7 @@ public class SessionAutoConfiguration { List imports = new ArrayList<>(); StoreType[] types = StoreType.values(); for (int i = 0; i < types.length; i++) { - imports.add(SessionStoreMappings.getConfigurationClass(webApplicationType, - types[i])); + imports.add(SessionStoreMappings.getConfigurationClass(webApplicationType, types[i])); } return StringUtils.toStringArray(imports); } @@ -177,8 +172,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) { @@ -191,8 +185,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) { @@ -213,8 +206,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; @@ -254,14 +246,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")); } } @@ -273,12 +264,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")); } } @@ -301,8 +291,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 " @@ -318,8 +307,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) { @@ -332,8 +320,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 c1711421960..2d3af57fcc1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,8 +111,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 244f5ee9baa..7906fdd5306 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 46a645fd806..bcb0e535078 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SolrAutoConfiguration { private SolrClient createSolrClient() { if (StringUtils.hasText(this.properties.getZkHost())) { - return new CloudSolrClient.Builder().withZkHost(this.properties.getZkHost()) - .build(); + return new CloudSolrClient.Builder().withZkHost(this.properties.getZkHost()).build(); } return new HttpSolrClient.Builder(this.properties.getHost()).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 8c652972290..6bfb966db1b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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 a6c7bef23da..ad72a6ae5d4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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)"); } } @@ -183,8 +179,7 @@ public class ThymeleafAutoConfiguration { private final SpringTemplateEngine templateEngine; - ThymeleafViewResolverConfiguration(ThymeleafProperties properties, - SpringTemplateEngine templateEngine) { + ThymeleafViewResolverConfiguration(ThymeleafProperties properties, SpringTemplateEngine templateEngine) { this.properties = properties; this.templateEngine = templateEngine; } @@ -196,8 +191,7 @@ public class ThymeleafAutoConfiguration { resolver.setTemplateEngine(this.templateEngine); resolver.setCharacterEncoding(this.properties.getEncoding().name()); resolver.setContentType( - appendCharset(this.properties.getServlet().getContentType(), - resolver.getCharacterEncoding())); + appendCharset(this.properties.getServlet().getContentType(), resolver.getCharacterEncoding())); resolver.setExcludedViewNames(this.properties.getExcludedViewNames()); resolver.setViewNames(this.properties.getViewNames()); // This resolver acts as a fallback resolver (e.g. like a @@ -232,8 +226,7 @@ public class ThymeleafAutoConfiguration { private final Collection dialects; - ThymeleafReactiveConfiguration(ThymeleafProperties properties, - Collection templateResolvers, + ThymeleafReactiveConfiguration(ThymeleafProperties properties, Collection templateResolvers, ObjectProvider> dialectsProvider) { this.properties = properties; this.templateResolvers = templateResolvers; @@ -265,8 +258,7 @@ public class ThymeleafAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "thymeleafReactiveViewResolver") - public ThymeleafReactiveViewResolver thymeleafViewResolver( - ISpringWebFluxTemplateEngine templateEngine) { + public ThymeleafReactiveViewResolver thymeleafViewResolver(ISpringWebFluxTemplateEngine templateEngine) { ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver(); resolver.setTemplateEngine(templateEngine); mapProperties(this.properties, resolver); @@ -277,24 +269,19 @@ 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).when((size) -> size > 0) - .to(resolver::setResponseMaxChunkSizeBytes); + map.from(properties::getMediaTypes).whenNonNull().to(resolver::setSupportedMediaTypes); + map.from(properties::getMaxChunkSize).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); } } @@ -327,8 +314,7 @@ public class ThymeleafAutoConfiguration { @ConditionalOnClass({ SpringSecurityDialect.class }) protected static class ThymeleafSecurityDialectConfiguration { - private final Log logger = LogFactory - .getLog(ThymeleafSecurityDialectConfiguration.class); + private final Log logger = LogFactory.getLog(ThymeleafSecurityDialectConfiguration.class); @Bean @ConditionalOnMissingBean @@ -343,8 +329,7 @@ public class ThymeleafAutoConfiguration { } @Configuration - @ConditionalOnClass({ - org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect.class }) + @ConditionalOnClass({ org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect.class }) protected static class ThymeleafSecurity5DialectConfiguration { @Bean 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 72c443d8715..6ad8c659a3e 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 @ConditionalOnClass(PlatformTransactionManager.class) @AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, - Neo4jDataAutoConfiguration.class }) + DataSourceTransactionManagerAutoConfiguration.class, Neo4jDataAutoConfiguration.class }) @EnableConfigurationProperties(TransactionProperties.class) public class TransactionAutoConfiguration { @@ -65,8 +64,7 @@ public class TransactionAutoConfiguration { private final PlatformTransactionManager transactionManager; - public TransactionTemplateConfiguration( - PlatformTransactionManager transactionManager) { + public TransactionTemplateConfiguration(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } @@ -85,16 +83,16 @@ public class TransactionAutoConfiguration { @Configuration @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 @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 8822d22ffca..0038ed86c7d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +68,15 @@ class AtomikosJtaConfiguration { AtomikosJtaConfiguration(JtaProperties jtaProperties, ObjectProvider transactionManagerCustomizers) { this.jtaProperties = jtaProperties; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean(initMethod = "init", destroyMethod = "shutdownWait") @ConditionalOnMissingBean(UserTransactionService.class) - public UserTransactionServiceImp userTransactionService( - AtomikosProperties atomikosProperties) { + public UserTransactionServiceImp userTransactionService(AtomikosProperties atomikosProperties) { Properties properties = new Properties(); if (StringUtils.hasText(this.jtaProperties.getTransactionManagerId())) { - properties.setProperty("com.atomikos.icatch.tm_unique_name", - this.jtaProperties.getTransactionManagerId()); + properties.setProperty("com.atomikos.icatch.tm_unique_name", this.jtaProperties.getTransactionManagerId()); } properties.setProperty("com.atomikos.icatch.log_base_dir", getLogBaseDir()); properties.putAll(atomikosProperties.asProperties()); @@ -96,8 +93,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); @@ -119,8 +116,7 @@ class AtomikosJtaConfiguration { @Bean public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - userTransaction, transactionManager); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, transactionManager); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(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 f6904a7e3ee..b67c5dbc43b 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 @@ -65,8 +65,7 @@ class BitronixJtaConfiguration { BitronixJtaConfiguration(JtaProperties jtaProperties, ObjectProvider transactionManagerCustomizers) { this.jtaProperties = jtaProperties; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @@ -94,8 +93,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(); } @@ -113,10 +111,8 @@ class BitronixJtaConfiguration { } @Bean - public JtaTransactionManager transactionManager( - TransactionManager transactionManager) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - transactionManager); + public JtaTransactionManager transactionManager(TransactionManager transactionManager) { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(transactionManager); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(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 f1c987614f9..19b8f0955ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +37,20 @@ import org.springframework.transaction.jta.JtaTransactionManager; */ @Configuration @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 { private final TransactionManagerCustomizers transactionManagerCustomizers; - JndiJtaConfiguration( - ObjectProvider transactionManagerCustomizers) { - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + JndiJtaConfiguration(ObjectProvider transactionManagerCustomizers) { + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean public JtaTransactionManager transactionManager() { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean() - .getObject(); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManagerFactoryBean().getObject(); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(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 575ecb97981..60d2b4f5587 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,10 @@ import org.springframework.context.annotation.Import; @Configuration @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, NarayanaJtaConfiguration.class }) +@AutoConfigureBefore({ XADataSourceAutoConfiguration.class, ActiveMQAutoConfiguration.class, + ArtemisAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) +@Import({ JndiJtaConfiguration.class, BitronixJtaConfiguration.class, AtomikosJtaConfiguration.class, + NarayanaJtaConfiguration.class }) @EnableConfigurationProperties(JtaProperties.class) public class JtaAutoConfiguration { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java index cd3df9ef308..aa3d05c1458 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/jta/NarayanaJtaConfiguration.java @@ -56,8 +56,8 @@ import org.springframework.util.StringUtils; * @since 1.4.0 */ @Configuration -@ConditionalOnClass({ JtaTransactionManager.class, - com.arjuna.ats.jta.UserTransaction.class, XAResourceRecoveryRegistry.class }) +@ConditionalOnClass({ JtaTransactionManager.class, com.arjuna.ats.jta.UserTransaction.class, + XAResourceRecoveryRegistry.class }) @ConditionalOnMissingBean(PlatformTransactionManager.class) @EnableConfigurationProperties(JtaProperties.class) public class NarayanaJtaConfiguration { @@ -69,8 +69,7 @@ public class NarayanaJtaConfiguration { public NarayanaJtaConfiguration(JtaProperties jtaProperties, ObjectProvider transactionManagerCustomizers) { this.jtaProperties = jtaProperties; - this.transactionManagerCustomizers = transactionManagerCustomizers - .getIfAvailable(); + this.transactionManagerCustomizers = transactionManagerCustomizers.getIfAvailable(); } @Bean @@ -81,12 +80,10 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean - public NarayanaConfigurationBean narayanaConfiguration( - NarayanaProperties properties) { + public NarayanaConfigurationBean narayanaConfiguration(NarayanaProperties properties) { properties.setLogDir(getLogDir().getAbsolutePath()); if (this.jtaProperties.getTransactionManagerId() != null) { - properties.setTransactionManagerId( - this.jtaProperties.getTransactionManagerId()); + properties.setTransactionManagerId(this.jtaProperties.getTransactionManagerId()); } return new NarayanaConfigurationBean(properties); } @@ -122,16 +119,14 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean - public NarayanaRecoveryManagerBean narayanaRecoveryManager( - RecoveryManagerService recoveryManagerService) { + public NarayanaRecoveryManagerBean narayanaRecoveryManager(RecoveryManagerService recoveryManagerService) { return new NarayanaRecoveryManagerBean(recoveryManagerService); } @Bean public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager) { - JtaTransactionManager jtaTransactionManager = new JtaTransactionManager( - userTransaction, transactionManager); + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, transactionManager); if (this.transactionManagerCustomizers != null) { this.transactionManagerCustomizers.customize(jtaTransactionManager); } @@ -140,11 +135,9 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean - public XADataSourceWrapper xaDataSourceWrapper( - NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, + public XADataSourceWrapper xaDataSourceWrapper(NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, NarayanaProperties narayanaProperties) { - return new NarayanaXADataSourceWrapper(narayanaRecoveryManagerBean, - narayanaProperties); + return new NarayanaXADataSourceWrapper(narayanaRecoveryManagerBean, narayanaProperties); } @Bean @@ -159,12 +152,10 @@ public class NarayanaJtaConfiguration { @Bean @ConditionalOnMissingBean(XAConnectionFactoryWrapper.class) - public NarayanaXAConnectionFactoryWrapper xaConnectionFactoryWrapper( - TransactionManager transactionManager, - NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, - NarayanaProperties narayanaProperties) { - return new NarayanaXAConnectionFactoryWrapper(transactionManager, - narayanaRecoveryManagerBean, narayanaProperties); + public NarayanaXAConnectionFactoryWrapper xaConnectionFactoryWrapper(TransactionManager transactionManager, + NarayanaRecoveryManagerBean narayanaRecoveryManagerBean, NarayanaProperties narayanaProperties) { + return new NarayanaXAConnectionFactoryWrapper(transactionManager, narayanaRecoveryManagerBean, + narayanaProperties); } } 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 38bcaa387fc..fef518b82b2 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 @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 ed84cc2ecea..6797cde6747 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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; @@ -70,11 +69,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); } } @@ -103,8 +100,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); } @@ -121,8 +117,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; } @@ -142,11 +137,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 4d4068beb6c..7bcdf1fc905 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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.gzipped = gzipped; } - 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)); return control; } @@ -487,8 +482,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 75abb2f7c01..0772d261c1a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -379,8 +379,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 e47f4521b39..c30bd55d7df 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 RestTemplateAutoConfiguration { private final ObjectProvider> restTemplateCustomizers; - public RestTemplateAutoConfiguration( - ObjectProvider messageConverters, + public RestTemplateAutoConfiguration(ObjectProvider messageConverters, ObjectProvider> restTemplateCustomizers) { this.messageConverters = messageConverters; this.restTemplateCustomizers = restTemplateCustomizers; @@ -65,8 +64,7 @@ public class RestTemplateAutoConfiguration { if (converters != null) { builder = builder.messageConverters(converters.getConverters()); } - List customizers = this.restTemplateCustomizers - .getIfAvailable(); + List customizers = this.restTemplateCustomizers.getIfAvailable(); if (!CollectionUtils.isEmpty(customizers)) { customizers = new ArrayList<>(customizers); AnnotationAwareOrderComparator.sort(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 eb90c0aa927..242f8e2899a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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); } @@ -68,8 +68,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); } @@ -83,8 +83,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); } 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 72179b7a2a7..2b10497752c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ import org.springframework.core.env.Environment; * @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; } @@ -66,24 +65,17 @@ public class JettyWebServerFactoryCustomizer implements public void customize(ConfigurableJettyWebServerFactory factory) { ServerProperties properties = this.serverProperties; ServerProperties.Jetty jettyProperties = properties.getJetty(); - factory.setUseForwardHeaders( - getOrDeduceUseForwardHeaders(properties, this.environment)); + factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders(properties, this.environment)); PropertyMapper propertyMapper = PropertyMapper.get(); - propertyMapper.from(jettyProperties::getAcceptors).whenNonNull() - .to(factory::setAcceptors); - propertyMapper.from(jettyProperties::getSelectors).whenNonNull() - .to(factory::setSelectors); + propertyMapper.from(jettyProperties::getAcceptors).whenNonNull().to(factory::setAcceptors); + propertyMapper.from(jettyProperties::getSelectors).whenNonNull().to(factory::setSelectors); propertyMapper.from(properties::getMaxHttpHeaderSize).when(this::isPositive) - .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, - maxHttpHeaderSize)); + .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize)); propertyMapper.from(jettyProperties::getMaxHttpPostSize).when(this::isPositive) - .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, - maxHttpPostSize)); + .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)); } @@ -91,8 +83,7 @@ public class JettyWebServerFactoryCustomizer implements return value > 0; } - private boolean getOrDeduceUseForwardHeaders(ServerProperties serverProperties, - Environment environment) { + private boolean getOrDeduceUseForwardHeaders(ServerProperties serverProperties, Environment environment) { if (serverProperties.isUseForwardHeaders() != null) { return serverProperties.isUseForwardHeaders(); } @@ -100,31 +91,25 @@ public class JettyWebServerFactoryCustomizer implements return platform != null && platform.isUsingForwardHeaders(); } - 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 customizeMaxHttpHeaderSize(ConfigurableJettyWebServerFactory factory, - int maxHttpHeaderSize) { + private void customizeMaxHttpHeaderSize(ConfigurableJettyWebServerFactory factory, int maxHttpHeaderSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override public void customize(Server server) { - for (org.eclipse.jetty.server.Connector connector : server - .getConnectors()) { - for (ConnectionFactory connectionFactory : connector - .getConnectionFactories()) { + for (org.eclipse.jetty.server.Connector connector : server.getConnectors()) { + for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { - customize( - (HttpConfiguration.ConnectionFactory) connectionFactory); + customize((HttpConfiguration.ConnectionFactory) connectionFactory); } } } @@ -139,8 +124,7 @@ public class JettyWebServerFactoryCustomizer implements }); } - private void customizeMaxHttpPostSize(ConfigurableJettyWebServerFactory factory, - int maxHttpPostSize) { + private void customizeMaxHttpPostSize(ConfigurableJettyWebServerFactory factory, int maxHttpPostSize) { factory.addServerCustomizers(new JettyServerCustomizer() { @Override @@ -148,19 +132,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()); } } } 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 15e6c856e97..d56238b85f5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ import org.springframework.util.StringUtils; * @author Phillip Webb * @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; } @@ -71,32 +70,23 @@ 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(() -> determineMaxHttpHeaderSize()).when(this::isPositive) - .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, - maxHttpHeaderSize)); - propertyMapper.from(tomcatProperties::getMaxHttpPostSize) - .when((maxHttpPostSize) -> maxHttpPostSize != 0) - .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, - maxHttpPostSize)); - propertyMapper.from(tomcatProperties::getAccesslog) - .when(ServerProperties.Tomcat.Accesslog::isEnabled) + .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize)); + propertyMapper.from(tomcatProperties::getMaxHttpPostSize).when((maxHttpPostSize) -> maxHttpPostSize != 0) + .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) @@ -110,13 +100,11 @@ public class TomcatWebServerFactoryCustomizer implements } private int determineMaxHttpHeaderSize() { - return (this.serverProperties.getMaxHttpHeaderSize() > 0) - ? this.serverProperties.getMaxHttpHeaderSize() + return (this.serverProperties.getMaxHttpHeaderSize() > 0) ? this.serverProperties.getMaxHttpHeaderSize() : this.serverProperties.getTomcat().getMaxHttpHeaderSize(); } - 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) { @@ -126,8 +114,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) { @@ -137,8 +124,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) { @@ -156,8 +142,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); } @@ -165,8 +150,7 @@ 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); } @@ -181,8 +165,7 @@ public class TomcatWebServerFactoryCustomizer implements } @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) { @@ -193,8 +176,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) { @@ -205,8 +187,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) { @@ -216,10 +197,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) { @@ -231,16 +210,14 @@ public class TomcatWebServerFactoryCustomizer implements valve.setSuffix(tomcatProperties.getAccesslog().getSuffix()); valve.setRenameOnRotate(tomcatProperties.getAccesslog().isRenameOnRotate()); valve.setFileDateFormat(tomcatProperties.getAccesslog().getFileDateFormat()); - valve.setRequestAttributesEnabled( - tomcatProperties.getAccesslog().isRequestAttributesEnabled()); + valve.setRequestAttributesEnabled(tomcatProperties.getAccesslog().isRequestAttributesEnabled()); valve.setRotatable(tomcatProperties.getAccesslog().isRotate()); valve.setBuffered(tomcatProperties.getAccesslog().isBuffered()); factory.addEngineValves(valve); } private void customizeStaticResources(ConfigurableTomcatWebServerFactory factory) { - ServerProperties.Tomcat.Resource resource = this.serverProperties.getTomcat() - .getResource(); + ServerProperties.Tomcat.Resource resource = this.serverProperties.getTomcat().getResource(); if (resource.getCacheTtl() == null) { return; } @@ -254,8 +231,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 07211da87dd..b4982b7d2ae 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ import org.springframework.core.env.Environment; * @author Phillip Webb * @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; } @@ -60,62 +59,46 @@ 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).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(() -> 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(() -> getOrDeduceUseForwardHeaders()).to(factory::setUseForwardHeaders); propertyMapper.from(properties::getMaxHttpHeaderSize).when(this::isPositive) - .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, - maxHttpHeaderSize)); + .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory, maxHttpHeaderSize)); propertyMapper.from(undertowProperties::getMaxHttpPostSize).when(this::isPositive) - .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, - maxHttpPostSize)); + .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory, maxHttpPostSize)); propertyMapper.from(properties::getConnectionTimeout) - .to((connectionTimeout) -> customizeConnectionTimeout(factory, - connectionTimeout)); - factory.addDeploymentInfoCustomizers((deploymentInfo) -> deploymentInfo - .setEagerFilterInit(undertowProperties.isEagerFilterInit())); + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); + factory.addDeploymentInfoCustomizers( + (deploymentInfo) -> deploymentInfo.setEagerFilterInit(undertowProperties.isEagerFilterInit())); } private boolean isPositive(Number value) { return value.longValue() > 0; } - private void customizeConnectionTimeout(ConfigurableUndertowWebServerFactory factory, - Duration connectionTimeout) { - factory.addBuilderCustomizers((builder) -> builder.setSocketOption( - UndertowOptions.NO_REQUEST_TIMEOUT, (int) connectionTimeout.toMillis())); + private void customizeConnectionTimeout(ConfigurableUndertowWebServerFactory factory, Duration connectionTimeout) { + factory.addBuilderCustomizers((builder) -> builder.setSocketOption(UndertowOptions.NO_REQUEST_TIMEOUT, + (int) connectionTimeout.toMillis())); } - private void customizeMaxHttpHeaderSize(ConfigurableUndertowWebServerFactory factory, - int maxHttpHeaderSize) { - factory.addBuilderCustomizers((builder) -> builder - .setServerOption(UndertowOptions.MAX_HEADER_SIZE, maxHttpHeaderSize)); + private void customizeMaxHttpHeaderSize(ConfigurableUndertowWebServerFactory factory, int maxHttpHeaderSize) { + factory.addBuilderCustomizers( + (builder) -> builder.setServerOption(UndertowOptions.MAX_HEADER_SIZE, maxHttpHeaderSize)); } - private void customizeMaxHttpPostSize(ConfigurableUndertowWebServerFactory factory, - long maxHttpPostSize) { - factory.addBuilderCustomizers((builder) -> builder - .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize)); + private void customizeMaxHttpPostSize(ConfigurableUndertowWebServerFactory factory, long maxHttpPostSize) { + factory.addBuilderCustomizers( + (builder) -> builder.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize)); } private boolean getOrDeduceUseForwardHeaders() { 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 8a7da88d8a0..0ed8a9498f8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 cd4a8f017ae..be09f86d518 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 709f3307daa..7d5617bfca4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.ObjectUtils; public class ReactiveWebServerFactoryAutoConfiguration { @Bean - public ReactiveWebServerFactoryCustomizer reactiveWebServerFactoryCustomizer( - ServerProperties serverProperties) { + public ReactiveWebServerFactoryCustomizer reactiveWebServerFactoryCustomizer(ServerProperties serverProperties) { return new ReactiveWebServerFactoryCustomizer(serverProperties); } @@ -66,8 +65,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; @@ -84,15 +82,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/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/WebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java index d25e4223637..4f5933622e3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ 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 { @@ -121,9 +121,8 @@ public class WebFluxAutoConfiguration { private final List 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) { @@ -132,8 +131,7 @@ public class WebFluxAutoConfiguration { this.beanFactory = beanFactory; this.argumentResolvers = resolvers.getIfAvailable(); this.codecCustomizers = codecCustomizers.getIfAvailable(); - this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer - .getIfAvailable(); + this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizer.getIfAvailable(); this.viewResolvers = viewResolvers.getIfAvailable(); } @@ -147,8 +145,7 @@ public class WebFluxAutoConfiguration { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { if (this.codecCustomizers != null) { - this.codecCustomizers - .forEach((customizer) -> customizer.customize(configurer)); + this.codecCustomizers.forEach((customizer) -> customizer.customize(configurer)); } } @@ -160,23 +157,19 @@ public class WebFluxAutoConfiguration { } Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { - ResourceHandlerRegistration registration = registry - .addResourceHandler("/webjars/**") + ResourceHandlerRegistration registration = registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); if (cachePeriod != null) { - registration.setCacheControl(CacheControl - .maxAge(cachePeriod.toMillis(), TimeUnit.MILLISECONDS)); + registration.setCacheControl(CacheControl.maxAge(cachePeriod.toMillis(), TimeUnit.MILLISECONDS)); } 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()); if (cachePeriod != null) { - registration.setCacheControl(CacheControl - .maxAge(cachePeriod.toMillis(), TimeUnit.MILLISECONDS)); + registration.setCacheControl(CacheControl.maxAge(cachePeriod.toMillis(), TimeUnit.MILLISECONDS)); } customizeResourceHandlerRegistration(registration); } @@ -207,8 +200,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); } @@ -221,8 +213,7 @@ public class WebFluxAutoConfiguration { * Configuration equivalent to {@code @EnableWebFlux}. */ @Configuration - public static class EnableWebFluxConfiguration - extends DelegatingWebFluxConfiguration { + public static class EnableWebFluxConfiguration extends DelegatingWebFluxConfiguration { private final WebFluxProperties webFluxProperties; @@ -233,8 +224,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; } @@ -242,8 +232,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()); @@ -277,12 +266,10 @@ public class WebFluxAutoConfiguration { @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 (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) { chain.addResolver(getVersionResourceResolver(strategy)); @@ -295,8 +282,7 @@ public class WebFluxAutoConfiguration { } } - 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/error/AbstractErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java index 405bbb59a7a..8c3e7220ff2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.web.util.HtmlUtils; * @since 2.0.0 * @see ErrorAttributes */ -public abstract class AbstractErrorWebExceptionHandler - implements ErrorWebExceptionHandler, InitializingBean { +public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExceptionHandler, InitializingBean { private final ApplicationContext applicationContext; @@ -66,8 +65,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"); @@ -75,8 +73,7 @@ public abstract class AbstractErrorWebExceptionHandler this.errorAttributes = errorAttributes; this.resourceProperties = resourceProperties; this.applicationContext = applicationContext; - this.templateAvailabilityProviders = new TemplateAvailabilityProviders( - applicationContext); + this.templateAvailabilityProviders = new TemplateAvailabilityProviders(applicationContext); } /** @@ -112,8 +109,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); } @@ -145,8 +141,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); } @@ -158,8 +154,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) { @@ -186,17 +181,16 @@ 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(); Object message = error.get("message"); Date timestamp = (Date) error.get("timestamp"); - builder.append("

    Whitelabel Error Page

    ").append( - "

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

    ") + 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("
    There was an unexpected error (type=") - .append(htmlEscape(error.get("error"))).append(", status=") - .append(htmlEscape(error.get("status"))).append(").
    "); + .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("
    "); } @@ -226,8 +220,7 @@ 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) { @@ -236,17 +229,13 @@ public abstract class AbstractErrorWebExceptionHandler } this.errorAttributes.storeErrorInformation(throwable, exchange); ServerRequest request = ServerRequest.create(exchange, this.messageReaders); - return getRoutingFunction(this.errorAttributes).route(request) - .switchIfEmpty(Mono.error(throwable)) - .flatMap((handler) -> handler.handle(request)) - .flatMap((response) -> write(exchange, response)); + return getRoutingFunction(this.errorAttributes).route(request).switchIfEmpty(Mono.error(throwable)) + .flatMap((handler) -> handler.handle(request)).flatMap((response) -> write(exchange, response)); } - 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 2160025d7bf..993caa8246e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa private static final Map SERIES_VIEWS; - private static final Log logger = LogFactory - .getLog(DefaultErrorWebExceptionHandler.class); + private static final Log logger = LogFactory.getLog(DefaultErrorWebExceptionHandler.class); static { Map views = new EnumMap<>(HttpStatus.Series.class); @@ -98,18 +97,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); } /** @@ -121,15 +117,13 @@ 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(MediaType.TEXT_HTML); + ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus).contentType(MediaType.TEXT_HTML); return Flux - .just("error/" + errorStatus.toString(), - "error/" + SERIES_VIEWS.get(errorStatus.series()), "error/error") + .just("error/" + errorStatus.toString(), "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().doOnNext((response) -> logError(request, errorStatus)); } @@ -142,10 +136,8 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa boolean includeStackTrace = isIncludeStackTrace(request, MediaType.ALL); Map error = getErrorAttributes(request, includeStackTrace); HttpStatus errorStatus = getHttpStatus(error); - return ServerResponse.status(getHttpStatus(error)) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .body(BodyInserters.fromObject(error)) - .doOnNext((resp) -> logError(request, errorStatus)); + return ServerResponse.status(getHttpStatus(error)).contentType(MediaType.APPLICATION_JSON_UTF8) + .body(BodyInserters.fromObject(error)).doOnNext((resp) -> logError(request, errorStatus)); } /** @@ -155,8 +147,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; } @@ -189,8 +180,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; @@ -209,8 +199,7 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa log(request, ex, (errorStatus.is5xxServerError() ? logger::error : logger::warn)); } - private void log(ServerRequest request, Throwable ex, - BiConsumer logger) { + private void log(ServerRequest request, Throwable ex, BiConsumer logger) { if (ex instanceof ResponseStatusException) { logger.accept(buildMessage(request, ex), null); } 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 2b4b72d9b28..677d841adfd 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 @@ -65,28 +65,22 @@ public class ErrorWebFluxAutoConfiguration { private final ServerCodecConfigurer serverCodecConfigurer; - public ErrorWebFluxAutoConfiguration(ServerProperties serverProperties, - ResourceProperties resourceProperties, - ObjectProvider> viewResolversProvider, - ServerCodecConfigurer serverCodecConfigurer, + public ErrorWebFluxAutoConfiguration(ServerProperties serverProperties, ResourceProperties resourceProperties, + ObjectProvider> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) { this.serverProperties = serverProperties; this.applicationContext = applicationContext; this.resourceProperties = resourceProperties; - this.viewResolvers = viewResolversProvider - .getIfAvailable(() -> Collections.emptyList()); + this.viewResolvers = viewResolversProvider.getIfAvailable(() -> Collections.emptyList()); this.serverCodecConfigurer = serverCodecConfigurer; } @Bean - @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, - search = SearchStrategy.CURRENT) + @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT) @Order(-1) - public ErrorWebExceptionHandler errorWebExceptionHandler( - ErrorAttributes errorAttributes) { - DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler( - errorAttributes, this.resourceProperties, - this.serverProperties.getError(), this.applicationContext); + public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) { + DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler(errorAttributes, + this.resourceProperties, this.serverProperties.getError(), this.applicationContext); exceptionHandler.setViewResolvers(this.viewResolvers); exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters()); exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders()); @@ -94,11 +88,9 @@ public class ErrorWebFluxAutoConfiguration { } @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/WebClientAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientAutoConfiguration.java index c22a41dd720..becdc282c83 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +54,13 @@ public class WebClientAutoConfiguration { private final WebClient.Builder webClientBuilder; - public WebClientAutoConfiguration( - ObjectProvider> customizerProvider) { + public WebClientAutoConfiguration(ObjectProvider> customizerProvider) { this.webClientBuilder = WebClient.builder(); List customizers = customizerProvider.getIfAvailable(); if (!CollectionUtils.isEmpty(customizers)) { customizers = new ArrayList<>(customizers); AnnotationAwareOrderComparator.sort(customizers); - customizers - .forEach((customizer) -> customizer.customize(this.webClientBuilder)); + customizers.forEach((customizer) -> customizer.customize(this.webClientBuilder)); } } @@ -80,8 +78,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/DispatcherServletAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java index 155c23de712..9b0414367f2 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 @@ -95,12 +95,10 @@ public class DispatcherServletAutoConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) public DispatcherServlet dispatcherServlet() { DispatcherServlet dispatcherServlet = new 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()); return dispatcherServlet; } @@ -127,24 +125,20 @@ public class DispatcherServletAutoConfiguration { private final MultipartConfigElement multipartConfig; - public DispatcherServletRegistrationConfiguration( - ServerProperties serverProperties, WebMvcProperties webMvcProperties, - ObjectProvider multipartConfigProvider) { + public DispatcherServletRegistrationConfiguration(ServerProperties serverProperties, + WebMvcProperties webMvcProperties, ObjectProvider multipartConfigProvider) { this.serverProperties = serverProperties; this.webMvcProperties = webMvcProperties; this.multipartConfig = multipartConfigProvider.getIfAvailable(); } @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) - @ConditionalOnBean(value = DispatcherServlet.class, - name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) - public DispatcherServletRegistrationBean dispatcherServletRegistration( - DispatcherServlet dispatcherServlet) { - DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean( - dispatcherServlet, this.serverProperties.getServlet().getPath()); + @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) + public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) { + DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, + this.serverProperties.getServlet().getPath()); registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME); - registration.setLoadOnStartup( - this.webMvcProperties.getServlet().getLoadOnStartup()); + registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup()); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } @@ -157,28 +151,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)); } @@ -186,12 +175,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()) { @@ -200,50 +187,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 88ea54c759e..2bd090abf0a 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(HttpEncodingProperties.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 HttpEncodingProperties 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 HttpEncodingProperties 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 6f902243680..8a0889edd1e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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()) { @@ -48,10 +48,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 3692bf63b21..042c92e7a68 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 -@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 cf8e5099665..0cf92107dfe 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.ObjectUtils; public class ServletWebServerFactoryAutoConfiguration { @Bean - public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer( - ServerProperties serverProperties) { + public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties) { return new ServletWebServerFactoryCustomizer(serverProperties); } @@ -78,8 +77,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; @@ -96,18 +94,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 8479df7023f..5657d6c6062 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 @@ -53,8 +53,7 @@ class ServletWebServerFactoryConfiguration { @Configuration @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 @@ -68,10 +67,8 @@ class ServletWebServerFactoryConfiguration { * Nested configuration if Jetty is being used. */ @Configuration - @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 @@ -86,8 +83,7 @@ class ServletWebServerFactoryConfiguration { */ @Configuration @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 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 236fbb477e7..4b580ff3738 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,29 +49,23 @@ 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()); } } - 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 44fa77d1c71..bcc0bb2c98b 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 @@ -139,8 +139,7 @@ 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, - ValidationAutoConfiguration.class }) +@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration { public static final String DEFAULT_PREFIX = ""; @@ -157,8 +156,7 @@ public class WebMvcAutoConfiguration { @Bean @ConditionalOnMissingBean(HttpPutFormContentFilter.class) - @ConditionalOnProperty(prefix = "spring.mvc.formcontent.putfilter", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.mvc.formcontent.putfilter", name = "enabled", matchIfMissing = true) public OrderedHttpPutFormContentFilter httpPutFormContentFilter() { return new OrderedHttpPutFormContentFilter(); } @@ -169,8 +167,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); @@ -186,16 +183,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 @@ -205,8 +200,8 @@ 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 @@ -219,23 +214,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); } @@ -259,12 +251,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); @@ -275,8 +265,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(); @@ -288,8 +277,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; @@ -319,23 +307,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)); } } @@ -344,28 +326,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) { @@ -381,23 +356,20 @@ 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 }) public static RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } @Configuration - @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; @@ -417,8 +389,7 @@ public class WebMvcAutoConfiguration { public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); - mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", - faviconRequestHandler())); + mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler())); return mapping; } @@ -430,11 +401,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); } @@ -455,10 +424,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; @@ -468,15 +435,14 @@ public class WebMvcAutoConfiguration { @Override public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(); - adapter.setIgnoreDefaultModelOnRedirect(this.mvcProperties == null - || this.mvcProperties.isIgnoreDefaultModelOnRedirect()); + 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(); @@ -493,8 +459,7 @@ public class WebMvcAutoConfiguration { @Bean @Override public FormattingConversionService mvcConversionService() { - WebConversionService conversionService = new WebConversionService( - this.mvcProperties.getDateFormat()); + WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat()); addFormatters(conversionService); return conversionService; } @@ -502,8 +467,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()); @@ -511,8 +475,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(); @@ -530,16 +493,14 @@ public class WebMvcAutoConfiguration { @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 configureHandlerExceptionResolvers( - List exceptionResolvers) { + protected void configureHandlerExceptionResolvers(List exceptionResolvers) { super.configureHandlerExceptionResolvers(exceptionResolvers); if (exceptionResolvers.isEmpty()) { addDefaultHandlerExceptionResolvers(exceptionResolvers); @@ -547,8 +508,7 @@ public class WebMvcAutoConfiguration { if (this.mvcProperties.isLogResolvedException()) { for (HandlerExceptionResolver resolver : exceptionResolvers) { if (resolver instanceof AbstractHandlerExceptionResolver) { - ((AbstractHandlerExceptionResolver) resolver) - .setWarnLogCategory(resolver.getClass().getName()); + ((AbstractHandlerExceptionResolver) resolver).setWarnLogCategory(resolver.getClass().getName()); } } } @@ -563,8 +523,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; @@ -598,12 +557,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 (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) { chain.addResolver(getVersionResourceResolver(strategy)); @@ -616,8 +573,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(); @@ -637,24 +593,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 7c43a96b6fb..5156c26b832 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. @@ -106,8 +106,7 @@ public class WebMvcProperties { return this.messageCodesResolverFormat; } - public void setMessageCodesResolverFormat( - DefaultMessageCodesResolver.Format messageCodesResolverFormat) { + public void setMessageCodesResolverFormat(DefaultMessageCodesResolver.Format messageCodesResolverFormat) { this.messageCodesResolverFormat = messageCodesResolverFormat; } @@ -147,8 +146,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 c0831151506..89706b5bbe7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 45f6b2cda0e..8c2ac790857 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); } @@ -71,8 +70,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; @@ -84,11 +83,10 @@ public class BasicErrorController extends AbstractErrorController { } @RequestMapping(produces = "text/html") - 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); @@ -97,8 +95,7 @@ public class BasicErrorController extends AbstractErrorController { @RequestMapping @ResponseBody 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); } @@ -109,8 +106,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 0ba9b75d36f..a5632c9dda4 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), 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 8921472ed3c..30c5627bf86 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 @@ -99,8 +99,7 @@ public class ErrorMvcAutoConfiguration { private final List errorViewResolvers; - public ErrorMvcAutoConfiguration(ServerProperties serverProperties, - DispatcherServletPath dispatcherServletPath, + public ErrorMvcAutoConfiguration(ServerProperties serverProperties, DispatcherServletPath dispatcherServletPath, ObjectProvider> errorViewResolversProvider) { this.serverProperties = serverProperties; this.dispatcherServletPath = dispatcherServletPath; @@ -108,19 +107,15 @@ 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) { - return new BasicErrorController(errorAttributes, this.serverProperties.getError(), - this.errorViewResolvers); + return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers); } @Bean @@ -150,24 +145,21 @@ 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 - @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 { - private final SpelView defaultErrorView = new SpelView( - "

    Whitelabel Error Page

    " - + "

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

    " - + "
    ${timestamp}
    " - + "
    There was an unexpected error (type=${error}, status=${status}).
    " - + "
    ${message}
    "); + private final SpelView defaultErrorView = new SpelView("

    Whitelabel Error Page

    " + + "

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

    " + + "
    ${timestamp}
    " + + "
    There was an unexpected error (type=${error}, status=${status}).
    " + + "
    ${message}
    "); @Bean(name = "error") @ConditionalOnMissingBean(name = "error") @@ -193,21 +185,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()); } } @@ -236,8 +222,8 @@ public class ErrorMvcAutoConfiguration { } @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); @@ -246,8 +232,7 @@ public class ErrorMvcAutoConfiguration { if (response.getContentType() == null) { response.setContentType(getContentType()); } - PlaceholderResolver resolver = new ExpressionResolver(getExpressions(), - model); + PlaceholderResolver resolver = new ExpressionResolver(getExpressions(), model); String result = this.helper.replacePlaceholders(this.template, resolver); response.getWriter().append(result); } @@ -312,15 +297,13 @@ public class ErrorMvcAutoConfiguration { } private EvaluationContext getContext(Map map) { - return SimpleEvaluationContext.forPropertyAccessors(new MapAccessor()) - .withRootObject(map).build(); + return SimpleEvaluationContext.forPropertyAccessors(new MapAccessor()).withRootObject(map).build(); } @Override public String resolvePlaceholder(String placeholderName) { Expression expression = this.expressions.get(placeholderName); - Object expressionValue = (expression != null) - ? expression.getValue(this.context) : null; + Object expressionValue = (expression != null) ? expression.getValue(this.context) : null; return escape(expressionValue); } @@ -339,16 +322,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); } @@ -363,18 +345,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/web/servlet/error/NonRecursivePropertyPlaceholderHelper.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/NonRecursivePropertyPlaceholderHelper.java index d4ade0a3934..f4b892225f0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/NonRecursivePropertyPlaceholderHelper.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/NonRecursivePropertyPlaceholderHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +27,14 @@ import org.springframework.util.PropertyPlaceholderHelper; */ class NonRecursivePropertyPlaceholderHelper extends PropertyPlaceholderHelper { - NonRecursivePropertyPlaceholderHelper(String placeholderPrefix, - String placeholderSuffix) { + NonRecursivePropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) { super(placeholderPrefix, placeholderSuffix); } @Override - protected String parseStringValue(String strVal, - PlaceholderResolver placeholderResolver, Set visitedPlaceholders) { - return super.parseStringValue(strVal, - new NonRecursivePlaceholderResolver(placeholderResolver), + protected String parseStringValue(String strVal, PlaceholderResolver placeholderResolver, + Set visitedPlaceholders) { + return super.parseStringValue(strVal, new NonRecursivePlaceholderResolver(placeholderResolver), visitedPlaceholders); } 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 78ff8793628..730a452283a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class WebServicesAutoConfiguration { servlet.setApplicationContext(applicationContext); String path = this.properties.getPath(); String urlMapping = path.endsWith("/") ? path + "*" : path + "/*"; - ServletRegistrationBean registration = new ServletRegistrationBean<>( - servlet, urlMapping); + ServletRegistrationBean registration = new ServletRegistrationBean<>(servlet, + urlMapping); WebServicesProperties.Servlet servletProperties = this.properties.getServlet(); registration.setLoadOnStartup(servletProperties.getLoadOnStartup()); servletProperties.getInit().forEach(registration::addInitParameter); @@ -109,42 +109,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, - registry); + registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, registry); registerBeans(wsdlLocation, "*.xsd", SimpleXsdSchema.class, 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, - BeanDefinitionRegistry registry) { + private void registerBeans(String location, String pattern, Class type, BeanDefinitionRegistry registry) { for (Resource resource : getResources(location, pattern)) { RootBeanDefinition beanDefinition = new RootBeanDefinition(type); ConstructorArgumentValues constructorArguments = new ConstructorArgumentValues(); constructorArguments.addIndexedArgumentValue(0, resource); beanDefinition.setConstructorArgumentValues(constructorArguments); - registry.registerBeanDefinition( - StringUtils.stripFilenameExtension(resource.getFilename()), + 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/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/reactive/WebSocketReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/WebSocketReactiveAutoConfiguration.java index 5b153f7811c..8b0a1962d72 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/WebSocketReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/WebSocketReactiveAutoConfiguration.java @@ -47,8 +47,7 @@ import org.springframework.context.annotation.Configuration; public class WebSocketReactiveAutoConfiguration { @Configuration - @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci", - value = Tomcat.class) + @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci", value = Tomcat.class) static class TomcatWebSocketConfiguration { @Bean 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 98125191011..a2d4c36ca53 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +51,9 @@ import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerCo public class WebSocketMessagingAutoConfiguration { @Configuration - @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/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfiguration.java index d4041f6426c..0153810a8af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfiguration.java @@ -58,8 +58,7 @@ import org.springframework.context.annotation.Configuration; public class WebSocketServletAutoConfiguration { @Configuration - @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci", - value = Tomcat.class) + @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci", value = Tomcat.class) static class TomcatWebSocketConfiguration { @Bean 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 f8f3375142d..ef01e38c807 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 @@ -72,8 +72,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 1f9b8b52b04..4029e8a004b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 bfea26a1e34..05db2faaece 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 @@ -75,15 +75,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()); @@ -99,8 +98,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()); @@ -108,8 +106,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()); @@ -117,8 +114,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()) @@ -128,46 +124,38 @@ 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()); } @@ -186,8 +174,7 @@ public class AutoConfigurationImportSelectorTests { @Test public void nonAutoConfigurationPropertyExclusionsWhenPresentOnClassPathShouldThrowException() { this.environment.setProperty("spring.autoconfigure.exclude", - "org.springframework.boot.autoconfigure." - + "AutoConfigurationImportSelectorTests.TestConfiguration"); + "org.springframework.boot.autoconfigure." + "AutoConfigurationImportSelectorTests.TestConfiguration"); this.expected.expect(IllegalStateException.class); selectImports(BasicEnableAutoConfiguration.class); } @@ -197,10 +184,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 @@ -210,14 +196,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); @@ -228,12 +212,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; @@ -253,8 +235,7 @@ public class AutoConfigurationImportSelectorTests { } - private static class TestAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, BeanFactoryAware { + private static class TestAutoConfigurationImportFilter implements AutoConfigurationImportFilter, BeanFactoryAware { private final Set nonMatching = new HashSet<>(); @@ -267,8 +248,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]); @@ -307,8 +287,7 @@ public class AutoConfigurationImportSelectorTests { } - @EnableAutoConfiguration( - excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") + @EnableAutoConfiguration(excludeName = "org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration") private class EnableAutoConfigurationWithClassNameExclusions { } @@ -330,14 +309,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 1119feac243..ce261b4c663 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 580714f915e..f088fbbdfc7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,26 +45,23 @@ 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); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfig.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to retrieve @EnableAutoConfiguration base packages"); + this.thrown.expectMessage("Unable to retrieve @EnableAutoConfiguration base packages"); AutoConfigurationPackages.get(context.getBeanFactory()); } @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 17bd5c305bc..2b7db69b56b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 772b405318b..8e98cdf5b51 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 @@ -79,19 +79,16 @@ public class AutoConfigurationSorterTests { private AutoConfigurationSorter sorter; - private AutoConfigurationMetadata autoConfigurationMetadata = mock( - AutoConfigurationMetadata.class); + private AutoConfigurationMetadata autoConfigurationMetadata = mock(AutoConfigurationMetadata.class); @Before 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); } @@ -115,22 +112,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); } @@ -142,8 +136,7 @@ public class AutoConfigurationSorterTests { @Test public void byAutoConfigureAfterWithCycle() { - this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), - this.autoConfigurationMetadata); + this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("AutoConfigure cycle detected"); this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D)); @@ -153,10 +146,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); } @@ -164,8 +155,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); } @@ -174,33 +164,27 @@ 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); + this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("AutoConfigure cycle detected"); this.sorter.getInPriorityOrder(Arrays.asList(D, B)); } - 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())); @@ -240,14 +224,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 { } @@ -270,8 +252,7 @@ public class AutoConfigurationSorterTests { } - @AutoConfigureBefore( - name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") + @AutoConfigureBefore(name = "org.springframework.boot.autoconfigure.AutoConfigurationSorterTests$AutoConfigureB") public static class AutoConfigureW2 { } @@ -290,8 +271,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 317f8bda5f1..d052eb2278b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 4905b243381..f3e1bfbcf5e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 df489c69023..ca3342c4048 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,27 +38,24 @@ 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"); } 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<>(); @@ -90,8 +87,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/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 f3a3e6e4b3e..f393f44129c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +64,8 @@ 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() { @@ -81,17 +80,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)); @@ -108,16 +104,13 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { @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)); } @@ -125,23 +118,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); + try (ConfigurableApplicationContext parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); + ConfigurableApplicationContext child = childBuilder.run("--" + ENABLE_ADMIN_PROP)) { + BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); this.thrown.expect(NoSuchBeanDefinitionException.class); - BeanFactoryUtils.beanOfType(child.getBeanFactory(), - SpringApplicationAdminMXBeanRegistrar.class); + BeanFactoryUtils.beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); } } @@ -159,8 +145,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 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 daa3a12cd09..3ea2e103c3d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,69 +89,52 @@ 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); - DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); - 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(dfa.getPropertyValue("publisherConfirms")) - .isEqualTo(false); - assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false); - 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); + DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); + 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(dfa.getPropertyValue("publisherConfirms")).isEqualTo(false); + assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false); + 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"); @@ -165,33 +148,27 @@ public class RabbitAutoConfigurationTests { @Test public void testConnectionFactoryWithCustomConnectionNameStrategy() { - this.contextRunner - .withUserConfiguration(ConnectionNameStrategyConfiguration.class) - .run((context) -> { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); - Address[] addresses = (Address[]) dfa.getPropertyValue("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)); - dfa.setPropertyValue("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); + DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); + Address[] addresses = (Address[]) dfa.getPropertyValue("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)); + dfa.setPropertyValue("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("/"); }); } @@ -200,8 +177,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"); }); } @@ -209,10 +185,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"); }); } @@ -221,8 +195,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("/"); }); } @@ -230,11 +203,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); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(true); @@ -245,37 +216,29 @@ 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")); - DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); - assertThat(dfa.getPropertyValue("retryTemplate")).isNull(); - }); + this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class).run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); + assertThat(dfa.getPropertyValue("retryTemplate")).isNull(); + }); } @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); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); assertThat(dfa.getPropertyValue("receiveTimeout")).isEqualTo(123L); assertThat(dfa.getPropertyValue("replyTimeout")).isEqualTo(456L); - RetryTemplate retryTemplate = (RetryTemplate) dfa - .getPropertyValue("retryTemplate"); + RetryTemplate retryTemplate = (RetryTemplate) dfa.getPropertyValue("retryTemplate"); assertThat(retryTemplate).isNotNull(); dfa = new DirectFieldAccessor(retryTemplate); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa - .getPropertyValue("retryPolicy"); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa.getPropertyValue("retryPolicy"); ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa .getPropertyValue("backOffPolicy"); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); @@ -293,16 +256,14 @@ 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 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(); }); @@ -310,10 +271,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(); }); @@ -321,16 +280,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 @@ -338,40 +294,31 @@ 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); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); assertThat(dfa.getPropertyValue("channelCacheSize")).isEqualTo(23); - assertThat(dfa.getPropertyValue("cacheMode")) - .isEqualTo(CacheMode.CONNECTION); + assertThat(dfa.getPropertyValue("cacheMode")).isEqualTo(CacheMode.CONNECTION); assertThat(dfa.getPropertyValue("connectionCacheSize")).isEqualTo(2); - assertThat(dfa.getPropertyValue("channelCheckoutTimeout")) - .isEqualTo(1000L); + assertThat(dfa.getPropertyValue("channelCheckoutTimeout")).isEqualTo(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 @@ -389,37 +336,30 @@ public class RabbitAutoConfigurationTests { @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); - DirectFieldAccessor dfa = new DirectFieldAccessor( - rabbitListenerContainerFactory); - Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain"); - assertThat(adviceChain).isNull(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration5.class).run((context) -> { + SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + rabbitListenerContainerFactory.setTxSize(10); + verify(rabbitListenerContainerFactory).setTxSize(10); + DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); + Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain"); + assertThat(adviceChain).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", @@ -435,13 +375,10 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.listener.simple.transactionSize:20") .run((context) -> { SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - SimpleRabbitListenerContainerFactory.class); - DirectFieldAccessor dfa = new DirectFieldAccessor( - rabbitListenerContainerFactory); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); assertThat(dfa.getPropertyValue("concurrentConsumers")).isEqualTo(5); - assertThat(dfa.getPropertyValue("maxConcurrentConsumers")) - .isEqualTo(10); + assertThat(dfa.getPropertyValue("maxConcurrentConsumers")).isEqualTo(10); assertThat(dfa.getPropertyValue("txSize")).isEqualTo(20); checkCommonProps(context, dfa); }); @@ -450,8 +387,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", @@ -466,10 +402,8 @@ public class RabbitAutoConfigurationTests { "spring.rabbitmq.listener.direct.idleEventInterval:5") .run((context) -> { DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", - DirectRabbitListenerContainerFactory.class); - DirectFieldAccessor dfa = new DirectFieldAccessor( - rabbitListenerContainerFactory); + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); + DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory); assertThat(dfa.getPropertyValue("consumersPerQueue")).isEqualTo(5); checkCommonProps(context, dfa); }); @@ -477,17 +411,12 @@ public class RabbitAutoConfigurationTests { @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); }); } @@ -500,10 +429,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); @@ -519,47 +446,36 @@ 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); }); } - private void checkCommonProps(AssertableApplicationContext context, - DirectFieldAccessor dfa) { + private void checkCommonProps(AssertableApplicationContext context, DirectFieldAccessor dfa) { assertThat(dfa.getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE); - assertThat(dfa.getPropertyValue("acknowledgeMode")) - .isEqualTo(AcknowledgeMode.MANUAL); + assertThat(dfa.getPropertyValue("acknowledgeMode")).isEqualTo(AcknowledgeMode.MANUAL); assertThat(dfa.getPropertyValue("prefetchCount")).isEqualTo(40); - assertThat(dfa.getPropertyValue("messageConverter")) - .isSameAs(context.getBean("myMessageConverter")); - assertThat(dfa.getPropertyValue("defaultRequeueRejected")) - .isEqualTo(Boolean.FALSE); + assertThat(dfa.getPropertyValue("messageConverter")).isSameAs(context.getBean("myMessageConverter")); + assertThat(dfa.getPropertyValue("defaultRequeueRejected")).isEqualTo(Boolean.FALSE); assertThat(dfa.getPropertyValue("idleEventInterval")).isEqualTo(5L); Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain"); assertThat(adviceChain).isNotNull(); assertThat(adviceChain.length).isEqualTo(1); dfa = new DirectFieldAccessor(adviceChain[0]); - MessageRecoverer messageRecoverer = context.getBean("myMessageRecoverer", - MessageRecoverer.class); - MethodInvocationRecoverer mir = (MethodInvocationRecoverer) dfa - .getPropertyValue("recoverer"); + MessageRecoverer messageRecoverer = context.getBean("myMessageRecoverer", MessageRecoverer.class); + MethodInvocationRecoverer mir = (MethodInvocationRecoverer) dfa.getPropertyValue("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) dfa - .getPropertyValue("retryOperations"); + RetryTemplate retryTemplate = (RetryTemplate) dfa.getPropertyValue("retryOperations"); assertThat(retryTemplate).isNotNull(); dfa = new DirectFieldAccessor(retryTemplate); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa - .getPropertyValue("retryPolicy"); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa - .getPropertyValue("backOffPolicy"); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) dfa.getPropertyValue("retryPolicy"); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa.getPropertyValue("backOffPolicy"); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); @@ -568,47 +484,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); }); } @@ -616,58 +522,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); }); } @@ -676,11 +574,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()); } @@ -690,11 +586,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); }); } @@ -702,18 +596,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"); @@ -723,18 +614,16 @@ public class RabbitAutoConfigurationTests { return (TrustManager) trustManager; } - private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory( - AssertableApplicationContext context) { - CachingConnectionFactory connectionFactory = context - .getBean(CachingConnectionFactory.class); - return (com.rabbitmq.client.ConnectionFactory) new DirectFieldAccessor( - connectionFactory).getPropertyValue("rabbitConnectionFactory"); + private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory(AssertableApplicationContext context) { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + return (com.rabbitmq.client.ConnectionFactory) new DirectFieldAccessor(connectionFactory) + .getPropertyValue("rabbitConnectionFactory"); } @SuppressWarnings("unchecked") private boolean getMandatory(RabbitTemplate rabbitTemplate) { - ValueExpression expression = (ValueExpression) new DirectFieldAccessor( - rabbitTemplate).getPropertyValue("mandatoryExpression"); + ValueExpression expression = (ValueExpression) new DirectFieldAccessor(rabbitTemplate) + .getPropertyValue("mandatoryExpression"); return expression.getValue(); } @@ -775,8 +664,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 8482d05e5e4..c9587a20ba3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,8 +102,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"); } @@ -116,8 +115,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"); } @@ -146,8 +144,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"); } @@ -160,8 +157,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"); } @@ -178,8 +174,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"); } @@ -192,8 +187,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"); } @@ -204,26 +198,22 @@ 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"); } } 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 2d6167de977..ea5ecfa68ca 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 ccd8dd828f5..5ca1358d57e 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 @@ -77,18 +77,16 @@ public class BatchAutoConfigurationTests { public ExpectedException expected = ExpectedException.none(); 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(); }); @@ -96,18 +94,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); }); @@ -115,12 +112,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(); }); } @@ -129,35 +126,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); @@ -166,16 +157,13 @@ 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); + assertThat(context.getBean(BatchProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.NEVER); this.expected.expect(BadSqlGrammarException.class); new JdbcTemplate(context.getBean(DataSource.class)) .queryForList("select * from BATCH_JOB_EXECUTION"); @@ -184,61 +172,52 @@ public class BatchAutoConfigurationTests { @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(); }); @@ -246,16 +225,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(); }); @@ -303,8 +279,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 ed76a432265..706f6919def 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 5fd4ec9c619..d0fba8a0dea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 4c76e515134..4aba7e3ae4b 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 @@ -92,33 +92,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 @@ -134,85 +129,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); }); } @@ -221,126 +200,99 @@ 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(); org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = (org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor( cacheManager).getPropertyValue("defaultCacheConfig"); - assertThat(redisCacheConfiguration.getTtl()) - .isEqualTo(java.time.Duration.ofSeconds(15)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()) - .isFalse(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("keyName")) - .isEqualTo("prefix"); + 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(); org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = (org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor( cacheManager).getPropertyValue("defaultCacheConfig"); - assertThat(redisCacheConfiguration.getTtl()) - .isEqualTo(java.time.Duration.ofSeconds(30)); - assertThat(redisCacheConfiguration.getKeyPrefixFor("")) - .isEqualTo("bar"); + 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"); org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = (org.springframework.data.redis.cache.RedisCacheConfiguration) new DirectFieldAccessor( cacheManager).getPropertyValue("defaultCacheConfig"); - assertThat(redisCacheConfiguration.getTtl()) - .isEqualTo(java.time.Duration.ofMinutes(0)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()) - .isTrue(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("test")) - .isEqualTo("test::"); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofMinutes(0)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isTrue(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("test")).isEqualTo("test::"); assertThat(redisCacheConfiguration.usePrefix()).isTrue(); }); } @@ -349,8 +301,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(); }); } @@ -359,8 +310,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")); } @@ -369,11 +319,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()); @@ -384,13 +332,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"); }); } @@ -399,20 +344,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); }); } @@ -420,10 +360,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")); }); } @@ -433,8 +371,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)); } @@ -443,15 +380,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()); }); } @@ -460,62 +394,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")); }); @@ -524,19 +445,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(); @@ -550,14 +465,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); }); } @@ -576,11 +488,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); }); } @@ -592,24 +502,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); }); @@ -618,8 +521,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); @@ -629,33 +531,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(); }); } @@ -665,12 +562,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 @@ -683,9 +578,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()); }); } @@ -693,16 +587,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(); @@ -712,42 +604,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); } @@ -755,35 +639,28 @@ 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); } @Configuration @@ -821,16 +698,14 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT } @Configuration - @Import({ GenericCacheConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ GenericCacheConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class GenericCacheAndCustomizersConfiguration { } @Configuration @EnableCaching - @Import({ HazelcastAutoConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ HazelcastAutoConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class HazelcastCacheAndCustomizersConfiguration { } @@ -850,8 +725,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT } @Configuration - @Import({ CouchbaseCacheConfiguration.class, - CacheManagerCustomizersConfiguration.class }) + @Import({ CouchbaseCacheConfiguration.class, CacheManagerCustomizersConfiguration.class }) static class CouchbaseCacheAndCustomizersConfiguration { } @@ -873,9 +747,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"); } } @@ -918,8 +791,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"); @@ -934,8 +806,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; @@ -980,8 +851,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Configuration @EnableCaching - static class CustomCacheManagerFromSupportConfiguration - extends CachingConfigurerSupport { + static class CustomCacheManagerFromSupportConfiguration extends CachingConfigurerSupport { @Override @Bean @@ -994,8 +864,7 @@ public class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationT @Configuration @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 6f50df2850c..9e3677c3070 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 ed6d892101c..b2b65cda17a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,39 +43,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"); }); } @@ -83,34 +76,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); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java index b9f2be49cc5..61de66ef116 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cloud/CloudAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 CloudAutoConfigurationTests { @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()); 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 c6235d755b9..ea2353c8a83 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 3628eb7d4a9..cbe54d12473 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 5e479f01ac2..b476c01f8c2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,32 +52,29 @@ 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); } 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 9264a9411af..877c111123a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 68e1c346d21..73b6040ea25 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a7a89e21925..c8bc51bfbca 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,43 +53,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 @@ -101,15 +97,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")); } @@ -117,16 +111,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); }); @@ -139,10 +133,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); @@ -266,8 +258,7 @@ public class ConditionalOnBeanTests { } - protected static class WithPropertyPlaceholderClassNameRegistrar - implements ImportBeanDefinitionRegistrar { + protected static class WithPropertyPlaceholderClassNameRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, 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 6b5f86c9ade..7867bacfb24 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,33 +39,28 @@ 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); } 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 532b59eeaca..c5113205de4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 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 c13724db696..3efe12dcb8d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 e7511cffcf6..04b462171a7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 65b8694cd41..866b62fe861 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +56,14 @@ public class ConditionalOnJndiTests { @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After 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 5c9f8e76d0b..8dfb14d7f51 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 @@ -80,8 +80,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testNameAndTypeOnMissingBeanCondition() { - this.context.register(FooConfiguration.class, - OnBeanNameAndTypeConfiguration.class); + this.context.register(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class); this.context.refresh(); /* * Arguably this should be true, but as things are implemented the conditions @@ -132,8 +131,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { this.context.register(FooConfiguration.class, OnAnnotationConfiguration.class, - FactoryBeanXmlConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isFalse(); assertThat(this.context.containsBean("example")).isTrue(); @@ -142,60 +140,48 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithFactoryBean() { - this.context.register(FactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithComponentScannedFactoryBean() { - this.context.register(ComponentScannedFactoryBeanBeanMethodConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(ComponentScannedFactoryBeanBeanMethodConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { - this.context.register( - ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { - this.context.register(FactoryBeanWithBeanMethodArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(FactoryBeanWithBeanMethodArgumentsConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); TestPropertyValues.of("theValue:foo").applyTo(this.context); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithConcreteFactoryBean() { - this.context.register(ConcreteFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { - this.context.register(UnhelpfulFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); // We could not tell that the FactoryBean would ultimately create an ExampleBean @@ -204,48 +190,39 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithRegisteredFactoryBean() { - this.context.register(RegisteredFactoryBeanConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { - this.context.register(NonspecificFactoryBeanClassAttributeConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(NonspecificFactoryBeanClassAttributeConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { - this.context.register(NonspecificFactoryBeanStringAttributeConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(NonspecificFactoryBeanStringAttributeConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithFactoryBeanInXml() { - this.context.register(FactoryBeanXmlConfiguration.class, - ConditionalOnFactoryBean.class, + this.context.register(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); - assertThat(this.context.getBean(ExampleBean.class).toString()) - .isEqualTo("fromFactory"); + assertThat(this.context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory"); } @Test public void testOnMissingBeanConditionWithIgnoredSubclass() { - this.context.register(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclass.class, + this.context.register(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -254,8 +231,7 @@ public class ConditionalOnMissingBeanTests { @Test public void testOnMissingBeanConditionWithIgnoredSubclassByName() { - this.context.register(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclassByName.class, + this.context.register(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -271,8 +247,7 @@ public class ConditionalOnMissingBeanTests { parent.refresh(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); child.setParent(parent); - child.register(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class); + child.register(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class); child.refresh(); assertThat(child.getBeansOfType(ExampleBean.class)).hasSize(1); child.close(); @@ -283,8 +258,7 @@ public class ConditionalOnMissingBeanTests { public void currentContextIsIgnoredWhenUsingAncestorsStrategy() { this.context.refresh(); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.register(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class); + child.register(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class); child.setParent(this.context); child.refresh(); assertThat(child.getBeansOfType(ExampleBean.class)).hasSize(2); @@ -292,8 +266,7 @@ public class ConditionalOnMissingBeanTests { @Test public void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { - this.context.register(ConcreteFactoryBeanConfiguration.class, - OnAnnotationWithFactoryBeanConfiguration.class); + this.context.register(ConcreteFactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("bar")).isFalse(); assertThat(this.context.getBeansOfType(ExampleBean.class)).hasSize(1); @@ -363,8 +336,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); } @@ -397,19 +369,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()); } } @@ -420,20 +387,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()); } } @@ -447,13 +409,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()); } } @@ -479,8 +438,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"); } 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 ecda09fddca..d4b347b0e2d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 f68139d5e9c..97ffb876f13 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 @@ -65,8 +65,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(); } @@ -78,29 +77,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(); } @@ -186,8 +181,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(); } @@ -206,16 +200,16 @@ public class ConditionalOnPropertyTests { @Test public void nameOrValueMustBeSpecified() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(hasMessage(containsString("The name or " - + "value attribute of @ConditionalOnProperty must be specified"))); + this.thrown.expectCause(hasMessage( + containsString("The name or " + "value attribute of @ConditionalOnProperty must be specified"))); load(NoNameOrValueAttribute.class, "some.property"); } @Test public void nameAndValueMustNotBeSpecified() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(hasMessage(containsString("The name and " - + "value attributes of @ConditionalOnProperty are exclusive"))); + this.thrown.expectCause(hasMessage( + containsString("The name and " + "value attributes of @ConditionalOnProperty are exclusive"))); load(NameAndValueAttribute.class, "some.property"); } @@ -251,15 +245,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 @@ -297,8 +290,7 @@ public class ConditionalOnPropertyTests { @Configuration // 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 @@ -310,8 +302,7 @@ public class ConditionalOnPropertyTests { @Configuration // 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 @@ -333,8 +324,7 @@ public class ConditionalOnPropertyTests { } @Configuration - @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", - matchIfMissing = true) + @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", matchIfMissing = true) static class DefaultValueConfig { @Bean @@ -356,8 +346,7 @@ public class ConditionalOnPropertyTests { } @Configuration - @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 @@ -413,8 +402,7 @@ public class ConditionalOnPropertyTests { @Configuration @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 @@ -426,8 +414,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 7f0e32c27b1..c43b582555b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -104,23 +103,20 @@ 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(); } @@ -128,8 +124,7 @@ public class ConditionalOnSingleCandidateTests { public void invalidAnnotationTwoTypes() { this.thrown.expect(IllegalStateException.class); this.thrown.expectCause(isA(IllegalArgumentException.class)); - this.thrown.expectMessage( - OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); + this.thrown.expectMessage(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); load(OnBeanSingleCandidateTwoTypesConfiguration.class); } @@ -137,8 +132,7 @@ public class ConditionalOnSingleCandidateTests { public void invalidAnnotationNoType() { this.thrown.expect(IllegalStateException.class); this.thrown.expectCause(isA(IllegalArgumentException.class)); - this.thrown - .expectMessage(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); + this.thrown.expectMessage(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); load(OnBeanSingleCandidateNoTypeConfiguration.class); } 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 9a543ec952f..41dec33feec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,33 +55,30 @@ public class ConditionalOnWebApplicationTests { @Test public void testWebApplicationWithServletContext() { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - 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 c98a7a2d89b..e4261a1138a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +49,10 @@ public class OnBeanConditionTypeDeductionFailureTests { fail("Context refresh was successful"); } catch (Exception 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 b1b209d21b4..0386c3b300c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +49,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); } @@ -66,10 +64,8 @@ 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() { 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 f0a31ef1001..ed6237506c3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 bce854e9157..97a68cd844b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringBootConditionTests { @Test public void sensibleClassException() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Error processing condition on " + ErrorOnClass.class.getName()); + this.thrown.expectMessage("Error processing condition on " + ErrorOnClass.class.getName()); new AnnotationConfigApplicationContext(ErrorOnClass.class); } @Test public void sensibleMethodException() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Error processing condition on " - + ErrorOnMethod.class.getName() + ".myBean"); + this.thrown.expectMessage("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); new AnnotationConfigApplicationContext(ErrorOnMethod.class); } @@ -74,8 +72,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 f1cbc14fa26..4219b446773 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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(SpringRunner.class) @SpringBootTest("spring.messages.basename:test/messages") -@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @DirtiesContext public class MessageSourceAutoConfigurationIntegrationTests { @@ -48,8 +47,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 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 9999f0215af..20d93674403 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest -@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) +@ImportAutoConfiguration({ MessageSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @ActiveProfiles("switch-messages") @DirtiesContext public class MessageSourceAutoConfigurationProfileTests { @@ -50,8 +49,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 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 b64c1eca548..164cea1d38b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,74 +46,65 @@ 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(new DirectFieldAccessor(context.getBean(MessageSource.class)) - .getPropertyValue("cacheMillis")).isEqualTo(expected); + assertThat(new DirectFieldAccessor(context.getBean(MessageSource.class)).getPropertyValue("cacheMillis")) + .isEqualTo(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"); }); } @@ -121,26 +112,20 @@ 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 @Ignore("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 public void testFallbackDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat( - isFallbackToSystemLocale(context.getBean(MessageSource.class))) - .isTrue()); + .run((context) -> assertThat(isFallbackToSystemLocale(context.getBean(MessageSource.class))).isTrue()); } @Test @@ -148,17 +133,13 @@ public class MessageSourceAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.fallback-to-system-locale:false") - .run((context) -> assertThat( - isFallbackToSystemLocale(context.getBean(MessageSource.class))) - .isFalse()); + .run((context) -> assertThat(isFallbackToSystemLocale(context.getBean(MessageSource.class))).isFalse()); } @Test public void testFormatMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat( - isAlwaysUseMessageFormat(context.getBean(MessageSource.class))) - .isFalse()); + .run((context) -> assertThat(isAlwaysUseMessageFormat(context.getBean(MessageSource.class))).isFalse()); } @Test @@ -166,27 +147,21 @@ public class MessageSourceAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.always-use-message-format:true") - .run((context) -> assertThat( - isAlwaysUseMessageFormat(context.getBean(MessageSource.class))) - .isTrue()); + .run((context) -> assertThat(isAlwaysUseMessageFormat(context.getBean(MessageSource.class))).isTrue()); } private boolean isFallbackToSystemLocale(MessageSource messageSource) { - return (boolean) new DirectFieldAccessor(messageSource) - .getPropertyValue("fallbackToSystemLocale"); + return (boolean) new DirectFieldAccessor(messageSource).getPropertyValue("fallbackToSystemLocale"); } private boolean isAlwaysUseMessageFormat(MessageSource messageSource) { - return (boolean) new DirectFieldAccessor(messageSource) - .getPropertyValue("alwaysUseMessageFormat"); + return (boolean) new DirectFieldAccessor(messageSource).getPropertyValue("alwaysUseMessageFormat"); } @Test public void testUseCodeAsDefaultMessageDefault() { - this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat( - isUseCodeAsDefaultMessage(context.getBean(MessageSource.class))) - .isFalse()); + this.contextRunner.withPropertyValues("spring.messages.basename:test/messages").run( + (context) -> assertThat(isUseCodeAsDefaultMessage(context.getBean(MessageSource.class))).isFalse()); } @Test @@ -194,30 +169,25 @@ public class MessageSourceAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.use-code-as-default-message:true") - .run((context) -> assertThat( - isUseCodeAsDefaultMessage(context.getBean(MessageSource.class))) - .isTrue()); + .run((context) -> assertThat(isUseCodeAsDefaultMessage(context.getBean(MessageSource.class))).isTrue()); } private boolean isUseCodeAsDefaultMessage(MessageSource messageSource) { - return (boolean) new DirectFieldAccessor(messageSource) - .getPropertyValue("useCodeAsDefaultMessage"); + return (boolean) new DirectFieldAccessor(messageSource).getPropertyValue("useCodeAsDefaultMessage"); } @Test public void existingMessageSourceIsPreferred() { this.contextRunner.withUserConfiguration(CustomMessageSource.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"))); } @Configuration @@ -234,20 +204,18 @@ public class MessageSourceAutoConfigurationTests { return new 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) + public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { + return code; + } + + @Override + public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { - return code; - } - - @Override - 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 10a23a2c3be..78adf67318a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -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 f4a8283767b..ecf3a32fe6e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 de01a9f8db2..e836e8e9b23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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() { @@ -58,19 +56,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); }); @@ -78,9 +74,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 @@ -92,8 +87,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"); @@ -107,8 +101,7 @@ public class CouchbaseAutoConfigurationTests { assertThat(env.queryServiceConfig().maxEndpoints()).isEqualTo(3); assertThat(env.viewServiceConfig().minEndpoints()).isEqualTo(4); assertThat(env.viewServiceConfig().maxEndpoints()).isEqualTo(4); - }, "spring.couchbase.env.endpoints.query=3", - "spring.couchbase.env.endpoints.view=4"); + }, "spring.couchbase.env.endpoints.query=3", "spring.couchbase.env.endpoints.view=4"); } @Test @@ -118,10 +111,8 @@ 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.query=33", - "spring.couchbase.env.endpoints.queryservice.min-endpoints=3", - "spring.couchbase.env.endpoints.queryservice.max-endpoints=5", - "spring.couchbase.env.endpoints.view=44", + }, "spring.couchbase.env.endpoints.query=33", "spring.couchbase.env.endpoints.queryservice.min-endpoints=3", + "spring.couchbase.env.endpoints.queryservice.max-endpoints=5", "spring.couchbase.env.endpoints.view=44", "spring.couchbase.env.endpoints.viewservice.min-endpoints=4", "spring.couchbase.env.endpoints.viewservice.max-endpoints=6"); } @@ -133,10 +124,8 @@ public class CouchbaseAutoConfigurationTests { assertThat(env.queryServiceConfig().maxEndpoints()).isEqualTo(5); assertThat(env.viewServiceConfig().minEndpoints()).isEqualTo(1); assertThat(env.viewServiceConfig().maxEndpoints()).isEqualTo(6); - }, "spring.couchbase.env.endpoints.query=33", - "spring.couchbase.env.endpoints.queryservice.max-endpoints=5", - "spring.couchbase.env.endpoints.view=44", - "spring.couchbase.env.endpoints.viewservice.max-endpoints=6"); + }, "spring.couchbase.env.endpoints.query=33", "spring.couchbase.env.endpoints.queryservice.max-endpoints=5", + "spring.couchbase.env.endpoints.view=44", "spring.couchbase.env.endpoints.viewservice.max-endpoints=6"); } @Test @@ -147,10 +136,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"); } @@ -160,8 +147,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 @@ -170,20 +156,15 @@ 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).couchbaseEnvironment(); + 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).couchbaseEnvironment(); environmentConsumer.accept(env); }); } @@ -195,8 +176,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); }); @@ -211,10 +191,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 0989f42ad5a..586d408eb14 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 79568f637d6..35a923469eb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -66,8 +65,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 @@ -79,8 +77,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 @@ -90,16 +87,14 @@ public class PersistenceExceptionTranslationAutoConfigurationTests { @Test(expected = IllegalArgumentException.class) public void persistOfNullThrowsIllegalArgumentExceptionWithoutExceptionTranslation() { - this.context = new AnnotationConfigApplicationContext( - EmbeddedDataSourceConfiguration.class, + this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, TestConfiguration.class); this.context.getBean(TestRepository.class).doSomething(); } @Test(expected = InvalidDataAccessApiUsageException.class) public void persistOfNullThrowsInvalidDataAccessApiUsageExceptionWithExceptionTranslation() { - this.context = new AnnotationConfigApplicationContext( - EmbeddedDataSourceConfiguration.class, + this.context = new AnnotationConfigApplicationContext(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, TestConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class); this.context.getBean(TestRepository.class).doSomething(); 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 b586fb93ac1..3120ce26496 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/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 b82efb60eba..bef9073451b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 CassandraDataAutoConfigurationIntegrationTests { this.context = new AnnotationConfigApplicationContext(); TestPropertyValues .of("spring.data.cassandra.port=" + cassandra.getMappedPort(), - "spring.data.cassandra.read-timeout=24000", - "spring.data.cassandra.connect-timeout=10000") + "spring.data.cassandra.read-timeout=24000", "spring.data.cassandra.connect-timeout=10000") .applyTo(this.context.getEnvironment()); } @@ -68,12 +67,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); } @@ -82,21 +79,16 @@ 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().withPort(cassandra.getMappedPort()) - .addContactPoint("localhost").build(); + Cluster cluster = Cluster.builder().withPort(cassandra.getMappedPort()).addContactPoint("localhost").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 1528c69bccf..b3a3a955ca0 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,35 +89,31 @@ 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(); } 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 - @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 { } @@ -146,8 +139,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 3a1fdbfc4ce..51fc1608cda 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 8a6365e8ded..3774faa4ddc 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 @@ -137,15 +126,13 @@ public class CassandraReactiveRepositoriesAutoConfigurationTests { @Configuration @TestAutoConfigurationPackage(CassandraReactiveRepositoriesAutoConfigurationTests.class) - @EnableReactiveCassandraRepositories( - basePackageClasses = ReactiveCityCassandraRepository.class) + @EnableReactiveCassandraRepositories(basePackageClasses = ReactiveCityCassandraRepository.class) static class CustomizedConfiguration { } @Configuration - @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 ed5ecdbc5c3..e03cbd7702a 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 @@ -137,8 +128,8 @@ public class CassandraRepositoriesAutoConfigurationTests { } @Configuration - @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 fc4907a40f9..f47b0705f98 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 4e38e1fae7a..e60e798bbdf 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 @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 f9c63f15346..b5ee4b01097 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 23b5f81c75c..e51c57ccdee 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 ff7c550648f..e35922a719f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 c4e25b1ed9c..4eb6644081a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,22 @@ 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(); new ElasticsearchNodeTemplate().doWithNode((node) -> { - TestPropertyValues.of( - "spring.data.elasticsearch.cluster-nodes:localhost:" - + node.getTcpPort(), - "spring.data.elasticsearch.properties.path.home:target/es/client") - .applyTo(this.context); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class); + TestPropertyValues.of("spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort(), + "spring.data.elasticsearch.properties.path.home:target/es/client").applyTo(this.context); + 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 3b58db23941..db733485a8f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ElasticsearchDataAutoConfigurationTests { @Test public void templateBackOffWithNoClient() { - this.context = new AnnotationConfigApplicationContext( - ElasticsearchDataAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(ElasticsearchDataAutoConfiguration.class); assertThat(this.context.getBeansOfType(ElasticsearchTemplate.class)).isEmpty(); } @@ -59,11 +58,9 @@ public class ElasticsearchDataAutoConfigurationTests { TestPropertyValues .of("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs", - "spring.data.elasticsearch.cluster-nodes:localhost:" - + node.getTcpPort()) + "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()) .applyTo(this.context); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class, + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); this.context.refresh(); assertHasSingleBean(ElasticsearchTemplate.class); @@ -77,11 +74,9 @@ public class ElasticsearchDataAutoConfigurationTests { TestPropertyValues .of("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs", - "spring.data.elasticsearch.cluster-nodes:localhost:" - + node.getTcpPort()) + "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()) .applyTo(this.context); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class, + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); this.context.refresh(); assertHasSingleBean(SimpleElasticsearchMappingContext.class); @@ -95,11 +90,9 @@ public class ElasticsearchDataAutoConfigurationTests { TestPropertyValues .of("spring.data.elasticsearch.properties.path.data:target/data", "spring.data.elasticsearch.properties.path.logs:target/logs", - "spring.data.elasticsearch.cluster-nodes:localhost:" - + node.getTcpPort()) + "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()) .applyTo(this.context); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - ElasticsearchAutoConfiguration.class, + this.context.register(PropertyPlaceholderAutoConfiguration.class, ElasticsearchAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class); this.context.refresh(); assertHasSingleBean(ElasticsearchConverter.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchNodeTemplate.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchNodeTemplate.java index 7da5529d96a..4bb5184d47f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchNodeTemplate.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchNodeTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +69,8 @@ public class ElasticsearchNodeTemplate { private static final class NettyTransportNode extends Node { private NettyTransportNode() { - super(InternalSettingsPreparer.prepareEnvironment(Settings.builder() - .put("path.home", "target/es/node").put("transport.type", "netty4") - .put("http.enabled", true).put("node.portsfile", true) + super(InternalSettingsPreparer.prepareEnvironment(Settings.builder().put("path.home", "target/es/node") + .put("transport.type", "netty4").put("http.enabled", true).put("node.portsfile", true) .put("http.port", 0).put("transport.tcp.port", 0).build(), null), Arrays.asList(Netty4Plugin.class)); new File("target/es/node/logs").mkdirs(); @@ -88,14 +87,12 @@ public class ElasticsearchNodeTemplate { } public int getTcpPort() { - return this.node.injector().getInstance(Transport.class).boundAddress() - .publishAddress().getPort(); + return this.node.injector().getInstance(Transport.class).boundAddress().publishAddress().getPort(); } public int getHttpPort() { try { - for (String line : Files - .readAllLines(Paths.get("target/es/node/logs/http.ports"))) { + for (String line : Files.readAllLines(Paths.get("target/es/node/logs/http.ports"))) { if (line.startsWith("127.0.0.1")) { return Integer.parseInt(line.substring(line.indexOf(":") + 1)); } 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 b07aca2ea87..41aa4ee315a 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 @@ -76,8 +76,7 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { new ElasticsearchNodeTemplate().doWithNode((node) -> { load(CustomizedConfiguration.class, node); - assertThat(this.context.getBean(CityElasticsearchDbRepository.class)) - .isNotNull(); + assertThat(this.context.getBean(CityElasticsearchDbRepository.class)).isNotNull(); }); } @@ -85,17 +84,14 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(); addElasticsearchProperties(this.context, node); this.context.register(config, ElasticsearchAutoConfiguration.class, - ElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class, + ElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } - private void addElasticsearchProperties(AnnotationConfigApplicationContext context, - ElasticsearchNode node) { + private void addElasticsearchProperties(AnnotationConfigApplicationContext context, ElasticsearchNode node) { TestPropertyValues.of("spring.data.elasticsearch.properties.path.home:target", - "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()) - .applyTo(context); + "spring.data.elasticsearch.cluster-nodes:localhost:" + node.getTcpPort()).applyTo(context); } @Configuration @@ -112,8 +108,7 @@ public class ElasticsearchRepositoriesAutoConfigurationTests { @Configuration @TestAutoConfigurationPackage(ElasticsearchRepositoriesAutoConfigurationTests.class) - @EnableElasticsearchRepositories( - basePackageClasses = CityElasticsearchDbRepository.class) + @EnableElasticsearchRepositories(basePackageClasses = CityElasticsearchDbRepository.class) protected static class CustomizedConfiguration { } 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/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index dc90eada20b..728d5c22ec5 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 @@ -66,9 +66,8 @@ public class JpaRepositoriesAutoConfigurationTests { @Test public void testOverrideRepositoryConfiguration() { prepareApplicationContext(CustomConfiguration.class); - assertThat(this.context.getBean( - org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class)) - .isNotNull(); + assertThat(this.context.getBean(org.springframework.boot.autoconfigure.data.alt.jpa.CityJpaRepository.class)) + .isNotNull(); assertThat(this.context.getBean(PlatformTransactionManager.class)).isNotNull(); assertThat(this.context.getBean(EntityManagerFactory.class)).isNotNull(); } @@ -83,10 +82,8 @@ public class JpaRepositoriesAutoConfigurationTests { private void prepareApplicationContext(Class... configurationClasses) { this.context = new AnnotationConfigApplicationContext(); this.context.register(configurationClasses); - this.context.register(EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(EmbeddedDataSourceConfiguration.class, HibernateJpaAutoConfiguration.class, + JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); } @@ -99,11 +96,8 @@ public class JpaRepositoriesAutoConfigurationTests { @Configuration @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 37699726281..70fa9b33cc8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +54,13 @@ public class JpaWebAutoConfigurationTests { public void testDefaultRepositoryConfiguration() { this.context = new AnnotationConfigWebApplicationContext(); 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 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/LdapDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java index 072b07cc993..8c3ce86d5db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ldap/LdapDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,9 @@ public class LdapDataAutoConfigurationTests { @Test public void templateExists() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.ldap.urls:ldap://localhost:389") - .applyTo(this.context); - this.context.register(PropertyPlaceholderAutoConfiguration.class, - LdapAutoConfiguration.class, LdapDataAutoConfiguration.class); + TestPropertyValues.of("spring.ldap.urls:ldap://localhost:389").applyTo(this.context); + this.context.register(PropertyPlaceholderAutoConfiguration.class, LdapAutoConfiguration.class, + LdapDataAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(LdapTemplate.class)).hasSize(1); } 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 21add239200..3def1f0e59b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +69,10 @@ 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, - LdapDataAutoConfiguration.class, LdapRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + this.context.register(LdapAutoConfiguration.class, LdapDataAutoConfiguration.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 afa2fa6cc2c..3897bb3f430 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 44ef2289930..4199dc906da 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +58,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 @@ -93,8 +89,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(); @@ -104,23 +99,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()) @@ -131,33 +122,27 @@ public class MongoDataAutoConfigurationTests { @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(); }); @@ -165,10 +150,8 @@ public class MongoDataAutoConfigurationTests { } @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 d2eb553fe3f..41deb5878e4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 c46f4ecd9ff..f8e2e311e68 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +35,13 @@ import static org.assertj.core.api.Assertions.assertThat; public class MongoReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - PropertyPlaceholderAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.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)); } } 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 c9c9b53341c..ad9f024f1b5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 f9813f21968..313c2655644 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 5137137afdf..d7afd023e6f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +92,9 @@ public class MixedNeo4jRepositoriesAutoConfigurationTests { private void load(Class config, String... environment) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - 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 1f38ab28e47..26546ead66d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +55,24 @@ import static org.mockito.Mockito.verify; public class Neo4jDataAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .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); - }); + 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); + }); } @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(); }); @@ -87,24 +80,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); + }); } @@ -113,12 +102,10 @@ public class Neo4jDataAutoConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 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(); @@ -128,26 +115,20 @@ 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 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)); + }); } - 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(); } @@ -174,8 +155,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 ce225091fce..fbc544ec2a0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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,8 +101,7 @@ public class Neo4jPropertiesTests { @Test public void credentialsAreSetFromUri() { - Neo4jProperties properties = load(true, - "spring.data.neo4j.uri=http://user:secret@my-server:7474"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=http://user:secret@my-server:7474"); Configuration configuration = properties.createConfiguration(); assertDriver(configuration, Neo4jProperties.HTTP_DRIVER, "http://my-server:7474"); assertCredentials(configuration, "user", "secret"); @@ -132,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:target/neo4j/my.db"); + Neo4jProperties properties = load(true, "spring.data.neo4j.uri=file:target/neo4j/my.db"); Configuration configuration = properties.createConfiguration(); - assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, - "file:target/neo4j/my.db"); + assertDriver(configuration, Neo4jProperties.EMBEDDED_DRIVER, "file:target/neo4j/my.db"); } private static void assertDriver(Configuration actual, String driver, String uri) { @@ -154,8 +141,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(); @@ -164,8 +150,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); @@ -177,8 +162,7 @@ public class Neo4jPropertiesTests { ctx.setClassLoader(new URLClassLoader(new URL[0], getClass().getClassLoader()) { @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.equals(Neo4jProperties.EMBEDDED_DRIVER)) { if (embeddedAvailable) { return TestEmbeddedDriver.class; 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 343f10b84a4..da387c95173 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); } @@ -82,11 +81,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 158d873acdf..6f86145bc4b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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,45 +93,28 @@ 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", + 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").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); @@ -151,14 +125,11 @@ public class RedisAutoConfigurationJedisTests { @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 @@ -166,38 +137,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 @@ -225,8 +187,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 f0a0ae554ef..b21fea492be 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 @@ -59,19 +59,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(); @@ -82,22 +79,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"); @@ -108,12 +101,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"); @@ -123,43 +114,34 @@ 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.shutdown-timeout:1000").run((context) -> { - LettuceConnectionFactory cf = context - .getBean(LettuceConnectionFactory.class); + 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.shutdown-timeout:1000") + .run((context) -> { + 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); @@ -170,14 +152,11 @@ public class RedisAutoConfigurationTests { @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 @@ -185,22 +164,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(); }); @@ -208,19 +181,13 @@ 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"); }); } @@ -228,12 +195,10 @@ public class RedisAutoConfigurationTests { 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), + .withPropertyValues("spring.redis.cluster.nodes[0]:" + clusterNodes.get(0), "spring.redis.cluster.nodes[1]:" + clusterNodes.get(1)) - .run((context) -> assertThat(context - .getBean(LettuceConnectionFactory.class).getClusterConnection()) - .isNotNull()); + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).getClusterConnection()) + .isNotNull()); } @Test @@ -243,17 +208,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 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 fcb81460e0c..45e27d55b60 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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() { 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 a5b89491fb8..3129629efa4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 RedisRepositoriesAutoConfigurationTests { @Before 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()); } @After @@ -61,8 +60,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(); } @@ -70,8 +68,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(); } @@ -79,8 +76,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 1b226544a01..41f305f4596 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @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 extends RepositoryRestConfigurerAdapter { @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 52b4de86162..fdce6a93e61 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +54,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 @@ -81,8 +79,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 bb24f96edbe..140b21e41bd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 cc41920bee2..4d80580c62c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,80 +55,63 @@ 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 failureAnalysisForMissingCollectionType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringCollectionConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringCollectionHandler.class, - 0, String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(StringCollectionConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringCollectionHandler.class, 0, String.class); + assertBeanMethodDisabled(analysis, "did not find property 'spring.string.enabled'", TestPropertyAutoConfiguration.class, "string"); assertActionMissingType(analysis, String.class); } @Test public void failureAnalysisForMissingMapType() { - FailureAnalysis analysis = analyzeFailure( - createFailure(StringMapConfiguration.class)); - assertDescriptionConstructorMissingType(analysis, StringMapHandler.class, 0, - String.class); - assertBeanMethodDisabled(analysis, - "did not find property 'spring.string.enabled'", + FailureAnalysis analysis = analyzeFailure(createFailure(StringMapConfiguration.class)); + assertDescriptionConstructorMissingType(analysis, StringMapHandler.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); } @@ -137,48 +120,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"); @@ -187,74 +162,65 @@ 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) new DirectFieldAccessor( - analyzer).getPropertyValue("report"); + private static void addExclusions(NoSuchBeanDefinitionFailureAnalyzer analyzer, Class... classes) { + ConditionEvaluationReport report = (ConditionEvaluationReport) new DirectFieldAccessor(analyzer) + .getPropertyValue("report"); List exclusions = new ArrayList<>(report.getExclusions()); for (Class c : classes) { exclusions.add(c.getName()); @@ -319,8 +285,7 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } @Configuration - @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 e72bd4c6d0a..43d4db1dbf3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,8 +102,7 @@ public class EntityScanPackagesTests { @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 +119,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"); } @@ -129,26 +127,21 @@ public class EntityScanPackagesTests { @Test public void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() { this.thrown.expect(AnnotationConfigurationException.class); - this.context = new AnnotationConfigApplicationContext( - EntityScanValueAndBasePackagesConfig.class); + this.context = new AnnotationConfigApplicationContext(EntityScanValueAndBasePackagesConfig.class); } @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 dcb9599181d..03c40eae5b2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -65,8 +64,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); @@ -75,16 +74,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 57bef2edeed..0948c212fbf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import static org.mockito.Mockito.mock; public class JestAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, - JestAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class, JestAutoConfiguration.class)); @Before public void preventElasticsearchFromConfiguringNetty() { @@ -74,28 +73,21 @@ public class JestAutoConfigurationTests { @Test public void jestClientOnLocalhostByDefault() { - this.contextRunner - .run((context) -> assertThat(context.getBeansOfType(JestClient.class)) - .hasSize(1)); + this.contextRunner.run((context) -> assertThat(context.getBeansOfType(JestClient.class)).hasSize(1)); } @Test public void customJestClient() { this.contextRunner.withUserConfiguration(CustomJestClient.class) - .withPropertyValues( - "spring.elasticsearch.jest.uris[0]=http://localhost:9200") - .run((context) -> assertThat(context.getBeansOfType(JestClient.class)) - .hasSize(1)); + .withPropertyValues("spring.elasticsearch.jest.uris[0]=http://localhost:9200") + .run((context) -> assertThat(context.getBeansOfType(JestClient.class)).hasSize(1)); } @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")); }); } @@ -103,46 +95,37 @@ 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() { new ElasticsearchNodeTemplate().doWithNode((node) -> this.contextRunner - .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:" - + node.getHttpPort()) + .withPropertyValues("spring.elasticsearch.jest.uris=http://localhost:" + node.getHttpPort()) .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") - .build(); + Index index = new Index.Builder(source).index("foo").type("bar").build(); execute(client, index); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("a", "alpha")); - assertThat(execute(client, - new Search.Builder(searchSourceBuilder.toString()) - .addIndex("foo").build()).getResponseCode()) - .isEqualTo(200); + assertThat( + execute(client, new Search.Builder(searchSourceBuilder.toString()).addIndex("foo").build()) + .getResponseCode()).isEqualTo(200); })); } 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 56b515ebc25..0c21e88b018 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +70,13 @@ public class FlywayAutoConfigurationTests { @Test public void noDataSource() { - this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); } @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(); }); @@ -87,8 +85,7 @@ public class FlywayAutoConfigurationTests { @Test public void createDataSourceWithUser() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:normal", - "spring.flyway.user:sa") + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:normal", "spring.flyway.user:sa") .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getDataSource()).isNotNull(); @@ -97,8 +94,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")); @@ -107,50 +105,45 @@ 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("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("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( - "classpath:db/changelog", "classpath:db/migration"); + assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", + "classpath:db/migration"); }); } @@ -162,8 +155,8 @@ public class FlywayAutoConfigurationTests { .run((context) -> { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getLocations()).containsExactly( - "classpath:db/changelog", "classpath:db/migration"); + assertThat(flyway.getLocations()).containsExactly("classpath:db/changelog", + "classpath:db/migration"); }); } @@ -173,41 +166,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 migrations location in"); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + assertThat(context).getFailure().hasMessageContaining("Cannot find migrations location 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()); } @@ -221,15 +207,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(); }); @@ -237,21 +223,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()); } @@ -261,8 +245,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")); }); } @@ -272,55 +255,45 @@ 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( - "classpath:db/vendors/h2", "classpath:db/changelog"); + assertThat(flyway.getLocations()).containsExactlyInAnyOrder("classpath:db/vendors/h2", + "classpath:db/changelog"); }); } @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("classpath:db/vendors/h2"); + assertThat(flyway.getLocations()).containsExactly("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); - FlywayCallback callbackOne = context.getBean("callbackOne", - FlywayCallback.class); - FlywayCallback callbackTwo = context.getBean("callbackTwo", - FlywayCallback.class); + FlywayCallback callbackOne = context.getBean("callbackOne", FlywayCallback.class); + FlywayCallback callbackTwo = context.getBean("callbackTwo", FlywayCallback.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) - .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)); }); } @@ -330,15 +303,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(); } } @@ -348,8 +319,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; } @@ -375,15 +345,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; 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 0b277cc7c0f..c10cf7a8237 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 34b5f80b264..490b59515ee 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -122,32 +121,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(ReflectionTestUtils.getField(viewResolver, "allowSessionOverride")) - .isEqualTo(true); + AbstractTemplateViewResolver viewResolver = this.context.getBean(FreeMarkerViewResolver.class); + assertThat(ReflectionTestUtils.getField(viewResolver, "allowSessionOverride")).isEqualTo(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"); @@ -162,10 +157,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)); } @@ -174,14 +167,11 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @SuppressWarnings("rawtypes") public void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 - load(FilterRegistrationConfiguration.class, - "spring.resources.chain.enabled:true"); - Map beans = this.context - .getBeansOfType(FilterRegistrationBean.class); + load(FilterRegistrationConfiguration.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)); } @@ -203,21 +193,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 - @ImportAutoConfiguration({ FreeMarkerAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ FreeMarkerAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class BaseConfiguration { } @@ -228,8 +215,7 @@ public class FreeMarkerAutoConfigurationServletIntegrationTests { @Bean public FilterRegistrationBean filterRegisration() { - return new FilterRegistrationBean( - new OrderedCharacterEncodingFilter()); + return new FilterRegistrationBean(new OrderedCharacterEncodingFilter()); } } 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 1c479f6e49f..d8c520d80a2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); @@ -63,15 +62,15 @@ public class FreeMarkerAutoConfigurationTests { this.contextRunner .withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,classpath:/also-does-not-exist") - .run((context) -> this.output - .expect(containsString("Cannot find template location"))); + .run((context) -> this.output.expect(containsString("Cannot find template location"))); } @Test public void emptyTemplateLocation() { new File("target/test-classes/templates/empty-directory").mkdir(); - this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/templates/empty-directory/").run((context) -> { + this.contextRunner + .withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/templates/empty-directory/") + .run((context) -> { }); } @@ -79,8 +78,7 @@ public class FreeMarkerAutoConfigurationTests { public void nonExistentLocationAndEmptyLocation() { new File("target/test-classes/templates/empty-directory").mkdir(); this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/templates/empty-directory/") - .run((context) -> { + + "classpath:/does-not-exist/,classpath:/templates/empty-directory/").run((context) -> { }); } 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 32fa73d55f4..057d8a3f71a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 6343ec5287a..300b95fb597 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class GroovyTemplateAutoConfigurationTests { @Test public void emptyTemplateLocation() { new File("target/test-classes/templates/empty-directory").mkdir(); - registerAndRefreshContext("spring.groovy.template.resource-loader-path:" - + "classpath:/templates/empty-directory/"); + registerAndRefreshContext( + "spring.groovy.template.resource-loader-path:" + "classpath:/templates/empty-directory/"); } @Test @@ -101,8 +101,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(); } @@ -143,8 +142,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"); @@ -153,8 +151,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 @@ -164,18 +161,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) { @@ -188,16 +181,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 ccc4aa51c49..59ad8af4c9f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 37bdfe0c0f3..5cbaab7fafa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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("{}"); @@ -82,18 +77,15 @@ public class GsonAutoConfigurationTests { @Test public void serializeNulls() { - 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 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<>(); @@ -107,73 +99,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,19 +172,18 @@ public class GsonAutoConfigurationTests { @Test public void withLenient() { - this.contextRunner.withPropertyValues("spring.gson.lenient:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - /* - * It seems that lenient setting not work in version 2.8.2. We get - * access to it via reflection - */ - Field lenientField = gson.getClass().getDeclaredField("lenient"); - lenientField.setAccessible(true); - boolean lenient = lenientField.getBoolean(gson); + this.contextRunner.withPropertyValues("spring.gson.lenient:true").run((context) -> { + Gson gson = context.getBean(Gson.class); + /* + * It seems that lenient setting not work in version 2.8.2. We get access to + * it via reflection + */ + Field lenientField = gson.getClass().getDeclaredField("lenient"); + lenientField.setAccessible(true); + boolean lenient = lenientField.getBoolean(gson); - assertThat(lenient).isTrue(); - }); + assertThat(lenient).isTrue(); + }); } @Test @@ -219,23 +196,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 @@ -243,18 +218,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 1913ec8d8cc..e07fbde2415 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +69,10 @@ 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 @@ -82,54 +80,42 @@ public class H2ConsoleAutoConfigurationTests { this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Failed to bind properties under 'spring.h2.console'"); 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(); } @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/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index 39a2333eb0b..2ca15087c9b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 HypermediaAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); 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(); @@ -101,12 +100,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); } } } @@ -116,22 +114,19 @@ public class HypermediaAutoConfigurationTests { this.context = new AnnotationConfigWebApplicationContext(); 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 f1dc48dfd33..084a6f3dfb3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 7ea849477b5..5ce90e9b48f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,56 +64,44 @@ public class HazelcastAutoConfigurationClientTests { @Test public void systemProperty() { - 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((context) -> assertThat(context).getBean(HazelcastInstance.class) - .isInstanceOf(HazelcastInstance.class) - .has(nameStartingWith("hz.client_"))); + .isInstanceOf(HazelcastInstance.class).has(nameStartingWith("hz.client_"))); } @Test public void explicitConfigFile() { this.contextRunner - .withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml") + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml") .run((context) -> assertThat(context).getBean(HazelcastInstance.class) - .isInstanceOf(HazelcastClientProxy.class) - .has(nameStartingWith("hz.client_"))); + .isInstanceOf(HazelcastClientProxy.class).has(nameStartingWith("hz.client_"))); } @Test public void explicitConfigUrl() { - this.contextRunner - .withPropertyValues( - "spring.hazelcast.config=hazelcast-client-default.xml") + this.contextRunner.withPropertyValues("spring.hazelcast.config=hazelcast-client-default.xml") .run((context) -> assertThat(context).getBean(HazelcastInstance.class) - .isInstanceOf(HazelcastClientProxy.class) - .has(nameStartingWith("hz.client_"))); + .isInstanceOf(HazelcastClientProxy.class).has(nameStartingWith("hz.client_"))); } @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 Condition nameStartingWith(String prefix) { - return new Condition<>((o) -> o.getName().startsWith(prefix), - "Name starts with " + prefix); + return new Condition<>((o) -> o.getName().startsWith(prefix), "Name starts with " + prefix); } @Configuration 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 ef42c230c76..7e9c02e1abb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); }); } @@ -72,34 +71,26 @@ public class HazelcastAutoConfigurationServerTests { @Test public void explicitConfigFile() { this.contextRunner.withPropertyValues( - "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.xml") + "spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.xml") .run((context) -> { Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getConfigurationFile()) - .isEqualTo(new ClassPathResource( - "org/springframework/boot/autoconfigure/hazelcast" - + "/hazelcast-specific.xml").getFile()); + assertThat(config.getConfigurationFile()).isEqualTo(new ClassPathResource( + "org/springframework/boot/autoconfigure/hazelcast" + "/hazelcast-specific.xml").getFile()); }); } @Test public void explicitConfigUrl() { - this.contextRunner - .withPropertyValues("spring.hazelcast.config=hazelcast-default.xml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getConfigurationUrl()).isEqualTo( - new ClassPathResource("hazelcast-default.xml").getURL()); - }); + this.contextRunner.withPropertyValues("spring.hazelcast.config=hazelcast-default.xml").run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getConfigurationUrl()).isEqualTo(new ClassPathResource("hazelcast-default.xml").getURL()); + }); } @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")); } @@ -109,12 +100,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); }); @@ -127,8 +115,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 06a311be7fc..362fce0054d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 HazelcastAutoConfigurationTests { // no hazelcast-client.xml and hazelcast.xml is 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()); }); } 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 b4a07ddb58f..1dadc9a0c60 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 8b9b64e4bc7..aac8902c2ff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,48 +61,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 @@ -115,33 +106,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 @@ -154,71 +137,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()); }); } @@ -227,8 +197,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); }); @@ -236,13 +205,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); }); } @@ -250,36 +216,30 @@ 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")); } 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); @@ -315,8 +275,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; @@ -363,8 +322,7 @@ public class HttpMessageConvertersAutoConfigurationTests { @Bean public TypeConstrainedMappingJackson2HttpMessageConverter typeConstrainedConverter() { - return new TypeConstrainedMappingJackson2HttpMessageConverter( - ResourceSupport.class); + return new TypeConstrainedMappingJackson2HttpMessageConverter(ResourceSupport.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 90b1e633ebb..4b4b89decfe 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 34a0d45e3fb..4924c308cf6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,22 @@ public class CodecsAutoConfigurationTests { @Test public void jacksonCodecCustomizerBacksOffWhenThereIsNoObjectMapper() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); } @Test public void jacksonCodecCustomizerIsAutoConfiguredWhenObjectMapperIsPresent() { - this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(CodecCustomizer.class)); + this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(CodecCustomizer.class)); } @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(2); - assertThat(codecCustomizers.get(1)) - .isInstanceOf(TestCodecCustomizer.class); + assertThat(codecCustomizers.get(1)).isInstanceOf(TestCodecCustomizer.class); }); } 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 5cc66c0554d..5452a8237df 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,35 +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 influxDbWithoutCredentialsAndOkHttpClientBuilder() { this.contextRunner.withUserConfiguration(CustomOkHttpClientBuilderConfig.class) - .withPropertyValues("spring.influx.url=http://localhost") - .run((context) -> { + .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); int readTimeout = getReadTimeoutProperty(context); assertThat(readTimeout).isEqualTo(30_000); @@ -84,8 +79,8 @@ public class InfluxDbAutoConfigurationTests { @Test public void influxDbWithOkHttpClientBuilder() { this.contextRunner.withUserConfiguration(CustomOkHttpClientBuilderConfig.class) - .withPropertyValues("spring.influx.url=http://localhost", - "spring.influx.password:password", "spring.influx.user:user") + .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.password:password", + "spring.influx.user:user") .run((context) -> { assertThat(context.getBeansOfType(InfluxDB.class)).hasSize(1); int readTimeout = getReadTimeoutProperty(context); @@ -95,10 +90,8 @@ public class InfluxDbAutoConfigurationTests { private int getReadTimeoutProperty(AssertableApplicationContext context) { InfluxDB influxDB = context.getBean(InfluxDB.class); - Retrofit retrofit = (Retrofit) new DirectFieldAccessor(influxDB) - .getPropertyValue("retrofit"); - OkHttpClient callFactory = (OkHttpClient) new DirectFieldAccessor(retrofit) - .getPropertyValue("callFactory"); + Retrofit retrofit = (Retrofit) new DirectFieldAccessor(influxDB).getPropertyValue("retrofit"); + OkHttpClient callFactory = (OkHttpClient) new DirectFieldAccessor(retrofit).getPropertyValue("callFactory"); return callFactory.readTimeoutMillis(); } 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 2f3ccc580ed..bed3b263cc9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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")); }); } @@ -79,45 +74,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")); + }); } @Configuration 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 04bb1ac927e..c4c5b15b63c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,38 +62,31 @@ public class IntegrationAutoConfigurationTests { public ExpectedException thrown = ExpectedException.none(); 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); }); } @@ -101,91 +94,73 @@ 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 jmxIntegrationEnabledByDefault() { this.contextRunner.run((context) -> { MBeanServer mBeanServer = context.getBean(MBeanServer.class); - assertThat(mBeanServer.getDomains()).contains( - "org.springframework.integration", + assertThat(mBeanServer.getDomains()).contains("org.springframework.integration", "org.springframework.integration.monitor"); - assertThat(context) - .hasBean(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME); + assertThat(context).hasBean(IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME); }); } @Test public void disableJmxIntegration() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=false") - .run((context) -> { - assertThat(context).doesNotHaveBean(MBeanServer.class); - assertThat(context) - .hasSingleBean(IntegrationManagementConfigurer.class); - }); + this.contextRunner.withPropertyValues("spring.jmx.enabled=false").run((context) -> { + assertThat(context).doesNotHaveBean(MBeanServer.class); + assertThat(context).hasSingleBean(IntegrationManagementConfigurer.class); + }); } @Test public void customizeJmxDomain() { - this.contextRunner.withPropertyValues("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"); - }); + this.contextRunner.withPropertyValues("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"); + }); } @Test public void primaryExporterIsAllowed() { - this.contextRunner.withUserConfiguration(CustomMBeanExporter.class) - .run((context) -> { - assertThat(context).getBeans(MBeanExporter.class).hasSize(2); - assertThat(context.getBean(MBeanExporter.class)) - .isSameAs(context.getBean("myMBeanExporter")); - }); + this.contextRunner.withUserConfiguration(CustomMBeanExporter.class).run((context) -> { + assertThat(context).getBeans(MBeanExporter.class).hasSize(2); + 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); @@ -197,14 +172,10 @@ public class IntegrationAutoConfigurationTests { @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); @@ -214,12 +185,11 @@ public class IntegrationAutoConfigurationTests { @Test public void integrationEnablesDefaultCounts() { - this.contextRunner.withUserConfiguration(MessageSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("myMessageSource"); - assertThat(new DirectFieldAccessor(context.getBean("myMessageSource")) - .getPropertyValue("countsEnabled")).isEqualTo(true); - }); + this.contextRunner.withUserConfiguration(MessageSourceConfiguration.class).run((context) -> { + assertThat(context).hasBean("myMessageSource"); + assertThat(new DirectFieldAccessor(context.getBean("myMessageSource")).getPropertyValue("countsEnabled")) + .isEqualTo(true); + }); } @Configuration 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 e7859de2b75..d9c8965840e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +91,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\"}"); }); } @@ -110,30 +108,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\""); }); } @@ -157,13 +148,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 @@ -172,191 +160,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(); }); @@ -365,86 +301,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 @@ -452,22 +370,19 @@ 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 + "\""); }); } - 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(ReflectionTestUtils.getField(annotationIntrospector, - "creatorBinding")).isEqualTo(expectedMode); + DeserializationConfig deserializationConfig = context.getBean(ObjectMapper.class) + .getDeserializationConfig(); + AnnotationIntrospector annotationIntrospector = deserializationConfig.getAnnotationIntrospector() + .allIntrospectors().iterator().next(); + assertThat(ReflectionTestUtils.getField(annotationIntrospector, "creatorBinding")).isEqualTo(expectedMode); }); } @@ -510,8 +425,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(); @@ -589,8 +503,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 8ff132b20db..6eb3a5a8a2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 545cdc3cdd7..d57a606844e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 ffa49eac9ae..ae87db70e3f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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)); }); } @@ -192,33 +172,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); }); } @@ -226,57 +202,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:" - + getRelativeLocationFor("lexical-schema-*.sql"), + "spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt(), + "spring.datasource.schema:" + getRelativeLocationFor("lexical-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 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"); }); } @@ -329,8 +290,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 f30e58917a5..f23281646fd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a391a0b8fe4..de906f46968 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,66 +51,50 @@ 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() { String poolName = UUID.randomUUID().toString(); this.contextRunner - .withPropertyValues( - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true") + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "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); }); } @@ -118,14 +102,11 @@ public class DataSourceJmxConfigurationTests { public void hikariProxiedCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) - .withPropertyValues( - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true") + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "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 +114,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.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.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.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 +190,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 f84ff9ec842..10de89bf83a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 f1c6b770050..82089c71e4a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 DataSourcePropertiesTests { DataSourceProperties properties = new DataSourceProperties(); properties.setUrl("jdbc:mysql://mydb"); assertThat(properties.getDriverClassName()).isNull(); - assertThat(properties.determineDriverClassName()) - .isEqualTo("com.mysql.jdbc.Driver"); + assertThat(properties.determineDriverClassName()).isEqualTo("com.mysql.jdbc.Driver"); } @Test @@ -52,8 +51,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 @@ -61,15 +59,13 @@ 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(); this.thrown.expect(DataSourceProperties.DataSourceBeanCreationException.class); this.thrown.expectMessage("Failed to determine suitable jdbc url"); 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 d3428958690..674de0851c1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 74026bb5e2d..11f5f2d2654 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 2d281e43625..bc92e2f4dd9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); @@ -64,14 +63,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"); }); } @@ -86,19 +83,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 14a810267d0..0ba0bfe1ce5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 b5f9fb89153..5d8a4489f08 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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); @@ -66,8 +65,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(); @@ -79,97 +77,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); }); } @@ -177,25 +156,19 @@ 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 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); }); } @@ -208,8 +181,7 @@ public class JdbcTemplateAutoConfigurationTests { } @Bean - public NamedParameterJdbcOperations customNamedParameterJdbcOperations( - DataSource dataSource) { + public NamedParameterJdbcOperations customNamedParameterJdbcOperations(DataSource dataSource) { return new NamedParameterJdbcTemplate(dataSource); } @@ -261,8 +233,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); } } @@ -272,8 +243,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); } } 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 9443f6750f8..1b36a2e394a 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 { @Before 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()); } @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); + Thread.currentThread().setContextClassLoader(new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After 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,39 +94,33 @@ 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) new DirectFieldAccessor(exporter) - .getPropertyValue("excludedBeans"); + Set excludedBeans = (Set) new DirectFieldAccessor(exporter).getPropertyValue("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()) { + for (MBeanExporter exporter : this.context.getBeansOfType(MBeanExporter.class).values()) { Set excludedBeans = (Set) new DirectFieldAccessor(exporter) .getPropertyValue("excludedBeans"); assertThat(excludedBeans).containsExactly("dataSource"); @@ -139,26 +129,22 @@ public class JndiDataSourceAutoConfigurationTests { @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) new DirectFieldAccessor(exporter) - .getPropertyValue("excludedBeans"); + Set excludedBeans = (Set) new DirectFieldAccessor(exporter).getPropertyValue("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 7558b77a02c..8929692aee9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +62,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(); @@ -90,10 +87,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; @@ -107,8 +102,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); @@ -130,8 +124,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 d2c78f24fd8..8971ce7ca85 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 aae64bf899d..9f72d9e209e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -77,8 +76,8 @@ public class JerseyAutoConfigurationCustomApplicationTests { } @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - JerseyAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, JerseyAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class }) static class TestConfiguration { @Configuration 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 1f02834d956..c496d416bbb 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 @@ -63,8 +63,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); } @@ -95,8 +94,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 ac510076755..fbc4a314fef 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 @@ -53,8 +53,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.type=filter") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext public class JerseyAutoConfigurationCustomFilterPathTests { @@ -63,8 +62,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); } @@ -95,8 +93,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 9c6b83ff47d..c66ef697c84 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 @@ -46,8 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll */ @RunWith(SpringRunner.class) -@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 { @@ -56,9 +55,8 @@ public class JerseyAutoConfigurationCustomLoadOnStartupTests { @Test public void contextLoads() { - assertThat( - new DirectFieldAccessor(this.context.getBean("jerseyServletRegistration")) - .getPropertyValue("loadOnStartup")).isEqualTo(5); + assertThat(new DirectFieldAccessor(this.context.getBean("jerseyServletRegistration")) + .getPropertyValue("loadOnStartup")).isEqualTo(5); } @MinimalWebConfiguration @@ -74,8 +72,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 fbddfe63657..07a8f5fc9d6 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 @@ -63,8 +63,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()); } @@ -122,9 +121,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 66cc0e5f193..f7c0cee6899 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 @@ -54,8 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "server.servlet.contextPath=/app") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "server.servlet.contextPath=/app") @DirtiesContext public class JerseyAutoConfigurationCustomServletContextPathTests { @@ -64,8 +63,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); } @@ -96,8 +94,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 440cba9e652..da108db525d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,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); } @@ -95,8 +94,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 30951cdcddd..a94f0f4bcdb 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 @@ -52,8 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "spring.jersey.type=filter") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.jersey.type=filter") @DirtiesContext public class JerseyAutoConfigurationDefaultFilterPathTests { @@ -62,8 +61,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); } @@ -93,8 +91,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 9075d765d69..f92da95c689 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -93,8 +92,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 cc1ca70e793..5c5aecee878 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 @@ -65,8 +65,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\"}"); } @@ -133,9 +132,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 7ab15ee046b..67e7a3f89f5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 @@ public class JerseyAutoConfigurationServletContainerTests { @Test public void existingJerseyServletIsAmended() { - assertThat(output.toString()) - .contains("Configuring existing registration for Jersey servlet"); - assertThat(output.toString()).contains( - "Servlet " + Application.class.getName() + " was not registered"); + assertThat(output.toString()).contains("Configuring existing registration for Jersey servlet"); + assertThat(output.toString()).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/JerseyAutoConfigurationWithoutApplicationPathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java index ee5b69b8e3c..ba26eaf47e8 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 @@ -52,8 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez */ @RunWith(SpringRunner.class) -@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 { @@ -62,8 +61,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); } @@ -93,8 +91,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 109e1a949cf..7b99af2e1f9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,65 +64,56 @@ 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) { - ActiveMQConnectionFactory factory = loaded - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = loaded.getBean(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(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()) - .getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) + .isEqualTo(ACTIVEMQ_EMBEDDED_URL); assertThat(loaded.containsBean("jmsListenerContainerFactory")).isTrue(); } @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); } @@ -130,149 +121,118 @@ 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 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(new DirectFieldAccessor(container) - .getPropertyValue("transactionManager")).isSameAs( - context.getBean(JtaTransactionManager.class)); + assertThat(new DirectFieldAccessor(container).getPropertyValue("transactionManager")) + .isSameAs(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(new DirectFieldAccessor(container) - .getPropertyValue("transactionManager")).isNull(); + assertThat(new DirectFieldAccessor(container).getPropertyValue("transactionManager")).isNull(); }); } @Test public void testDefaultContainerFactoryNoTransactionManager() { - this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, - "jmsListenerContainerFactory"); - assertThat(container.isSessionTransacted()).isTrue(); - assertThat(new DirectFieldAccessor(container) - .getPropertyValue("transactionManager")).isNull(); - }); + this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class).run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isTrue(); + assertThat(new DirectFieldAccessor(container).getPropertyValue("transactionManager")).isNull(); + }); } @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); @@ -285,15 +245,13 @@ public class JmsAutoConfigurationTests { @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 @@ -314,12 +272,10 @@ public class JmsAutoConfigurationTests { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.jms.pubSubDomain:false").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(factory).isNotNull() - .isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); }); } @@ -328,47 +284,38 @@ public class JmsAutoConfigurationTests { this.contextRunner.withUserConfiguration(TestConfiguration.class) .withPropertyValues("spring.activemq.inMemory:false").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); - assertThat(factory).isNotNull() - .isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(((ActiveMQConnectionFactory) jmsTemplate - .getConnectionFactory()).getBrokerURL()) - .isEqualTo(ACTIVEMQ_NETWORK_URL); + assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) + .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) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertThat(jmsTemplate).isNotNull(); assertThat(factory).isNotNull(); assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); - assertThat(((ActiveMQConnectionFactory) jmsTemplate - .getConnectionFactory()).getBrokerURL()) - .isEqualTo("tcp://remote-host:10000"); + assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()) + .isEqualTo("tcp://remote-host:10000"); }); } @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); - PooledConnectionFactory pool = context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory pool = context.getBean(PooledConnectionFactory.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); }); } @@ -376,17 +323,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); - PooledConnectionFactory pool = context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory pool = context.getBean(PooledConnectionFactory.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); }); } @@ -398,25 +342,21 @@ public class JmsAutoConfigurationTests { "spring.activemq.brokerUrl:tcp://remote-host:10000") .run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - PooledConnectionFactory pool = context - .getBean(PooledConnectionFactory.class); + PooledConnectionFactory pool = context.getBean(PooledConnectionFactory.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 @@ -454,8 +394,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); @@ -464,8 +403,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; } @@ -476,8 +414,7 @@ public class JmsAutoConfigurationTests { @Bean JmsMessagingTemplate jmsMessagingTemplate(JmsTemplate jmsTemplate) { - JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate( - jmsTemplate); + JmsMessagingTemplate messagingTemplate = new JmsMessagingTemplate(jmsTemplate); messagingTemplate.setDefaultDestinationName("fooBar"); return messagingTemplate; } @@ -488,8 +425,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; @@ -554,8 +490,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 1ca12219b78..e67840e219c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; @@ -52,19 +51,16 @@ public class JndiConnectionFactoryAutoConfigurationTests { @Before 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())); } @After 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); @@ -74,8 +70,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 @@ -86,8 +81,7 @@ public class JndiConnectionFactoryAutoConfigurationTests { @Test public void detectWithXAConnectionFactory() { - ConnectionFactory connectionFactory = configureConnectionFactory( - "java:/XAConnectionFactory"); + ConnectionFactory connectionFactory = configureConnectionFactory("java:/XAConnectionFactory"); this.contextRunner.run(assertConnectionFactory(connectionFactory)); } @@ -100,21 +94,17 @@ public class JndiConnectionFactoryAutoConfigurationTests { @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 b3a51afc702..b16d664d1b6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,56 +43,40 @@ 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).getBean(ConnectionFactory.class) - .isInstanceOf(ActiveMQConnectionFactory.class); - assertThat(context.getBean(ActiveMQConnectionFactory.class) - .getBrokerURL()) - .isEqualTo("vm://localhost?broker.persistent=false"); - }); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { + assertThat(context).getBean(ConnectionFactory.class).isInstanceOf(ActiveMQConnectionFactory.class); + assertThat(context.getBean(ActiveMQConnectionFactory.class).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 defaultConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=false") - .run((context) -> { - assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)) - .hasSize(1); - ActiveMQConnectionFactory connectionFactory = context - .getBean(ActiveMQConnectionFactory.class); + .withPropertyValues("spring.activemq.pool.enabled=false").run((context) -> { + 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())); }); } @@ -101,53 +85,39 @@ public class ActiveMQAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.activemq.pool.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 defaultPooledConnectionFactoryIsApplied() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=true") - .run((context) -> { - assertThat(context.getBeansOfType(PooledConnectionFactory.class)) - .hasSize(1); - PooledConnectionFactory connectionFactory = context - .getBean(PooledConnectionFactory.class); + .withPropertyValues("spring.activemq.pool.enabled=true").run((context) -> { + assertThat(context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); + PooledConnectionFactory connectionFactory = context.getBean(PooledConnectionFactory.class); PooledConnectionFactory defaultFactory = new PooledConnectionFactory(); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo( - defaultFactory.getBlockIfSessionPoolIsFullTimeout()); - assertThat(connectionFactory.getIdleTimeout()) - .isEqualTo(defaultFactory.getIdleTimeout()); - assertThat(connectionFactory.getMaxConnections()) - .isEqualTo(defaultFactory.getMaxConnections()); + .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); + assertThat(connectionFactory.getIdleTimeout()).isEqualTo(defaultFactory.getIdleTimeout()); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); assertThat(connectionFactory.getMaximumActiveSessionPerConnection()) - .isEqualTo(defaultFactory - .getMaximumActiveSessionPerConnection()); + .isEqualTo(defaultFactory.getMaximumActiveSessionPerConnection()); assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()) - .isEqualTo( - defaultFactory.getTimeBetweenExpirationCheckMillis()); + .isEqualTo(defaultFactory.getTimeBetweenExpirationCheckMillis()); assertThat(connectionFactory.isUseAnonymousProducers()) .isEqualTo(defaultFactory.isUseAnonymousProducers()); }); @@ -157,17 +127,13 @@ public class ActiveMQAutoConfigurationTests { @Deprecated public void defaultPooledConnectionFactoryIsAppliedWithDeprecatedSettings() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.activemq.pool.enabled=true") - .run((context) -> { - assertThat(context.getBeansOfType(PooledConnectionFactory.class)) - .hasSize(1); - PooledConnectionFactory connectionFactory = context - .getBean(PooledConnectionFactory.class); + .withPropertyValues("spring.activemq.pool.enabled=true").run((context) -> { + assertThat(context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); + PooledConnectionFactory connectionFactory = context.getBean(PooledConnectionFactory.class); PooledConnectionFactory defaultFactory = new PooledConnectionFactory(); assertThat(connectionFactory.isCreateConnectionOnStartup()) .isEqualTo(defaultFactory.isCreateConnectionOnStartup()); - assertThat(connectionFactory.getExpiryTimeout()) - .isEqualTo(defaultFactory.getExpiryTimeout()); + assertThat(connectionFactory.getExpiryTimeout()).isEqualTo(defaultFactory.getExpiryTimeout()); assertThat(connectionFactory.isReconnectOnException()) .isEqualTo(defaultFactory.isReconnectOnException()); }); @@ -176,28 +142,21 @@ public class ActiveMQAutoConfigurationTests { @Test public void customPooledConnectionFactoryIsApplied() { 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", + .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.maximumActiveSessionPerConnection=1024", "spring.activemq.pool.timeBetweenExpirationCheck=2048", "spring.activemq.pool.useAnonymousProducers=false") .run((context) -> { - assertThat(context.getBeansOfType(PooledConnectionFactory.class)) - .hasSize(1); - PooledConnectionFactory connectionFactory = context - .getBean(PooledConnectionFactory.class); + assertThat(context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); + PooledConnectionFactory connectionFactory = context.getBean(PooledConnectionFactory.class); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo(64); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); assertThat(connectionFactory.getIdleTimeout()).isEqualTo(512); assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaximumActiveSessionPerConnection()) - .isEqualTo(1024); - assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()) - .isEqualTo(2048); + assertThat(connectionFactory.getMaximumActiveSessionPerConnection()).isEqualTo(1024); + assertThat(connectionFactory.getTimeBetweenExpirationCheckMillis()).isEqualTo(2048); assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); }); } @@ -208,13 +167,10 @@ public class ActiveMQAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.activemq.pool.enabled=true", "spring.activemq.pool.createConnectionOnStartup=false", - "spring.activemq.pool.expiryTimeout=4096", - "spring.activemq.pool.reconnectOnException=false") + "spring.activemq.pool.expiryTimeout=4096", "spring.activemq.pool.reconnectOnException=false") .run((context) -> { - assertThat(context.getBeansOfType(PooledConnectionFactory.class)) - .hasSize(1); - PooledConnectionFactory connectionFactory = context - .getBean(PooledConnectionFactory.class); + assertThat(context.getBeansOfType(PooledConnectionFactory.class)).hasSize(1); + PooledConnectionFactory connectionFactory = context.getBean(PooledConnectionFactory.class); assertThat(connectionFactory.isCreateConnectionOnStartup()).isFalse(); assertThat(connectionFactory.getExpiryTimeout()).isEqualTo(4096); assertThat(connectionFactory.isReconnectOnException()).isFalse(); @@ -224,8 +180,7 @@ public class ActiveMQAutoConfigurationTests { @Test public void pooledConnectionFactoryConfiguration() { 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(PooledConnectionFactory.class); context.getSourceApplicationContext().close(); @@ -254,8 +209,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 c5b1e8ae8e0..e09ecf6a194 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 8d40dc7dc8d..58d877622a7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +65,14 @@ public class ArtemisAutoConfigurationTests { public final TemporaryFolder folder = new TemporaryFolder(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, - JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); @Test public void nativeConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) .withPropertyValues("spring.artemis.mode:native").run((context) -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(factory, "localhost", 61616); assertThat(factory.getUser()).isNull(); @@ -85,11 +83,10 @@ 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) -> { - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertNettyConnectionFactory(factory, "192.168.1.144", 9876); }); } @@ -97,12 +94,11 @@ public class ArtemisAutoConfigurationTests { @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); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertThat(factory).isEqualTo(jmsTemplate.getConnectionFactory()); assertNettyConnectionFactory(factory, "localhost", 61616); assertThat(factory.getUser()).isEqualTo("user"); @@ -114,17 +110,14 @@ 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(); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(factory); }); } @@ -132,29 +125,24 @@ public class ArtemisAutoConfigurationTests { @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(); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); - assertInVmConnectionFactory(factory); - }); + 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(); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); + assertInVmConnectionFactory(factory); + }); } @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); - ActiveMQConnectionFactory factory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory factory = context.getBean(ActiveMQConnectionFactory.class); assertNettyConnectionFactory(factory, "localhost", 61616); }); } @@ -163,12 +151,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(); - ActiveMQConnectionFactory connectionFactory = context - .getBean(ActiveMQConnectionFactory.class); + ActiveMQConnectionFactory connectionFactory = context.getBean(ActiveMQConnectionFactory.class); assertInVmConnectionFactory(connectionFactory); }); } @@ -190,20 +176,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); @@ -214,9 +198,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 @@ -227,8 +211,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) -> { @@ -244,35 +227,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", @@ -281,40 +255,32 @@ 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); }); }); } - 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]; } @@ -338,21 +304,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 1fa90986799..ef822b4851b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 25afb725b36..653d62d4fb8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +98,9 @@ public class JmxAutoConfigurationTests { this.context.refresh(); MBeanExporter mBeanExporter = this.context.getBean(MBeanExporter.class); assertThat(mBeanExporter).isNotNull(); - MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils - .getField(mBeanExporter, "namingStrategy"); - assertThat(ReflectionTestUtils.getField(naming, "defaultDomain")) - .isEqualTo("my-test-domain"); + MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(mBeanExporter, + "namingStrategy"); + assertThat(ReflectionTestUtils.getField(naming, "defaultDomain")).isEqualTo("my-test-domain"); } @Test @@ -131,11 +130,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); DirectFieldAccessor dfa = new DirectFieldAccessor(mbeanExporter); assertThat(dfa.getPropertyValue("domain")).isEqualTo("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 4377921fd94..a3e0e654c23 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,75 +71,59 @@ 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")); - try { - dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');")); - fail("An DataIntegrityViolationException should have been thrown."); - } - catch (DataIntegrityViolationException ex) { - // Ignore - } - 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")); + try { + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');")); + fail("An DataIntegrityViolationException should have been thrown."); + } + catch (DataIntegrityViolationException ex) { + // Ignore + } + 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")); + 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")); try { - dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('bar');", + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", "insert into jooqtest (name) values ('foo');")); fail("A DataIntegrityViolationException should have been thrown."); } catch (DataIntegrityViolationException ex) { // Ignore } - 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).run((context) -> { DSLContext dsl = context.getBean(DSLContext.class); @@ -147,14 +131,10 @@ public class JooqAutoConfigurationTests { .isEqualTo(TestRecordMapperProvider.class); assertThat(dsl.configuration().recordUnmapperProvider().getClass()) .isEqualTo(TestRecordUnmapperProvider.class); - assertThat(dsl.configuration().recordListenerProviders().length) - .isEqualTo(1); - assertThat(dsl.configuration().executeListenerProviders().length) - .isEqualTo(2); - assertThat(dsl.configuration().visitListenerProviders().length) - .isEqualTo(1); - assertThat(dsl.configuration().transactionListenerProviders().length) - .isEqualTo(1); + assertThat(dsl.configuration().recordListenerProviders().length).isEqualTo(1); + assertThat(dsl.configuration().executeListenerProviders().length).isEqualTo(2); + assertThat(dsl.configuration().visitListenerProviders().length).isEqualTo(1); + assertThat(dsl.configuration().transactionListenerProviders().length).isEqualTo(1); }); } @@ -162,9 +142,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 { @@ -183,8 +162,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); } } @@ -214,8 +192,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(); } } @@ -233,8 +210,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; } @@ -243,8 +219,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; } @@ -259,8 +234,7 @@ public class JooqAutoConfigurationTests { } - protected static class TestExecuteListenerProvider - implements ExecuteListenerProvider { + protected static class TestExecuteListenerProvider implements ExecuteListenerProvider { @Override public ExecuteListener provide() { @@ -278,8 +252,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 f9bfdef2f1c..9c16a17e7d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 ed5991d62dc..c5ffadc2273 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a38e66291a3..70c10974834 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 @@ -50,8 +50,7 @@ public class KafkaAutoConfigurationIntegrationTests { private static final String ADMIN_CREATED_TOPIC = "adminCreatedTopic"; @ClassRule - public static final KafkaEmbedded kafkaEmbedded = new KafkaEmbedded(1, true, - TEST_TOPIC); + public static final KafkaEmbedded kafkaEmbedded = new KafkaEmbedded(1, true, TEST_TOPIC); private AnnotationConfigApplicationContext context; @@ -65,20 +64,16 @@ public class KafkaAutoConfigurationIntegrationTests { @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testEndToEnd() throws Exception { - load(KafkaConfig.class, - "spring.kafka.bootstrap-servers:" + kafkaEmbedded.getBrokersAsString(), - "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:" + kafkaEmbedded.getBrokersAsString(), + "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(); @@ -88,8 +83,7 @@ public class KafkaAutoConfigurationIntegrationTests { 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); @@ -122,8 +116,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 206a7b46e1a..8167faaa16f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,81 +69,53 @@ public class KafkaAutoConfigurationTests { @Test public void consumerProperties() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .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.keystore-location=classpath:ksLoc", - "spring.kafka.ssl.keystore-password=p2", - "spring.kafka.ssl.keystore-type=PKCS12", - "spring.kafka.ssl.truststore-location=classpath:tsLoc", - "spring.kafka.ssl.truststore-password=p3", - "spring.kafka.ssl.truststore-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=789", - "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") + this.contextRunner.withUserConfiguration(TestConfiguration.class).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.keystore-location=classpath:ksLoc", + "spring.kafka.ssl.keystore-password=p2", "spring.kafka.ssl.keystore-type=PKCS12", + "spring.kafka.ssl.truststore-location=classpath:tsLoc", "spring.kafka.ssl.truststore-password=p3", + "spring.kafka.ssl.truststore-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=789", + "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(789); - 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(789); + 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"); @@ -153,73 +125,50 @@ public class KafkaAutoConfigurationTests { @Test public void producerProperties() { - this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.kafka.clientId=cid", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.producer.acks=all", - "spring.kafka.producer.batch-size=20", - "spring.kafka.producer.bootstrap-servers=bar:1234", // test - // override - "spring.kafka.producer.buffer-memory=12345", - "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.ssl.key-password=p4", - "spring.kafka.producer.ssl.keystore-location=classpath:ksLocP", - "spring.kafka.producer.ssl.keystore-password=p5", - "spring.kafka.producer.ssl.keystore-type=PKCS12", - "spring.kafka.producer.ssl.truststore-location=classpath:tsLocP", - "spring.kafka.producer.ssl.truststore-password=p6", - "spring.kafka.producer.ssl.truststore-type=PKCS12", - "spring.kafka.producer.ssl.protocol=TLSv1.2", - "spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.IntegerSerializer") + this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( + "spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", + "spring.kafka.producer.acks=all", "spring.kafka.producer.batch-size=20", + "spring.kafka.producer.bootstrap-servers=bar:1234", // test + // override + "spring.kafka.producer.buffer-memory=12345", "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.ssl.key-password=p4", + "spring.kafka.producer.ssl.keystore-location=classpath:ksLocP", + "spring.kafka.producer.ssl.keystore-password=p5", "spring.kafka.producer.ssl.keystore-type=PKCS12", + "spring.kafka.producer.ssl.truststore-location=classpath:tsLocP", + "spring.kafka.producer.ssl.truststore-password=p6", "spring.kafka.producer.ssl.truststore-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(20); + assertThat(configs.get(ProducerConfig.BATCH_SIZE_CONFIG)).isEqualTo(20); assertThat(configs.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) .isEqualTo(Collections.singletonList("bar:1234")); // override - assertThat(configs.get(ProducerConfig.BUFFER_MEMORY_CONFIG)) - .isEqualTo(12345L); - 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(12345L); + 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"); }); @@ -227,49 +176,36 @@ 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.keystore-location=classpath:ksLocP", - "spring.kafka.admin.ssl.keystore-password=p5", - "spring.kafka.admin.ssl.keystore-type=PKCS12", - "spring.kafka.admin.ssl.truststore-location=classpath:tsLocP", - "spring.kafka.admin.ssl.truststore-password=p6", - "spring.kafka.admin.ssl.truststore-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.keystore-location=classpath:ksLocP", + "spring.kafka.admin.ssl.keystore-password=p5", "spring.kafka.admin.ssl.keystore-type=PKCS12", + "spring.kafka.admin.ssl.truststore-location=classpath:tsLocP", + "spring.kafka.admin.ssl.truststore-password=p6", + "spring.kafka.admin.ssl.truststore-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(KafkaTestUtils.getPropertyValue(admin, - "fatalIfBrokerNotAvailable", Boolean.class)).isTrue(); + assertThat(KafkaTestUtils.getPropertyValue(admin, "fatalIfBrokerNotAvailable", Boolean.class)) + .isTrue(); }); } @@ -278,76 +214,46 @@ public class KafkaAutoConfigurationTests { public void listenerProperties() { this.contextRunner.withUserConfiguration(TestConfiguration.class) .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.log-container-config=true", - "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.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.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); KafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(KafkaListenerContainerFactory.class); - assertThat(kafkaTemplate.getMessageConverter()) - .isInstanceOf(MessagingMessageConverter.class); - assertThat(new DirectFieldAccessor(kafkaTemplate) - .getPropertyValue("producerFactory")) - .isEqualTo(producerFactory); + assertThat(kafkaTemplate.getMessageConverter()).isInstanceOf(MessagingMessageConverter.class); + assertThat(new DirectFieldAccessor(kafkaTemplate).getPropertyValue("producerFactory")) + .isEqualTo(producerFactory); assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); - DirectFieldAccessor dfa = new DirectFieldAccessor( - kafkaListenerContainerFactory); - assertThat(dfa.getPropertyValue("consumerFactory")) - .isEqualTo(consumerFactory); - assertThat(dfa.getPropertyValue("containerProperties.ackMode")) - .isEqualTo(AckMode.MANUAL); - assertThat(dfa.getPropertyValue("containerProperties.clientId")) - .isEqualTo("client"); - assertThat(dfa.getPropertyValue("containerProperties.ackCount")) - .isEqualTo(123); - assertThat(dfa.getPropertyValue("containerProperties.ackTime")) - .isEqualTo(456L); + DirectFieldAccessor dfa = new DirectFieldAccessor(kafkaListenerContainerFactory); + assertThat(dfa.getPropertyValue("consumerFactory")).isEqualTo(consumerFactory); + assertThat(dfa.getPropertyValue("containerProperties.ackMode")).isEqualTo(AckMode.MANUAL); + assertThat(dfa.getPropertyValue("containerProperties.clientId")).isEqualTo("client"); + assertThat(dfa.getPropertyValue("containerProperties.ackCount")).isEqualTo(123); + assertThat(dfa.getPropertyValue("containerProperties.ackTime")).isEqualTo(456L); assertThat(dfa.getPropertyValue("concurrency")).isEqualTo(3); - assertThat(dfa.getPropertyValue("containerProperties.pollTimeout")) - .isEqualTo(2000L); - assertThat( - dfa.getPropertyValue("containerProperties.noPollThreshold")) - .isEqualTo(2.5f); - assertThat( - dfa.getPropertyValue("containerProperties.idleEventInterval")) - .isEqualTo(1000L); - assertThat( - dfa.getPropertyValue("containerProperties.monitorInterval")) - .isEqualTo(45); - assertThat(dfa - .getPropertyValue("containerProperties.logContainerConfig")) - .isEqualTo(Boolean.TRUE); + assertThat(dfa.getPropertyValue("containerProperties.pollTimeout")).isEqualTo(2000L); + assertThat(dfa.getPropertyValue("containerProperties.noPollThreshold")).isEqualTo(2.5f); + assertThat(dfa.getPropertyValue("containerProperties.idleEventInterval")).isEqualTo(1000L); + assertThat(dfa.getPropertyValue("containerProperties.monitorInterval")).isEqualTo(45); + assertThat(dfa.getPropertyValue("containerProperties.logContainerConfig")).isEqualTo(Boolean.TRUE); assertThat(dfa.getPropertyValue("batchListener")).isEqualTo(true); - 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); dfa = new DirectFieldAccessor(jaas); assertThat(dfa.getPropertyValue("loginModule")).isEqualTo("foo"); - assertThat(dfa.getPropertyValue("controlFlag")).isEqualTo( - AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)) - .hasSize(1); + assertThat(dfa.getPropertyValue("controlFlag")) + .isEqualTo(AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).hasSize(1); assertThat(((Map) dfa.getPropertyValue("options"))) .containsExactly(entry("useKeyTab", "true")); }); @@ -355,26 +261,20 @@ public class KafkaAutoConfigurationTests { @Test public void testKafkaTemplateRecordMessageConverters() { - this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .run((context) -> { - KafkaTemplate kafkaTemplate = context - .getBean(KafkaTemplate.class); - assertThat(kafkaTemplate.getMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); - }); + this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class).run((context) -> { + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); + assertThat(kafkaTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + }); } @Test public void testConcurrentKafkaListenerContainerFactoryWithCustomMessageConverters() { - this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - DirectFieldAccessor dfa = new DirectFieldAccessor( - kafkaListenerContainerFactory); - assertThat(dfa.getPropertyValue("messageConverter")) - .isSameAs(context.getBean("myMessageConverter")); - }); + this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class).run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + DirectFieldAccessor dfa = new DirectFieldAccessor(kafkaListenerContainerFactory); + assertThat(dfa.getPropertyValue("messageConverter")).isSameAs(context.getBean("myMessageConverter")); + }); } @Test @@ -382,10 +282,8 @@ public class KafkaAutoConfigurationTests { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context .getBean(ConcurrentKafkaListenerContainerFactory.class); - DirectFieldAccessor dfa = new DirectFieldAccessor( - kafkaListenerContainerFactory); - assertThat(dfa.getPropertyValue("replyTemplate")) - .isSameAs(context.getBean(KafkaTemplate.class)); + DirectFieldAccessor dfa = new DirectFieldAccessor(kafkaListenerContainerFactory); + assertThat(dfa.getPropertyValue("replyTemplate")).isSameAs(context.getBean(KafkaTemplate.class)); }); } 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 44de1294e82..fa99a694f1c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 LdapAutoConfigurationTests { public void contextSourceWithDefaultUrl() { this.contextRunner.run((context) -> { LdapContextSource contextSource = context.getBean(LdapContextSource.class); - String[] urls = (String[]) ReflectionTestUtils.getField(contextSource, - "urls"); + String[] urls = (String[]) ReflectionTestUtils.getField(contextSource, "urls"); assertThat(urls).containsExactly("ldap://localhost:389"); assertThat(contextSource.isAnonymousReadOnly()).isFalse(); }); @@ -50,49 +49,39 @@ public class LdapAutoConfigurationTests { @Test public void contextSourceWithSingleUrl() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123") - .run((context) -> { - ContextSource contextSource = context.getBean(ContextSource.class); - String[] urls = (String[]) ReflectionTestUtils.getField(contextSource, - "urls"); - assertThat(urls).containsExactly("ldap://localhost:123"); - }); + this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123").run((context) -> { + ContextSource contextSource = context.getBean(ContextSource.class); + String[] urls = (String[]) ReflectionTestUtils.getField(contextSource, "urls"); + assertThat(urls).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) -> { ContextSource contextSource = context.getBean(ContextSource.class); LdapProperties ldapProperties = context.getBean(LdapProperties.class); - String[] urls = (String[]) ReflectionTestUtils.getField(contextSource, - "urls"); - assertThat(urls).containsExactly("ldap://localhost:123", - "ldap://mycompany:123"); + String[] urls = (String[]) ReflectionTestUtils.getField(contextSource, "urls"); + assertThat(urls).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"); }); } 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 ee69ec8f3a7..1cf85e88e3d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,56 +45,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(); }); @@ -102,88 +91,60 @@ 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, - LdapDataAutoConfiguration.class)) + this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") + .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class, LdapDataAutoConfiguration.class)) .run((context) -> { - assertThat(context.getBeanNamesForType(LdapTemplate.class).length) - .isEqualTo(1); + 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); }); } @@ -191,8 +152,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 1b1c03a0048..c7aa89d96cf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +70,8 @@ public class LiquibaseAutoConfigurationTests { @Before 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() @@ -81,16 +80,14 @@ public class LiquibaseAutoConfigurationTests { @Test public void noDataSource() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); } @Test 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(); @@ -100,8 +97,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"))); } @@ -109,19 +105,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"))); } @@ -130,25 +123,21 @@ 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 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 @@ -158,35 +147,29 @@ 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"); })); } @Test public void overrideUser() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:normal", - "spring.datasource.username:not-sa", "spring.liquibase.user:sa") + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:normal", "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("jdbc:hsqldb:mem:normal"); - assertThat(((HikariDataSource) dataSource).getUsername()) - .isEqualTo("sa"); + assertThat(((HikariDataSource) dataSource).getJdbcUrl()).isEqualTo("jdbc:hsqldb:mem:normal"); + assertThat(((HikariDataSource) dataSource).getUsername()).isEqualTo("sa"); })); } @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); }); } @@ -196,8 +179,7 @@ public class LiquibaseAutoConfigurationTests { .run(assertLiquibase((liquibase) -> { Object log = ReflectionTestUtils.getField(liquibase, "log"); assertThat(log).isInstanceOf(CommonsLoggingLiquibaseLogger.class); - assertThat(this.outputCapture.toString()) - .doesNotContain(": liquibase:"); + assertThat(this.outputCapture.toString()).doesNotContain(": liquibase:"); })); } @@ -205,18 +187,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"); })); @@ -226,12 +206,9 @@ public class LiquibaseAutoConfigurationTests { public void rollbackFile() throws IOException { File file = this.temp.newFile("rollback-file.sql"); 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(); String content = new String(FileCopyUtils.copyToByteArray(file)); assertThat(content).contains("DROP TABLE PUBLIC.customer;"); @@ -240,26 +217,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); @@ -273,15 +247,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 4fe38447e1f..5eda852eb86 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +65,8 @@ public class ConditionEvaluationReportLoggingListenerTests { this.initializer.initialize(context); context.register(Config.class); context.refresh(); - withDebugLogging(() -> this.initializer - .onApplicationEvent(new ContextRefreshedEvent(context))); - assertThat(this.outputCapture.toString()) - .contains("CONDITIONS EVALUATION REPORT"); + withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context))); + assertThat(this.outputCapture.toString()).contains("CONDITIONS EVALUATION REPORT"); } @Test @@ -81,12 +79,10 @@ public class ConditionEvaluationReportLoggingListenerTests { fail("Did not error"); } catch (Exception ex) { - withDebugLogging( - () -> this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex))); + withDebugLogging(() -> this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex))); } - assertThat(this.outputCapture.toString()) - .contains("CONDITIONS EVALUATION REPORT"); + assertThat(this.outputCapture.toString()).contains("CONDITIONS EVALUATION REPORT"); } @Test @@ -99,12 +95,12 @@ public class ConditionEvaluationReportLoggingListenerTests { fail("Did not error"); } catch (Exception ex) { - this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex)); + this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)); } - assertThat(this.outputCapture.toString()).contains("Error starting" - + " ApplicationContext. To display the conditions report re-run" - + " your application with 'debug' enabled."); + assertThat(this.outputCapture.toString()) + .contains("Error starting" + " ApplicationContext. To display the conditions report re-run" + + " your application with 'debug' enabled."); } @Test @@ -112,13 +108,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(this.outputCapture.toString()) - .contains("not a servlet web application (OnWebApplicationCondition)"); + withDebugLogging(() -> this.initializer.onApplicationEvent(new ContextRefreshedEvent(context))); + assertThat(this.outputCapture.toString()).contains("not a servlet web application (OnWebApplicationCondition)"); } @Test @@ -149,29 +142,25 @@ public class ConditionEvaluationReportLoggingListenerTests { context.register(Config.class); context.refresh(); initializer.onApplicationEvent(new ContextRefreshedEvent(context)); - assertThat(this.outputCapture.toString()) - .contains("CONDITIONS EVALUATION REPORT"); + assertThat(this.outputCapture.toString()).contains("CONDITIONS EVALUATION REPORT"); } @Test public void listenerSupportsOnlyInfoAndDebug() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( - () -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) .withMessage("LogLevel must be INFO or DEBUG"); } @Test public void noErrorIfNotInitialized() { - this.initializer - .onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), - new String[0], null, new RuntimeException("Planned"))); - assertThat(this.outputCapture.toString()) - .contains("Unable to provide the conditions report"); + this.initializer.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], null, + new RuntimeException("Planned"))); + assertThat(this.outputCapture.toString()).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 cfbf79256d4..fcf8ae9e07f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 { @Before 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())); } @After 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(); }); @@ -151,25 +138,22 @@ public class MailSenderAutoConfigurationTests { @Test public void jndiSessionAvailable() { Session session = configureJndiSession("foo"); - this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo") - .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:foo").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 @@ -183,36 +167,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"); }); } @@ -220,11 +199,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"); }); } @@ -232,12 +210,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(); }); } @@ -245,12 +220,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 51d3df3d6cb..93216ff47be 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,38 +43,32 @@ 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.withPropertyValues("spring.data.mongodb.host:localhost") - .withUserConfiguration(OptionsConfig.class) - .run((context) -> assertThat(context.getBean(MongoClient.class) - .getMongoClientOptions().getSocketTimeout()).isEqualTo(300)); + .withUserConfiguration(OptionsConfig.class).run((context) -> assertThat( + context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()).isEqualTo(300)); } @Test public void optionsAddedButNoHost() { - this.contextRunner - .withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") - .withUserConfiguration(OptionsConfig.class) - .run((context) -> assertThat(context.getBean(MongoClient.class) - .getMongoClientOptions().getSocketTimeout()).isEqualTo(300)); + this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") + .withUserConfiguration(OptionsConfig.class).run((context) -> assertThat( + context.getBean(MongoClient.class).getMongoClientOptions().getSocketTimeout()).isEqualTo(300)); } @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); MongoClient mongo = context.getBean(MongoClient.class); MongoClientOptions options = mongo.getMongoClientOptions(); assertThat(options.isSslEnabled()).isTrue(); - assertThat(options.getSocketFactory()) - .isSameAs(context.getBean("mySocketFactory")); + assertThat(options.getSocketFactory()).isSameAs(context.getBean("mySocketFactory")); }); } @@ -93,8 +87,7 @@ public class MongoAutoConfigurationTests { @Bean public MongoClientOptions mongoClientOptions() { - return MongoClientOptions.builder().sslEnabled(true) - .socketFactory(mySocketFactory()).build(); + return MongoClientOptions.builder().sslEnabled(true).socketFactory(mySocketFactory()).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 4e0ac13b30e..334ad60d04f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 class MongoClientFactoryTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); MongoClient client = createMongoClient(properties); - assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", - "test"); + assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "test"); } @Test @@ -82,8 +81,7 @@ public class MongoClientFactoryTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); MongoClient client = createMongoClient(properties); - assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", - "foo"); + assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "foo"); } @Test @@ -93,15 +91,13 @@ public class MongoClientFactoryTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); MongoClient client = createMongoClient(properties); - assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", - "foo"); + assertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "foo"); } @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); @@ -127,26 +123,23 @@ 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); } private List extractServerAddresses(MongoClient client) { Cluster cluster = (Cluster) ReflectionTestUtils.getField(client, "cluster"); - ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils - .getField(cluster, "settings"); + ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils.getField(cluster, "settings"); return clusterSettings.getHosts(); } - 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 467ec9e6a4c..17206fcdfd9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,38 +78,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 @@ -118,8 +107,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 = extractServerAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345); @@ -130,8 +118,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 = extractServerAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "localhost", 27017); @@ -141,8 +128,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 = extractServerAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345); @@ -151,8 +137,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 = extractServerAddresses(client); assertThat(allAddresses).hasSize(1); assertServerAddress(allAddresses.get(0), "localhost", 27017); @@ -160,13 +145,11 @@ public class MongoPropertiesTests { private List extractServerAddresses(MongoClient client) { Cluster cluster = (Cluster) ReflectionTestUtils.getField(client, "cluster"); - ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils - .getField(cluster, "settings"); + ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils.getField(cluster, "settings"); return clusterSettings.getHosts(); } - 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 15f7cc9414c..6a5e891b179 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,46 +47,38 @@ 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( - context.getBean(MongoClient.class).getSettings() - .getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) - .isEqualTo(300)); + .run((context) -> assertThat(context.getBean(MongoClient.class).getSettings().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(context.getBean(MongoClient.class) - .getSettings().getReadPreference()) - .isEqualTo(ReadPreference.nearest())); + .run((context) -> assertThat(context.getBean(MongoClient.class).getSettings().getReadPreference()) + .isEqualTo(ReadPreference.nearest())); } @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); MongoClient mongo = context.getBean(MongoClient.class); MongoClientSettings settings = mongo.getSettings(); assertThat(settings.getApplicationName()).isEqualTo("test-config"); - assertThat(settings.getStreamFactoryFactory()) - .isSameAs(context.getBean("myStreamFactoryFactory")); + assertThat(settings.getStreamFactoryFactory()).isSameAs(context.getBean("myStreamFactoryFactory")); }); } @@ -94,21 +86,18 @@ public class MongoReactiveAutoConfigurationTests { public void nettyStreamFactoryFactoryIsConfiguredAutomatically() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(MongoClient.class); - assertThat(context.getBean(MongoClient.class).getSettings() - .getStreamFactoryFactory()) - .isInstanceOf(NettyStreamFactoryFactory.class); + assertThat(context.getBean(MongoClient.class).getSettings().getStreamFactoryFactory()) + .isInstanceOf(NettyStreamFactoryFactory.class); }); } @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); MongoClient client = context.getBean(MongoClient.class); - assertThat(client.getSettings().getApplicationName()) - .isEqualTo("overridden-name"); + assertThat(client.getSettings().getApplicationName()).isEqualTo("overridden-name"); assertThat(client.getSettings().getStreamFactoryFactory()) .isEqualTo(SimpleCustomizerConfig.streamFactoryFactory); }); @@ -120,9 +109,7 @@ public class MongoReactiveAutoConfigurationTests { @Bean public MongoClientSettings mongoClientSettings() { return MongoClientSettings.builder().readPreference(ReadPreference.nearest()) - .socketSettings(SocketSettings.builder() - .readTimeout(300, TimeUnit.SECONDS).build()) - .build(); + .socketSettings(SocketSettings.builder().readTimeout(300, TimeUnit.SECONDS).build()).build(); } } @@ -139,8 +126,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; } @@ -154,8 +140,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 bdde4c6176b..ff979718bf5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -127,8 +126,8 @@ public class ReactiveMongoClientFactoryTests { properties.setUsername("user"); properties.setPassword("secret".toCharArray()); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + this.thrown.expectMessage( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); createMongoClient(properties); } @@ -139,8 +138,8 @@ public class ReactiveMongoClientFactoryTests { properties.setHost("localhost"); properties.setPort(4567); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); + this.thrown.expectMessage( + "Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); createMongoClient(properties); } @@ -158,8 +157,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)); } @@ -168,8 +166,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)); } @@ -178,8 +175,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)); } @@ -188,11 +184,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) { @@ -206,14 +201,13 @@ public class ReactiveMongoClientFactoryTests { return settings.getCredential(); } - 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 d01fb9ab121..be8f7b50e87 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void customFeatures() { load("spring.mongodb.embedded.features=TEXT_SEARCH, SYNC_DELAY"); - assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()) - .contains(Feature.TEXT_SEARCH, Feature.SYNC_DELAY); + assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()).contains(Feature.TEXT_SEARCH, + Feature.SYNC_DELAY); } @Test @@ -80,8 +80,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(client.getAddress().getPort()).isEqualTo(mongoPort); } @@ -90,8 +89,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(client.getAddress().getPort()).isEqualTo(mongoPort); } @@ -99,8 +97,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(client.getAddress().getPort()).isEqualTo(mongoPort); } @@ -110,11 +107,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(); } } @@ -131,8 +126,7 @@ public class EmbeddedMongoAutoConfigurationTests { public void mongoWritesToCustomDatabaseDir() { File customDatabaseDir = new File("target/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(); } @@ -140,28 +134,23 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void customOpLogSizeIsAppliedToConfiguration() { 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"); } - 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 }"); 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 4b379be874b..8949432e6a9 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 @@ -51,8 +51,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Brian Clozel */ @RunWith(SpringRunner.class) -@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 @@ -60,22 +59,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 - @Import({ ReactiveWebServerFactoryAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @Import({ ReactiveWebServerFactoryAutoConfiguration.class, WebFluxAutoConfiguration.class, + HttpHandlerAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @Controller public static class Application { @@ -97,9 +95,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 e65fcb7c051..1a60830aae0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +84,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(); } @@ -119,9 +117,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"); @@ -137,8 +134,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 fe2b861ddc0..58435265f9d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 AnnotationConfigWebApplicationContext(); - 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 8c590534948..0ecaadc659f 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 @@ -40,8 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @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 @@ -49,32 +48,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 - @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 eff3f86af0e..d7d35f527d6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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,71 +109,55 @@ 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 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(); @@ -189,9 +169,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); @@ -202,12 +180,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"); }); @@ -215,20 +190,15 @@ 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); @@ -299,12 +269,11 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Configuration - 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); @@ -319,12 +288,10 @@ public abstract class AbstractJpaAutoConfigurationTests { } @Configuration - 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 3466821fcff..855456ff6dc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,64 +57,47 @@ 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 bean = context.getBean(JpaProperties.class); - Map hibernateProperties = bean - .getHibernateProperties(new HibernateSettings()); - assertThat(hibernateProperties.get("hibernate.ejb.naming_strategy")) - .isNull(); + Map hibernateProperties = bean.getHibernateProperties(new HibernateSettings()); + assertThat(hibernateProperties.get("hibernate.ejb.naming_strategy")).isNull(); }); } @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 defaultDatabaseForH2() { 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.H2); }); } @@ -133,8 +116,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/Hibernate2ndLevelCacheEhCacheIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheEhCacheIntegrationTests.java index df67c446f26..eb2486ebd50 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheEhCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheEhCacheIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.assertj.core.api.Assertions.assertThat; public class Hibernate2ndLevelCacheEhCacheIntegrationTests { 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); 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 3f66ecdf158..e74a257d140 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,25 +40,22 @@ 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 public void defaultDdlAutoForMysql() { // Set up environment so we get a MySQL database but don't require server to be // running... - this.contextRunner.withPropertyValues( - "spring.datasource.type:" - + org.apache.tomcat.jdbc.pool.DataSource.class.getName(), - "spring.datasource.database:mysql", - "spring.datasource.url:jdbc:mysql://localhost/nonexistent", - "spring.jpa.database:MYSQL").run((context) -> { + this.contextRunner + .withPropertyValues("spring.datasource.type:" + org.apache.tomcat.jdbc.pool.DataSource.class.getName(), + "spring.datasource.database:mysql", "spring.datasource.url:jdbc:mysql://localhost/nonexistent", + "spring.jpa.database:MYSQL") + .run((context) -> { HibernateDefaultDdlAutoProvider ddlAutoProvider = new HibernateDefaultDdlAutoProvider( Collections.emptyList()); - assertThat(ddlAutoProvider - .getDefaultDdlAuto(context.getBean(DataSource.class))) - .isEqualTo("none"); + assertThat(ddlAutoProvider.getDefaultDdlAuto(context.getBean(DataSource.class))).isEqualTo("none"); }); } @@ -68,9 +65,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"); }); } @@ -79,8 +74,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"); @@ -92,12 +86,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 4922f3123fc..ca73730d780 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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); @@ -83,10 +82,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"); }); } @@ -95,24 +92,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 @@ -128,60 +120,48 @@ 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 jtaDefaultPlatform() { - contextRunner() - .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .run((context) -> { - Map jpaPropertyMap = context - .getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaPropertyMap.get("hibernate.transaction.jta.platform")) - .isInstanceOf(SpringJtaPlatform.class); - }); + contextRunner().withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)).run((context) -> { + Map jpaPropertyMap = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaPropertyMap.get("hibernate.transaction.jta.platform")).isInstanceOf(SpringJtaPlatform.class); + }); } @Test public void jtaCustomPlatform() { contextRunner() .withPropertyValues( - "spring.jpa.properties.hibernate.transaction.jta.platform:" - + TestJtaPlatform.class.getName()) - .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .run((context) -> { - Map jpaPropertyMap = context - .getBean(LocalContainerEntityManagerFactoryBean.class) + "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) + .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)).run((context) -> { + Map jpaPropertyMap = context.getBean(LocalContainerEntityManagerFactoryBean.class) .getJpaPropertyMap(); - assertThat((String) jpaPropertyMap - .get("hibernate.transaction.jta.platform")) - .isEqualTo(TestJtaPlatform.class.getName()); + assertThat((String) jpaPropertyMap.get("hibernate.transaction.jta.platform")) + .isEqualTo(TestJtaPlatform.class.getName()); }); } @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(); }); @@ -190,11 +170,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); }); @@ -202,71 +180,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"); @@ -275,34 +240,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 @@ -310,47 +265,34 @@ 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"); }); } @@ -361,8 +303,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(); @@ -404,10 +345,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); }; } @@ -449,8 +388,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()); 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 f47515dc197..014c39d6474 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,76 +68,62 @@ public class JpaPropertiesTests { @Test public void noCustomNamingStrategy() { this.contextRunner.run(assertJpaProperties((properties) -> { - Map hibernateProperties = properties - .getHibernateProperties(new HibernateSettings()); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); - assertThat(hibernateProperties).containsEntry( - "hibernate.physical_naming_strategy", + Map hibernateProperties = properties.getHibernateProperties(new HibernateSettings()); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + assertThat(hibernateProperties).containsEntry("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName()); - assertThat(hibernateProperties).containsEntry( - "hibernate.implicit_naming_strategy", + assertThat(hibernateProperties).containsEntry("hibernate.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(assertJpaProperties((properties) -> { Map hibernateProperties = properties .getHibernateProperties(new HibernateSettings()); assertThat(hibernateProperties).contains( - entry("hibernate.implicit_naming_strategy", - "com.example.Implicit"), - entry("hibernate.physical_naming_strategy", - "com.example.Physical")); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + entry("hibernate.implicit_naming_strategy", "com.example.Implicit"), + entry("hibernate.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(assertJpaProperties((properties) -> { Map hibernateProperties = properties .getHibernateProperties(new HibernateSettings()); // You can override them as we don't provide any default assertThat(hibernateProperties).contains( - entry("hibernate.implicit_naming_strategy", - "com.example.Implicit"), - entry("hibernate.physical_naming_strategy", - "com.example.Physical")); - assertThat(hibernateProperties) - .doesNotContainKeys("hibernate.ejb.naming_strategy"); + entry("hibernate.implicit_naming_strategy", "com.example.Implicit"), + entry("hibernate.physical_naming_strategy", "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); })); } @Test public void useNewIdGeneratorMappingsDefault() { this.contextRunner.run(assertJpaProperties((properties) -> { - Map hibernateProperties = properties - .getHibernateProperties(new HibernateSettings()); - assertThat(hibernateProperties).containsEntry( - AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); + Map hibernateProperties = properties.getHibernateProperties(new HibernateSettings()); + 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") + this.contextRunner.withPropertyValues("spring.jpa.hibernate.use-new-id-generator-mappings:false") .run(assertJpaProperties((properties) -> { Map hibernateProperties = properties .getHibernateProperties(new HibernateSettings()); - assertThat(hibernateProperties).containsEntry( - AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false"); + assertThat(hibernateProperties).containsEntry(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, + "false"); })); } @@ -160,20 +146,17 @@ public class JpaPropertiesTests { @Test 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); })); } @Test 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 @@ -184,18 +167,15 @@ public class JpaPropertiesTests { @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 assertJpaProperties((properties) -> { - Map hibernateProperties = properties.getHibernateProperties( - new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); - assertThat(hibernateProperties).containsEntry("hibernate.hbm2ddl.auto", - expectedDdlAuto); + Map hibernateProperties = properties + .getHibernateProperties(new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); + assertThat(hibernateProperties).containsEntry("hibernate.hbm2ddl.auto", expectedDdlAuto); verify(this.ddlAutoSupplier, never()).get(); }); } @@ -203,8 +183,7 @@ public class JpaPropertiesTests { @Test 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); })); } @@ -235,8 +214,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 bb532129ebe..36d57873307 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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,14 +144,11 @@ public class QuartzAutoConfigurationTests { @Test public void withConfiguredJobAndTrigger() { 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); this.output.expect(containsString("withConfiguredJobAndTrigger")); this.output.expect(containsString("jobDataValue")); @@ -177,20 +157,17 @@ public class QuartzAutoConfigurationTests { @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); @@ -200,12 +177,11 @@ 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"); + }); } @Import(ComponentThatUsesScheduler.class) @@ -219,14 +195,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(); } } @@ -242,11 +216,11 @@ public class QuartzAutoConfigurationTests { @Bean public Trigger fooTrigger() { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() - .withIntervalInSeconds(10).repeatForever(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10) + .repeatForever(); - return TriggerBuilder.newTrigger().forJob(fooJob()).withIdentity("fooTrigger") - .withSchedule(scheduleBuilder).build(); + return TriggerBuilder.newTrigger().forJob(fooJob()).withIdentity("fooTrigger").withSchedule(scheduleBuilder) + .build(); } } @@ -281,15 +255,13 @@ public class QuartzAutoConfigurationTests { @Bean public SchedulerFactoryBeanCustomizer customizer() { - return (schedulerFactoryBean) -> schedulerFactoryBean - .setSchedulerName("fooScheduler"); + return (schedulerFactoryBean) -> schedulerFactoryBean.setSchedulerName("fooScheduler"); } } @Configuration - protected static class MultipleDataSourceConfiguration - extends BaseQuartzConfiguration { + protected static class MultipleDataSourceConfiguration extends BaseQuartzConfiguration { @Bean @Primary @@ -329,8 +301,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 c19656ee43a..4f99845e82e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/security/jpa/JpaUserDetailsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/jpa/JpaUserDetailsTests.java index 93d0cc8f20d..12f18129b84 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 @@ -40,8 +40,7 @@ import org.springframework.test.context.junit4.SpringRunner; * @author Dave Syer */ @RunWith(SpringRunner.class) -@ContextConfiguration(classes = JpaUserDetailsTests.Main.class, - loader = SpringBootContextLoader.class) +@ContextConfiguration(classes = JpaUserDetailsTests.Main.class, loader = SpringBootContextLoader.class) @DirtiesContext public class JpaUserDetailsTests { @@ -54,8 +53,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 5e8ebd3e6d1..9ff56eaf47f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +67,19 @@ 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"); - assertThat(adaptedProvider.getUserInfoEndpoint().getUri()) - .isEqualTo("https://example.com/info"); - assertThat(adaptedProvider.getUserInfoEndpoint().getUserNameAttributeName()) - .isEqualTo("sub"); + assertThat(adaptedProvider.getUserInfoEndpoint().getUri()).isEqualTo("https://example.com/info"); + assertThat(adaptedProvider.getUserInfoEndpoint().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("scope"); assertThat(adapted.getClientName()).isEqualTo("clientName"); } @@ -100,25 +96,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"); assertThat(adaptedProvider.getUserInfoEndpoint().getUri()) .isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); - assertThat(adaptedProvider.getUserInfoEndpoint().getUserNameAttributeName()) - .isEqualTo(IdTokenClaimNames.SUB); - assertThat(adaptedProvider.getJwkSetUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); + assertThat(adaptedProvider.getUserInfoEndpoint().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}/login/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}/login/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); } @@ -140,25 +131,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"); assertThat(adaptedProvider.getUserInfoEndpoint().getUri()) .isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); - assertThat(adaptedProvider.getUserInfoEndpoint().getUserNameAttributeName()) - .isEqualTo(IdTokenClaimNames.SUB); - assertThat(adaptedProvider.getJwkSetUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); + assertThat(adaptedProvider.getUserInfoEndpoint().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.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("scope"); assertThat(adapted.getClientName()).isEqualTo("clientName"); } @@ -185,23 +171,19 @@ 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"); assertThat(adaptedProvider.getUserInfoEndpoint().getUri()) .isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); - assertThat(adaptedProvider.getJwkSetUri()) - .isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); + 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}/login/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}/login/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); } @@ -212,8 +194,7 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { Registration registration = new Registration(); properties.getRegistration().put("missing", registration); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Provider ID must be specified for client registration 'missing'"); + this.thrown.expectMessage("Provider ID must be specified for client registration 'missing'"); OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfigurationTests.java index 190787d2196..61d91cc3e23 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/OAuth2WebSecurityConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2WebSecurityConfigurationTests.java index b4f78bbe20e..262cc394163 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2WebSecurityConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2WebSecurityConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,109 +59,82 @@ public class OAuth2WebSecurityConfigurationTests { @Test public void securityConfigurerConfiguresOAuth2Login() { - this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> { - ClientRegistrationRepository expected = context - .getBean(ClientRegistrationRepository.class); + this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class).run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils - .getField(getAuthCodeFilters(context).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), - actual.findByRegistrationId("first"))).isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), - actual.findByRegistrationId("second"))).isTrue(); + .getField(getAuthCodeFilters(context).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) + this.contextRunner.withUserConfiguration(TestConfig.class, OAuth2WebSecurityConfiguration.class) .run((context) -> assertThat(getAuthCodeFilters(context)).isEmpty()); } @Test public void configurationRegistersAuthorizedClientServiceBean() { - this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> { - OAuth2AuthorizedClientService bean = context - .getBean(OAuth2AuthorizedClientService.class); + this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class).run((context) -> { + OAuth2AuthorizedClientService bean = context.getBean(OAuth2AuthorizedClientService.class); OAuth2AuthorizedClientService authorizedClientService = (OAuth2AuthorizedClientService) ReflectionTestUtils - .getField(getAuthCodeFilters(context).get(0), - "authorizedClientService"); + .getField(getAuthCodeFilters(context).get(0), "authorizedClientService"); assertThat(authorizedClientService).isEqualTo(bean); }); } @Test public void securityConfigurerBacksOffWhenOtherWebSecurityAdapterPresent() { - this.contextRunner.withUserConfiguration(TestWebSecurityConfigurerConfig.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { + this.contextRunner + .withUserConfiguration(TestWebSecurityConfigurerConfig.class, OAuth2WebSecurityConfiguration.class) + .run((context) -> { assertThat(getAuthCodeFilters(context)).isEmpty(); - assertThat(context).getBean(OAuth2AuthorizedClientService.class) - .isNotNull(); + assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); }); } @Test public void authorizedClientServiceBeanIsConditionalOnMissingBean() { - this.contextRunner - .withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> { - OAuth2AuthorizedClientService bean = context - .getBean(OAuth2AuthorizedClientService.class); + this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, + OAuth2WebSecurityConfiguration.class).run((context) -> { + OAuth2AuthorizedClientService bean = context.getBean(OAuth2AuthorizedClientService.class); OAuth2AuthorizedClientService authorizedClientService = (OAuth2AuthorizedClientService) ReflectionTestUtils - .getField(getAuthCodeFilters(context).get(0), - "authorizedClientService"); + .getField(getAuthCodeFilters(context).get(0), "authorizedClientService"); assertThat(authorizedClientService).isEqualTo(bean); }); } @SuppressWarnings("unchecked") private List getAuthCodeFilters(AssertableApplicationContext 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 = (List) ReflectionTestUtils - .getField(filterChains.get(0), "filters"); - List oauth2Filters = filters.stream() - .filter((f) -> f instanceof OAuth2LoginAuthenticationFilter - || f instanceof OAuth2AuthorizationRequestRedirectFilter) - .collect(Collectors.toList()); - return oauth2Filters.stream() - .filter((f) -> f instanceof OAuth2LoginAuthenticationFilter) + List filters = (List) ReflectionTestUtils.getField(filterChains.get(0), "filters"); + List oauth2Filters = filters.stream().filter((f) -> f instanceof OAuth2LoginAuthenticationFilter + || f instanceof OAuth2AuthorizationRequestRedirectFilter).collect(Collectors.toList()); + return oauth2Filters.stream().filter((f) -> f instanceof OAuth2LoginAuthenticationFilter) .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; } @@ -183,23 +156,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", "http://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(); } @@ -218,8 +188,7 @@ public class OAuth2WebSecurityConfigurationTests { @Bean public OAuth2AuthorizedClientService testAuthorizedClientService( ClientRegistrationRepository clientRegistrationRepository) { - return new InMemoryOAuth2AuthorizedClientService( - clientRegistrationRepository); + return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); } } 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 b010eb071b6..79af51d6406 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 84eeaba6f17..44758b8c717 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 ae12a01bc0d..f1a7e74cd22 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,57 +48,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 @@ -117,15 +100,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); })); } @@ -142,10 +123,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 33f84ab8fb9..46208a6d62e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,8 +72,7 @@ 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"); } @@ -104,40 +103,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; } @@ -155,8 +149,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 bd26c2f02a1..9a421af6084 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 339383cdc3e..422316f9ae2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +60,8 @@ 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)); @Rule public OutputCapture outputCapture = new OutputCapture(); @@ -71,74 +70,56 @@ public class SecurityAutoConfigurationTests { 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( - FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 100)); + .withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(FilterRegistrationBean.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( - FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 100)); + this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()).isEqualTo(FilterRegistrationBean.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)); } @@ -149,53 +130,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); }); } @@ -221,8 +191,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 fb203aeb0de..d53dc354fd6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,25 +62,20 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests { context.register(Config.class); context.refresh(); int port = context.getWebServer().getPort(); - String password = this.outputCapture.toString() - .split("Using generated security password: ")[1].split("\n")[0] - .trim(); - new TestRestTemplate("user", password) - .getForEntity("http://localhost:" + port, Object.class); + String password = this.outputCapture.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 - @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 dd8f3f5c684..384922fae26 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +51,10 @@ public class SecurityFilterAutoConfigurationTests { } @Configuration - @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 c063c34b8f8..3d5d3332aa3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 e660ab35885..fa6b017b354 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); } @@ -104,10 +103,8 @@ public class StaticResourceRequestTests { return assertThat(new RequestMatcherAssert(context, matcher)); } - private RequestMatcherAssert assertMatcher(RequestMatcher matcher, - ServerProperties serverProperties) { - DispatcherServletPath dispatcherServletPath = () -> serverProperties.getServlet() - .getPath(); + private RequestMatcherAssert assertMatcher(RequestMatcher matcher, ServerProperties serverProperties) { + DispatcherServletPath dispatcherServletPath = () -> serverProperties.getServlet().getPath(); StaticWebApplicationContext context = new StaticWebApplicationContext(); context.registerBean(ServerProperties.class, () -> serverProperties); context.registerBean(DispatcherServletPath.class, () -> dispatcherServletPath); @@ -134,8 +131,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) { @@ -147,8 +143,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) { @@ -157,9 +152,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 e9532816fa7..b4e1ce7923d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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)); @Rule public OutputCapture outputCapture = new OutputCapture(); @@ -64,67 +64,49 @@ public class UserDetailsServiceAutoConfigurationTests { public void testDefaultUsernamePassword() { this.contextRunner.run((context) -> { UserDetailsService manager = context.getBean(UserDetailsService.class); - assertThat(this.outputCapture.toString()) - .contains("Using generated security password:"); + assertThat(this.outputCapture.toString()).contains("Using generated security password:"); assertThat(manager.loadUserByUsername("user")).isNotNull(); }); } @Test public void defaultUserNotCreatedIfAuthenticationManagerBeanPresent() { - this.contextRunner - .withUserConfiguration(TestAuthenticationManagerConfiguration.class) - .run((context) -> { - AuthenticationManager manager = context - .getBean(AuthenticationManager.class); - assertThat(manager).isEqualTo(context.getBean( - TestAuthenticationManagerConfiguration.class).authenticationManager); - assertThat(this.outputCapture.toString()) - .doesNotContain("Using generated security password: "); - TestingAuthenticationToken token = new TestingAuthenticationToken( - "foo", "bar"); - assertThat(manager.authenticate(token)).isNotNull(); - }); + this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> { + AuthenticationManager manager = context.getBean(AuthenticationManager.class); + assertThat(manager) + .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); + assertThat(this.outputCapture.toString()).doesNotContain("Using generated security password: "); + TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); + assertThat(manager.authenticate(token)).isNotNull(); + }); } @Test public void defaultUserNotCreatedIfUserDetailsServiceBeanPresent() { - this.contextRunner - .withUserConfiguration(TestUserDetailsServiceConfiguration.class) - .run((context) -> { - UserDetailsService userDetailsService = context - .getBean(UserDetailsService.class); - assertThat(this.outputCapture.toString()) - .doesNotContain("Using generated security password: "); - assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull(); - }); + this.contextRunner.withUserConfiguration(TestUserDetailsServiceConfiguration.class).run((context) -> { + UserDetailsService userDetailsService = context.getBean(UserDetailsService.class); + assertThat(this.outputCapture.toString()).doesNotContain("Using generated security password: "); + assertThat(userDetailsService.loadUserByUsername("foo")).isNotNull(); + }); } @Test public void defaultUserNotCreatedIfAuthenticationProviderBeanPresent() { - this.contextRunner - .withUserConfiguration(TestAuthenticationProviderConfiguration.class) - .run((context) -> { - AuthenticationProvider provider = context - .getBean(AuthenticationProvider.class); - assertThat(this.outputCapture.toString()) - .doesNotContain("Using generated security password: "); - TestingAuthenticationToken token = new TestingAuthenticationToken( - "foo", "bar"); - assertThat(provider.authenticate(token)).isNotNull(); - }); + this.contextRunner.withUserConfiguration(TestAuthenticationProviderConfiguration.class).run((context) -> { + AuthenticationProvider provider = context.getBean(AuthenticationProvider.class); + assertThat(this.outputCapture.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 @@ -145,29 +127,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() { - this.contextRunner - .withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) + this.contextRunner.withUserConfiguration(TestConfigWithAuthenticationManagerBuilder.class) .run(((context) -> assertThat(this.outputCapture.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); })); } @@ -180,8 +155,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; } @@ -192,8 +166,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()); } } @@ -245,11 +218,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 a96d48140ef..9ef799e7da2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,20 +62,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 33554d70c5b..99487b155a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -43,23 +43,20 @@ public abstract class AbstractSessionAutoConfigurationTests { } protected Integer getSessionTimeout(SessionRepository sessionRepository) { - return (Integer) new DirectFieldAccessor(sessionRepository) - .getPropertyValue("defaultMaxInactiveInterval"); + return (Integer) new DirectFieldAccessor(sessionRepository).getPropertyValue("defaultMaxInactiveInterval"); } protected > T validateSessionRepository( 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); } protected Integer getSessionTimeout(ReactiveSessionRepository sessionRepository) { - return (Integer) new DirectFieldAccessor(sessionRepository) - .getPropertyValue("defaultMaxInactiveInterval"); + return (Integer) new DirectFieldAccessor(sessionRepository).getPropertyValue("defaultMaxInactiveInterval"); } } 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 5b8234a59fa..bc0d356678b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 6ff52d686b2..64b4766aaa8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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)); @@ -48,47 +47,38 @@ 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); - assertThat(new DirectFieldAccessor(repository) - .getPropertyValue("collectionName")).isEqualTo(collectionName); + ReactiveMongoOperationsSessionRepository repository = validateSessionRepository(context, + ReactiveMongoOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("collectionName")) + .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 a33eb37995c..747e79ef346 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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)); @@ -48,43 +47,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); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("namespace")) - .isEqualTo(namespace); - assertThat(new DirectFieldAccessor(repository) - .getPropertyValue("redisFlushMode")).isEqualTo(flushMode); + ReactiveRedisOperationsSessionRepository repository = validateSessionRepository(context, + ReactiveRedisOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("namespace")).isEqualTo(namespace); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("redisFlushMode")).isEqualTo(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 43ae9c18f5d..23ef2693583 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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)) @@ -53,17 +52,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); } @@ -75,28 +71,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(new DirectFieldAccessor(repository) - .getPropertyValue("hazelcastFlushMode")) - .isEqualTo(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(new DirectFieldAccessor(repository).getPropertyValue("hazelcastFlushMode")) + .isEqualTo(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 d208603e937..d0a1d18f7c2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 4c54a739fa0..62b9a4aca4d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,106 +46,93 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Vedran Pavic * @author Stephane Nicoll */ -public class SessionAutoConfigurationJdbcTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { @Rule public ExpectedException thrown = ExpectedException.none(); 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); } private void validateDefaultConfig(AssertableWebApplicationContext context) { JdbcOperationsSessionRepository repository = validateSessionRepository(context, JdbcOperationsSessionRepository.class); - assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) - .isEqualTo("SPRING_SESSION"); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")).isEqualTo("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(new DirectFieldAccessor(configuration).getPropertyValue("cleanupCron")) - .isEqualTo("0 * * * * *"); + assertThat(new DirectFieldAccessor(configuration).getPropertyValue("cleanupCron")).isEqualTo("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(new DirectFieldAccessor(repository) - .getPropertyValue("tableName")).isEqualTo("SPRING_SESSION"); - assertThat(context.getBean(JdbcSessionProperties.class) - .getInitializeSchema()) - .isEqualTo(DataSourceInitializationMode.NEVER); + this.contextRunner + .withPropertyValues("spring.session.store-type=jdbc", "spring.session.jdbc.initialize-schema=never") + .run((context) -> { + JdbcOperationsSessionRepository repository = validateSessionRepository(context, + JdbcOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) + .isEqualTo("SPRING_SESSION"); + assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) + .isEqualTo(DataSourceInitializationMode.NEVER); this.thrown.expect(BadSqlGrammarException.class); - context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION"); + 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(new DirectFieldAccessor(repository) - .getPropertyValue("tableName")).isEqualTo("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(new DirectFieldAccessor(repository).getPropertyValue("tableName")).isEqualTo("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(new DirectFieldAccessor(configuration) - .getPropertyValue("cleanupCron")).isEqualTo("0 0 12 * * *"); + assertThat(new DirectFieldAccessor(configuration).getPropertyValue("cleanupCron")) + .isEqualTo("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 d1ee2683b9a..1a5054dc055 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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)); @@ -48,8 +47,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")); } @@ -58,10 +56,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")); } @@ -69,21 +65,18 @@ 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(new DirectFieldAccessor(repository) - .getPropertyValue("collectionName")).isEqualTo(collectionName); + MongoOperationsSessionRepository repository = validateSessionRepository(context, + MongoOperationsSessionRepository.class); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("collectionName")) + .isEqualTo(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 eef93b7f4bf..8ee81056d45 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.assertj.core.api.Assertions.assertThat; * @author Stephane Nicoll * @author Vedran Pavic */ -public class SessionAutoConfigurationRedisTests - extends AbstractSessionAutoConfigurationTests { +public class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfigurationTests { @ClassRule public static RedisContainer redis = new RedisContainer(); @@ -54,52 +53,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(new DirectFieldAccessor(repository) - .getPropertyValue("redisFlushMode")).isEqualTo(flushMode); + RedisOperationsSessionRepository repository = validateSessionRepository(context, + RedisOperationsSessionRepository.class); + assertThat(repository.getSessionCreatedChannelPrefix()).isEqualTo(sessionCreatedChannelPrefix); + assertThat(new DirectFieldAccessor(repository).getPropertyValue("redisFlushMode")).isEqualTo(flushMode); SpringBootRedisHttpSessionConfiguration configuration = context .getBean(SpringBootRedisHttpSessionConfiguration.class); - assertThat(new DirectFieldAccessor(configuration) - .getPropertyValue("cleanupCron")).isEqualTo(cleanupCron); + assertThat(new DirectFieldAccessor(configuration).getPropertyValue("cleanupCron")).isEqualTo(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 3190142de56..10cc2cceaab 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,91 +61,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); }); } @@ -154,14 +134,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); }); } @@ -169,26 +145,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); }); } @@ -196,53 +163,39 @@ 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()); } @Configuration @@ -263,8 +216,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration @EnableSpringHttpSession - static class UserProvidedCookieSerializerConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedCookieSerializerConfiguration extends SessionRepositoryConfiguration { @Bean public DefaultCookieSerializer myCookieSerializer() { @@ -275,8 +227,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration @EnableSpringHttpSession - static class UserProvidedCookieHttpSessionStrategyConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedCookieHttpSessionStrategyConfiguration extends SessionRepositoryConfiguration { @Bean public CookieHttpSessionIdResolver httpSessionStrategy() { @@ -287,8 +238,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration @EnableSpringHttpSession - static class UserProvidedHeaderHttpSessionStrategyConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedHeaderHttpSessionStrategyConfiguration extends SessionRepositoryConfiguration { @Bean public HeaderHttpSessionIdResolver httpSessionStrategy() { @@ -299,8 +249,7 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat @Configuration @EnableSpringHttpSession - static class UserProvidedCustomHttpSessionStrategyConfiguration - extends SessionRepositoryConfiguration { + static class UserProvidedCustomHttpSessionStrategyConfiguration extends SessionRepositoryConfiguration { @Bean public HttpSessionIdResolver httpSessionStrategy() { 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 fbb2fe3d81d..5e2fbb21497 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,7 @@ public class TemplateAvailabilityProvidersTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - this.providers = new TemplateAvailabilityProviders( - Collections.singleton(this.provider)); + this.providers = new TemplateAvailabilityProviders(Collections.singleton(this.provider)); } @Test @@ -78,8 +77,7 @@ 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(); } @@ -93,8 +91,7 @@ public class TemplateAvailabilityProvidersTests { @Test public void createWhenUsingClassLoaderShouldLoadProviders() { - TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders( - this.classLoader); + TemplateAvailabilityProviders providers = new TemplateAvailabilityProviders(this.classLoader); assertThat(providers.getProviders()).isNotEmpty(); } @@ -102,8 +99,7 @@ public class TemplateAvailabilityProvidersTests { public void createWhenProvidersIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Providers must not be null"); - new TemplateAvailabilityProviders( - (Collection) null); + new TemplateAvailabilityProviders((Collection) null); } @Test @@ -124,24 +120,21 @@ public class TemplateAvailabilityProvidersTests { public void getProviderWhenViewIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("View must not be null"); - this.providers.getProvider(null, this.environment, this.classLoader, - this.resourceLoader); + this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader); } @Test public void getProviderWhenEnvironmentIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Environment must not be null"); - this.providers.getProvider(this.view, null, this.classLoader, - this.resourceLoader); + this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader); } @Test public void getProviderWhenClassLoaderIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ClassLoader must not be null"); - this.providers.getProvider(this.view, this.environment, null, - this.resourceLoader); + this.providers.getProvider(this.view, this.environment, null, this.resourceLoader); } @Test @@ -153,56 +146,49 @@ public class TemplateAvailabilityProvidersTests { @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 f7573a15fea..bebada38a99 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 bd718f4347c..a9d23a8c982 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +82,16 @@ public class ThymeleafReactiveAutoConfigurationTests { load(BaseConfiguration.class, "spring.thymeleaf.encoding:UTF-16"); ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class); assertThat(resolver instanceof SpringResourceTemplateResolver).isTrue(); - assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()) - .isEqualTo("UTF-16"); - ThymeleafReactiveViewResolver views = this.context - .getBean(ThymeleafReactiveViewResolver.class); + assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()).isEqualTo("UTF-16"); + ThymeleafReactiveViewResolver views = this.context.getBean(ThymeleafReactiveViewResolver.class); assertThat(views.getDefaultCharset().name()).isEqualTo("UTF-16"); } @Test public void overrideMediaTypes() { - load(BaseConfiguration.class, - "spring.thymeleaf.reactive.media-types:text/html,text/plain"); - ThymeleafReactiveViewResolver views = this.context - .getBean(ThymeleafReactiveViewResolver.class); - assertThat(views.getSupportedMediaTypes()).contains(MediaType.TEXT_HTML, - MediaType.TEXT_PLAIN); + load(BaseConfiguration.class, "spring.thymeleaf.reactive.media-types:text/html,text/plain"); + ThymeleafReactiveViewResolver views = this.context.getBean(ThymeleafReactiveViewResolver.class); + assertThat(views.getSupportedMediaTypes()).contains(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN); } @Test @@ -109,72 +104,60 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void overrideViewNames() { load(BaseConfiguration.class, "spring.thymeleaf.viewNames:foo,bar"); - ThymeleafReactiveViewResolver views = this.context - .getBean(ThymeleafReactiveViewResolver.class); + ThymeleafReactiveViewResolver views = this.context.getBean(ThymeleafReactiveViewResolver.class); assertThat(views.getViewNames()).isEqualTo(new String[] { "foo", "bar" }); } @Test public void overrideMaxChunkSize() { load(BaseConfiguration.class, "spring.thymeleaf.reactive.maxChunkSize:8192"); - ThymeleafReactiveViewResolver views = this.context - .getBean(ThymeleafReactiveViewResolver.class); + ThymeleafReactiveViewResolver views = this.context.getBean(ThymeleafReactiveViewResolver.class); assertThat(views.getResponseMaxChunkSizeBytes()).isEqualTo(Integer.valueOf(8192)); } @Test public void overrideFullModeViewNames() { - load(BaseConfiguration.class, - "spring.thymeleaf.reactive.fullModeViewNames:foo,bar"); - ThymeleafReactiveViewResolver views = this.context - .getBean(ThymeleafReactiveViewResolver.class); + load(BaseConfiguration.class, "spring.thymeleaf.reactive.fullModeViewNames:foo,bar"); + ThymeleafReactiveViewResolver views = this.context.getBean(ThymeleafReactiveViewResolver.class); assertThat(views.getFullModeViewNames()).isEqualTo(new String[] { "foo", "bar" }); } @Test public void overrideChunkedModeViewNames() { - load(BaseConfiguration.class, - "spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar"); - ThymeleafReactiveViewResolver views = this.context - .getBean(ThymeleafReactiveViewResolver.class); - assertThat(views.getChunkedModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" }); + load(BaseConfiguration.class, "spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar"); + ThymeleafReactiveViewResolver views = this.context.getBean(ThymeleafReactiveViewResolver.class); + assertThat(views.getChunkedModeViewNames()).isEqualTo(new String[] { "foo", "bar" }); } @Test public void overrideEnableSpringElCompiler() { load(BaseConfiguration.class, "spring.thymeleaf.enable-spring-el-compiler:true"); - assertThat(this.context.getBean(SpringWebFluxTemplateEngine.class) - .getEnableSpringELCompiler()).isTrue(); + assertThat(this.context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()).isTrue(); } @Test public void enableSpringElCompilerIsDisabledByDefault() { load(BaseConfiguration.class); - assertThat(this.context.getBean(SpringWebFluxTemplateEngine.class) - .getEnableSpringELCompiler()).isFalse(); + assertThat(this.context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()).isFalse(); } @Test public void templateLocationDoesNotExist() { - load(BaseConfiguration.class, - "spring.thymeleaf.prefix:classpath:/no-such-directory/"); + load(BaseConfiguration.class, "spring.thymeleaf.prefix:classpath:/no-such-directory/"); this.output.expect(containsString("Cannot find template location")); } @Test public void templateLocationEmpty() { new File("target/test-classes/templates/empty-directory").mkdir(); - load(BaseConfiguration.class, - "spring.thymeleaf.prefix:classpath:/templates/empty-directory/"); + load(BaseConfiguration.class, "spring.thymeleaf.prefix:classpath:/templates/empty-directory/"); this.output.expect(not(containsString("Cannot find template location"))); } @Test public void useDataDialect() { load(BaseConfiguration.class); - ISpringWebFluxTemplateEngine engine = this.context - .getBean(ISpringWebFluxTemplateEngine.class); + ISpringWebFluxTemplateEngine engine = this.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(""); @@ -183,8 +166,7 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void useJava8TimeDialect() { load(BaseConfiguration.class); - ISpringWebFluxTemplateEngine engine = this.context - .getBean(ISpringWebFluxTemplateEngine.class); + ISpringWebFluxTemplateEngine engine = this.context.getBean(ISpringWebFluxTemplateEngine.class); Context attrs = new Context(Locale.UK); String result = engine.process("java8time-dialect", attrs).trim(); assertThat(result).isEqualTo("2015-11-24"); @@ -193,8 +175,7 @@ public class ThymeleafReactiveAutoConfigurationTests { @Test public void renderTemplate() { load(BaseConfiguration.class); - ISpringWebFluxTemplateEngine engine = this.context - .getBean(ISpringWebFluxTemplateEngine.class); + ISpringWebFluxTemplateEngine engine = this.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"); @@ -204,8 +185,7 @@ public class ThymeleafReactiveAutoConfigurationTests { public void layoutDialectCanBeCustomized() { load(LayoutDialectConfiguration.class); LayoutDialect layoutDialect = this.context.getBean(LayoutDialect.class); - assertThat(ReflectionTestUtils.getField(layoutDialect, "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class); + assertThat(ReflectionTestUtils.getField(layoutDialect, "sortingStrategy")).isInstanceOf(GroupingStrategy.class); } private void load(Class config, String... envVariables) { @@ -219,8 +199,7 @@ public class ThymeleafReactiveAutoConfigurationTests { } @Configuration - @ImportAutoConfiguration({ ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected static class BaseConfiguration { } 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 e313cb896e0..17674900122 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ThymeleafServletAutoConfigurationTests { @Test public void createFromConfigClass() { - load(BaseConfiguration.class, "spring.thymeleaf.mode:HTML", - "spring.thymeleaf.suffix:"); + load(BaseConfiguration.class, "spring.thymeleaf.mode:HTML", "spring.thymeleaf.suffix:"); TemplateEngine engine = this.context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); String result = engine.process("template.html", attrs).trim(); @@ -98,8 +97,7 @@ public class ThymeleafServletAutoConfigurationTests { load(BaseConfiguration.class, "spring.thymeleaf.encoding:UTF-16"); ITemplateResolver resolver = this.context.getBean(ITemplateResolver.class); assertThat(resolver instanceof SpringResourceTemplateResolver).isTrue(); - assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()) - .isEqualTo("UTF-16"); + assertThat(((SpringResourceTemplateResolver) resolver).getCharacterEncoding()).isEqualTo("UTF-16"); ThymeleafViewResolver views = this.context.getBean(ThymeleafViewResolver.class); assertThat(views.getCharacterEncoding()).isEqualTo("UTF-16"); assertThat(views.getContentType()).isEqualTo("text/html;charset=UTF-16"); @@ -122,41 +120,36 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void overrideEnableSpringElCompiler() { load(BaseConfiguration.class, "spring.thymeleaf.enable-spring-el-compiler:true"); - assertThat(this.context.getBean(SpringTemplateEngine.class) - .getEnableSpringELCompiler()).isTrue(); + assertThat(this.context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()).isTrue(); } @Test public void enableSpringElCompilerIsDisabledByDefault() { load(BaseConfiguration.class); - assertThat(this.context.getBean(SpringTemplateEngine.class) - .getEnableSpringELCompiler()).isFalse(); + assertThat(this.context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()).isFalse(); } @Test public void templateLocationDoesNotExist() { - load(BaseConfiguration.class, - "spring.thymeleaf.prefix:classpath:/no-such-directory/"); + load(BaseConfiguration.class, "spring.thymeleaf.prefix:classpath:/no-such-directory/"); this.output.expect(containsString("Cannot find template location")); } @Test public void templateLocationEmpty() { new File("target/test-classes/templates/empty-directory").mkdir(); - load(BaseConfiguration.class, - "spring.thymeleaf.prefix:classpath:/templates/empty-directory/"); + load(BaseConfiguration.class, "spring.thymeleaf.prefix:classpath:/templates/empty-directory/"); } @Test public void createLayoutFromConfigClass() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.register(ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); + context.register(ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); MockServletContext servletContext = new MockServletContext(); context.setServletContext(servletContext); context.refresh(); - 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); @@ -197,13 +190,10 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void renderNonWebAppTemplate() { try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext( - ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class)) { - assertThat(customContext.getBeanNamesForType(ViewResolver.class).length) - .isEqualTo(0); + ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) { + assertThat(customContext.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0); TemplateEngine engine = customContext.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"); } @@ -218,10 +208,8 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() { load(BaseConfiguration.class, "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)); } @@ -230,14 +218,11 @@ public class ThymeleafServletAutoConfigurationTests { @SuppressWarnings("rawtypes") public void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 - load(FilterRegistrationConfiguration.class, - "spring.resources.chain.enabled:true"); - Map beans = this.context - .getBeansOfType(FilterRegistrationBean.class); + load(FilterRegistrationConfiguration.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)); } @@ -246,16 +231,14 @@ public class ThymeleafServletAutoConfigurationTests { public void layoutDialectCanBeCustomized() { load(LayoutDialectConfiguration.class); LayoutDialect layoutDialect = this.context.getBean(LayoutDialect.class); - assertThat(ReflectionTestUtils.getField(layoutDialect, "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class); + assertThat(ReflectionTestUtils.getField(layoutDialect, "sortingStrategy")).isInstanceOf(GroupingStrategy.class); } @Test public void cachingCanBeDisabled() { load(BaseConfiguration.class, "spring.thymeleaf.cache:false"); assertThat(this.context.getBean(ThymeleafViewResolver.class).isCache()).isFalse(); - SpringResourceTemplateResolver templateResolver = this.context - .getBean(SpringResourceTemplateResolver.class); + SpringResourceTemplateResolver templateResolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(templateResolver.isCacheable()).isFalse(); } @@ -267,8 +250,7 @@ public class ThymeleafServletAutoConfigurationTests { } @Configuration - @ImportAutoConfiguration({ ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class }) + @ImportAutoConfiguration({ ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) static class BaseConfiguration { } @@ -290,8 +272,7 @@ public class ThymeleafServletAutoConfigurationTests { @Bean public FilterRegistrationBean filterRegisration() { - return new FilterRegistrationBean( - new OrderedCharacterEncodingFilter()); + return new FilterRegistrationBean(new OrderedCharacterEncodingFilter()); } } 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 15c62aeef67..4b68d18f623 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 60d2f04a2ae..f18aac68622 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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) { @@ -217,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 bbfa2f18e02..f4da2538baf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 834bc7fbae6..e5c55aa0395 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +96,8 @@ public class JtaAutoConfigurationTests { @Test public void customPlatformTransactionManager() { - this.context = new AnnotationConfigApplicationContext( - CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); + this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.class, + JtaAutoConfiguration.class); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean(JtaTransactionManager.class); } @@ -110,14 +110,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); @@ -130,8 +128,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); @@ -142,8 +139,7 @@ public class JtaAutoConfigurationTests { @Test public void narayanaSanityCheck() { - this.context = new AnnotationConfigApplicationContext(JtaProperties.class, - NarayanaJtaConfiguration.class); + this.context = new AnnotationConfigApplicationContext(JtaProperties.class, NarayanaJtaConfiguration.class); this.context.getBean(NarayanaConfigurationBean.class); this.context.getBean(UserTransaction.class); this.context.getBean(TransactionManager.class); @@ -156,33 +152,27 @@ public class JtaAutoConfigurationTests { @Test public void defaultBitronixServerId() throws UnknownHostException { - this.context = new AnnotationConfigApplicationContext( - JtaPropertiesConfiguration.class, BitronixJtaConfiguration.class); - String serverId = this.context.getBean(bitronix.tm.Configuration.class) - .getServerId(); + this.context = new AnnotationConfigApplicationContext(JtaPropertiesConfiguration.class, + 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); - this.context.register(JtaPropertiesConfiguration.class, - BitronixJtaConfiguration.class); + TestPropertyValues.of("spring.jta.transactionManagerId:custom").applyTo(this.context); + this.context.register(JtaPropertiesConfiguration.class, 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() { this.context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.jta.logDir:target/transaction-logs") - .applyTo(this.context); - this.context.register(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class); + TestPropertyValues.of("spring.jta.logDir:target/transaction-logs").applyTo(this.context); + this.context.register(JtaPropertiesConfiguration.class, AtomikosJtaConfiguration.class); this.context.refresh(); File epochFile = new File("target/transaction-logs/tmlog0.log"); @@ -192,15 +182,12 @@ 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); - this.context.register(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class, PoolConfiguration.class); + TestPropertyValues.of("spring.jta.atomikos.connectionfactory.minPoolSize:5", + "spring.jta.atomikos.connectionfactory.maxPoolSize:10").applyTo(this.context); + this.context.register(JtaPropertiesConfiguration.class, 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); } @@ -208,15 +195,12 @@ 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); - this.context.register(JtaPropertiesConfiguration.class, - BitronixJtaConfiguration.class, PoolConfiguration.class); + TestPropertyValues.of("spring.jta.bitronix.connectionfactory.minPoolSize:5", + "spring.jta.bitronix.connectionfactory.maxPoolSize:10").applyTo(this.context); + this.context.register(JtaPropertiesConfiguration.class, 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); } @@ -225,14 +209,12 @@ 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(JtaPropertiesConfiguration.class, - AtomikosJtaConfiguration.class, PoolConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, 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); } @@ -241,14 +223,12 @@ 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(JtaPropertiesConfiguration.class, - BitronixJtaConfiguration.class, PoolConfiguration.class); + this.context.register(JtaPropertiesConfiguration.class, 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); } @@ -257,14 +237,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(); } @@ -273,14 +250,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(); } @@ -288,8 +262,8 @@ public class JtaAutoConfigurationTests { @Test public void narayanaRecoveryManagerBeanCanBeCustomized() { this.context = new AnnotationConfigApplicationContext(); - this.context.register(CustomNarayanaRecoveryManagerConfiguration.class, - JtaProperties.class, NarayanaJtaConfiguration.class); + this.context.register(CustomNarayanaRecoveryManagerConfiguration.class, JtaProperties.class, + NarayanaJtaConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(NarayanaRecoveryManagerBean.class)) .isInstanceOf(CustomNarayanaRecoveryManagerBean.class); @@ -315,8 +289,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); @@ -341,18 +314,15 @@ public class JtaAutoConfigurationTests { public static class CustomNarayanaRecoveryManagerConfiguration { @Bean - public NarayanaRecoveryManagerBean customRecoveryManagerBean( - RecoveryManagerService recoveryManagerService) { + public NarayanaRecoveryManagerBean customRecoveryManagerBean(RecoveryManagerService recoveryManagerService) { return new CustomNarayanaRecoveryManagerBean(recoveryManagerService); } } - static final class CustomNarayanaRecoveryManagerBean - extends NarayanaRecoveryManagerBean { + static final class CustomNarayanaRecoveryManagerBean extends NarayanaRecoveryManagerBean { - private CustomNarayanaRecoveryManagerBean( - RecoveryManagerService recoveryManagerService) { + private CustomNarayanaRecoveryManagerBean(RecoveryManagerService recoveryManagerService) { super(recoveryManagerService); } 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 d7b547d2cac..c95e5ce26c3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,8 +127,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); @@ -144,14 +144,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(); } @@ -169,8 +168,7 @@ public class ValidationAutoConfigurationTests { 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); this.thrown.expect(ConstraintViolationException.class); service.doSomething(2); @@ -178,11 +176,9 @@ public class ValidationAutoConfigurationTests { @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); this.thrown.expect(ConstraintViolationException.class); @@ -193,22 +189,18 @@ public class ValidationAutoConfigurationTests { 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.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); assertThat(this.context.getBean(Validator.class)) - .isNotSameAs(new DirectFieldAccessor(userMethodValidationPostProcessor) - .getPropertyValue("validator")); + .isNotSameAs(new DirectFieldAccessor(userMethodValidationPostProcessor).getPropertyValue("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 37eac5d3311..502f1c1777b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a2e01a3ee60..b25bf16389c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 675bf8317b5..fe012168e8c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ValidatorAdapterTests { public void wrapLocalValidatorFactoryBean() { ValidatorAdapter wrapper = load(LocalValidatorFactoryBeanConfig.class); assertThat(wrapper.supports(SampleData.class)).isTrue(); - MapBindingResult errors = new MapBindingResult(new HashMap(), - "test"); + MapBindingResult errors = new MapBindingResult(new HashMap(), "test"); wrapper.validate(new SampleData(40), errors); assertThat(errors.getErrorCount()).isEqualTo(1); } @@ -66,8 +65,7 @@ public class ValidatorAdapterTests { @Test public void wrapperInvokesCallbackOnNonManagedBean() { load(NonManagedBeanConfig.class); - LocalValidatorFactoryBean validator = this.context - .getBean(NonManagedBeanConfig.class).validator; + LocalValidatorFactoryBean validator = this.context.getBean(NonManagedBeanConfig.class).validator; verify(validator, times(1)).setApplicationContext(any(ApplicationContext.class)); verify(validator, times(1)).afterPropertiesSet(); verify(validator, never()).destroy(); @@ -79,8 +77,7 @@ public class ValidatorAdapterTests { @Test public void wrapperDoesNotInvokeCallbackOnManagedBean() { load(ManagedBeanConfig.class); - LocalValidatorFactoryBean validator = this.context - .getBean(ManagedBeanConfig.class).validator; + LocalValidatorFactoryBean validator = this.context.getBean(ManagedBeanConfig.class).validator; verify(validator, never()).setApplicationContext(any(ApplicationContext.class)); verify(validator, never()).afterPropertiesSet(); verify(validator, never()).destroy(); @@ -115,8 +112,7 @@ public class ValidatorAdapterTests { @Configuration static class NonManagedBeanConfig { - private final LocalValidatorFactoryBean validator = mock( - LocalValidatorFactoryBean.class); + private final LocalValidatorFactoryBean validator = mock(LocalValidatorFactoryBean.class); @Bean public ValidatorAdapter wrapper() { @@ -128,8 +124,7 @@ public class ValidatorAdapterTests { @Configuration 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 2fd7883534b..c69ddd9d254 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 9ec932a9f4d..bb6f8116a52 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ResourcePropertiesTests { @Test public void emptyCacheControl() { - CacheControl cacheControl = this.properties.getCache().getCachecontrol() - .toHttpCacheControl(); + CacheControl cacheControl = this.properties.getCache().getCachecontrol().toHttpCacheControl(); assertThat(cacheControl.getHeaderValue()).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 4c504f321c3..667c7811b3f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -104,8 +103,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 @@ -147,10 +145,8 @@ public class ServerPropertiesTests { assertThat(tomcat.getAccesslog().getSuffix()).isEqualTo("-bar.log"); 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 @@ -168,8 +164,7 @@ public class ServerPropertiesTests { @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 @@ -209,20 +204,17 @@ public class ServerPropertiesTests { @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 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 @@ -233,14 +225,13 @@ public class ServerPropertiesTests { @Test public void tomcatMaxHttpPostSizeMatchesConnectorDefault() throws Exception { - assertThat(this.properties.getTomcat().getMaxHttpPostSize()) - .isEqualTo(getDefaultConnector().getMaxPostSize()); + assertThat(this.properties.getTomcat().getMaxHttpPostSize()).isEqualTo(getDefaultConnector().getMaxPostSize()); } @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 @@ -263,9 +254,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 @@ -277,28 +267,24 @@ public class ServerPropertiesTests { @Test public void jettyMaxHttpPostSizeMatchesDefault() throws Exception { JettyServletWebServerFactory jettyFactory = new JettyServletWebServerFactory(0); - JettyWebServer jetty = (JettyWebServer) jettyFactory - .getWebServer(new ServletContextInitializer() { + JettyWebServer jetty = (JettyWebServer) jettyFactory.getWebServer(new ServletContextInitializer() { + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContext.addServlet("formPost", new HttpServlet() { @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - servletContext.addServlet("formPost", new HttpServlet() { - - @Override - protected void doPost(HttpServletRequest req, - HttpServletResponse resp) - throws ServletException, IOException { - req.getParameterMap(); - } - - }).addMapping("/form"); + 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() { @@ -331,17 +317,13 @@ 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()) - .isEqualTo(defaultMaxPostSize); + int defaultMaxPostSize = Integer.valueOf(message.substring(message.lastIndexOf(' ')).trim()); + assertThat(this.properties.getJetty().getMaxHttpPostSize()).isEqualTo(defaultMaxPostSize); } finally { jetty.stop(); @@ -359,8 +341,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 17d9fda0576..31eddae9468 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +60,9 @@ public class RestTemplateAutoConfigurationTests { load(HttpMessageConvertersAutoConfiguration.class, RestTemplateConfig.class); assertThat(this.context.getBeansOfType(RestTemplate.class)).hasSize(1); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); - List> converters = this.context - .getBean(HttpMessageConverters.class).getConverters(); - assertThat(restTemplate.getMessageConverters()) - .containsExactlyElementsOf(converters); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + List> converters = this.context.getBean(HttpMessageConverters.class).getConverters(); + assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test @@ -78,8 +75,7 @@ public class RestTemplateAutoConfigurationTests { @Test public void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { - load(CustomHttpMessageConverter.class, - HttpMessageConvertersAutoConfiguration.class, RestTemplateConfig.class); + load(CustomHttpMessageConverter.class, HttpMessageConvertersAutoConfiguration.class, RestTemplateConfig.class); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); List> converterClasses = new ArrayList<>(); for (HttpMessageConverter converter : restTemplate.getMessageConverters()) { @@ -94,16 +90,14 @@ public class RestTemplateAutoConfigurationTests { assertThat(this.context.getBeansOfType(RestTemplate.class)).hasSize(1); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); assertThat(restTemplate.getMessageConverters()).hasSize(1); - assertThat(restTemplate.getMessageConverters().get(0)) - .isInstanceOf(CustomHttpMessageConverter.class); + assertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.class); } @Test public void restTemplateShouldApplyCustomizer() { load(RestTemplateCustomizerConfig.class, RestTemplateConfig.class); RestTemplate restTemplate = this.context.getBean(RestTemplate.class); - RestTemplateCustomizer customizer = this.context - .getBean(RestTemplateCustomizer.class); + RestTemplateCustomizer customizer = this.context.getBean(RestTemplateCustomizer.class); verify(customizer).customize(restTemplate); } @@ -166,8 +160,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 969502436e5..624c820d8c0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +59,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); } @@ -85,18 +82,12 @@ public class JettyWebServerFactoryCustomizerTests { File logFile = File.createTempFile("jetty_log", ".log"); String timezone = TimeZone.getDefault().getID(); bind("server.jetty.accesslog.enabled=true", - "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.extended-format=true", - "server.jetty.accesslog.date-format=HH:mm:ss", - "server.jetty.accesslog.locale=en_BE", - "server.jetty.accesslog.time-zone=" + timezone, - "server.jetty.accesslog.log-cookies=true", - "server.jetty.accesslog.log-server=true", - "server.jetty.accesslog.log-latency=true"); + "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.extended-format=true", + "server.jetty.accesslog.date-format=HH:mm:ss", "server.jetty.accesslog.locale=en_BE", + "server.jetty.accesslog.time-zone=" + timezone, "server.jetty.accesslog.log-cookies=true", + "server.jetty.accesslog.log-server=true", "server.jetty.accesslog.log-latency=true"); JettyWebServer server = customizeAndGetServer(); NCSARequestLog requestLog = getNCSARequestLog(server); assertThat(requestLog.getFilename()).isEqualTo(logFile.getAbsolutePath()); @@ -134,15 +125,13 @@ 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); } 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/TomcatWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java index 2f71e52ecc5..6b510fdf0e9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ 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 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)); } @@ -74,23 +73,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)); } @@ -98,17 +94,14 @@ 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 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(); @@ -140,8 +133,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(); } @@ -166,8 +158,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); } @@ -175,8 +166,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 @@ -208,11 +198,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 @@ -227,25 +215,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 @@ -255,8 +241,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 5573924af93..d38e2981c06 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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"); @@ -77,16 +72,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); } @@ -94,15 +87,13 @@ 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); } 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 20c9539d9e0..44684a91af5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 584254f4390..a3aada2a9d4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 f0f080aaf89..6bab565efc3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,20 +42,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(1); - 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(1); + assertThat(context.getBeansOfType(ReactiveWebServerFactoryCustomizer.class)).hasSize(1); }); } @@ -70,31 +65,28 @@ 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)); } @Configuration 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 df18b09b2e5..09fc754b6c7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a9acc4ee7de..f2c737e2eac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -95,53 +92,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/")); @@ -150,17 +134,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 @@ -172,29 +151,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)); @@ -204,25 +175,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 @@ -230,144 +196,112 @@ 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(new DirectFieldAccessor(target) - .getPropertyValue("targetValidator")) - .isSameAs(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(new DirectFieldAccessor(target).getPropertyValue("targetValidator")) + .isSameAs(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); + }); } @Configuration 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 84d85b6c9a8..df8fa8bf4b5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +57,11 @@ import static org.hamcrest.Matchers.not; public class DefaultErrorWebExceptionHandlerIntegrationTests { 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); @Rule @@ -76,58 +73,48 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { @Test public void jsonError() { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - client.get().uri("/").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); + 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(); - this.output.expect(allOf(containsString("Failed to handle request [GET /]"), - containsString("IllegalStateException"))); + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/")) + .jsonPath("message").isEqualTo("Expected!").jsonPath("exception").doesNotExist().jsonPath("trace") + .doesNotExist(); + this.output.expect( + allOf(containsString("Failed to handle request [GET /]"), containsString("IllegalStateException"))); }); } @Test public void notFound() { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - 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(); + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); + 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(); }); } @Test public void htmlError() { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange() - .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) - .expectHeader().contentType(MediaType.TEXT_HTML) + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); + String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(MediaType.TEXT_HTML) .expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("status: 500").contains("message: Expected!"); - this.output.expect(allOf(containsString("Failed to handle request [GET /]"), - containsString("IllegalStateException"))); + this.output.expect( + allOf(containsString("Failed to handle request [GET /]"), containsString("IllegalStateException"))); }); } @Test public void bindingResultError() { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - 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(); + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); + 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(); }); this.output.expect(allOf(containsString("Failed to handle request [POST /bind]"), containsString("Validation failed for argument"), @@ -136,132 +123,98 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { @Test public void includeStackTraceOnParam() { - this.contextRunner - .withPropertyValues("server.error.include-exception=true", - "server.error.include-stacktrace=on-trace-param") - .run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); + this.contextRunner.withPropertyValues("server.error.include-exception=true", + "server.error.include-stacktrace=on-trace-param").run((context) -> { + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); 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(); + .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(); }); } @Test public void alwaysIncludeStackTrace() throws Exception { - this.contextRunner.withPropertyValues("server.error.include-exception=true", - "server.error.include-stacktrace=always").run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); + this.contextRunner + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") + .run((context) -> { + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); 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(); + .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(); }); } @Test public void neverIncludeStackTrace() { - this.contextRunner.withPropertyValues("server.error.include-exception=true", - "server.error.include-stacktrace=never").run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); + this.contextRunner + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") + .run((context) -> { + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); 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(); + .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(); }); } @Test public void statusException() { - this.contextRunner.withPropertyValues("server.error.include-exception=true") - .run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - 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()); - this.output.expect(not(containsString("ResponseStatusException"))); - }); + this.contextRunner.withPropertyValues("server.error.include-exception=true").run((context) -> { + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); + 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()); + this.output.expect(not(containsString("ResponseStatusException"))); + }); } @Test public void defaultErrorView() { - this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/") - .run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML) - .exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader() - .contentType(MediaType.TEXT_HTML).expectBody(String.class) - .returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page") - .contains("
    Expected!
    "); - this.output.expect( - allOf(containsString("Failed to handle request [GET /]"), - containsString("IllegalStateException"))); - }); + this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/").run((context) -> { + WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); + String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(MediaType.TEXT_HTML) + .expectBody(String.class).returnResult().getResponseBody(); + assertThat(body).contains("Whitelabel Error Page").contains("
    Expected!
    "); + this.output.expect( + allOf(containsString("Failed to handle request [GET /]"), containsString("IllegalStateException"))); + }); } @Test public void escapeHtmlInDefaultErrorView() { - this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/") - .run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context) - .build(); - String body = client.get().uri("/html").accept(MediaType.TEXT_HTML) - .exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader() - .contentType(MediaType.TEXT_HTML).expectBody(String.class) - .returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page") - .doesNotContain("")) + new RuntimeException("")) .accept(MediaType.TEXT_HTML)) .andExpect(status().is5xxServerError()).andReturn(); String content = response.getResponse().getContentAsString(); @@ -96,12 +94,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"); @@ -114,10 +108,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 c82e010b35c..637599a2395 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ 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 @@ -101,51 +101,43 @@ public class DefaultErrorViewResolverTests { @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); @@ -154,8 +146,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); @@ -164,8 +155,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); @@ -174,23 +165,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); @@ -209,8 +195,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 { @@ -219,8 +205,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 f672d0d3975..6f65fcf886a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ 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)); @Rule public OutputCapture outputCapture = new OutputCapture(); @@ -52,12 +50,12 @@ 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"), false); - errorView.render(errorAttributes.getErrorAttributes(webRequest, true), - webRequest.getRequest(), webRequest.getResponse()); - assertThat(((MockHttpServletResponse) webRequest.getResponse()) - .getContentAsString()).contains("
    Exception message
    "); + DispatcherServletWebRequest webRequest = createWebRequest(new IllegalStateException("Exception message"), + false); + errorView.render(errorAttributes.getErrorAttributes(webRequest, true), webRequest.getRequest(), + webRequest.getResponse()); + assertThat(((MockHttpServletResponse) webRequest.getResponse()).getContentAsString()) + .contains("
    Exception message
    "); }); } @@ -66,28 +64,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(this.outputCapture.toString()) - .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(this.outputCapture.toString()).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/NonRecursivePropertyPlaceholderHelperTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/NonRecursivePropertyPlaceholderHelperTests.java index 88549395e7a..834b1cb7e7c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/NonRecursivePropertyPlaceholderHelperTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/NonRecursivePropertyPlaceholderHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.assertj.core.api.Assertions.assertThat; */ public class NonRecursivePropertyPlaceholderHelperTests { - private final NonRecursivePropertyPlaceholderHelper helper = new NonRecursivePropertyPlaceholderHelper( - "${", "}"); + private final NonRecursivePropertyPlaceholderHelper helper = new NonRecursivePropertyPlaceholderHelper("${", "}"); @Test public void canResolve() { 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 6cfc061286e..0b816520d87 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 @@ -47,8 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Dave Syer */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, - properties = "server.servlet.path:/spring/*") +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "server.servlet.path:/spring/*") @DirtiesContext public class RemappedErrorViewIntegrationTests { @@ -59,24 +58,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 @Import({ PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class }) @Controller public static class TestConfiguration implements ErrorPageRegistrar { @@ -93,8 +89,7 @@ public class RemappedErrorViewIntegrationTests { // For manual testing public static void main(String[] args) { - new SpringApplicationBuilder(TestConfiguration.class) - .properties("server.servlet.path:spring/*").run(args); + new SpringApplicationBuilder(TestConfiguration.class).properties("server.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 e754913e1be..d87decf63b5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 OnWsdlLocationsConditionTests { @Test public void bootstrapHostsDefinedAsList() { - 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 21c21eb94c1..50e60d30643 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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)) - .hasSize(1).containsKey("service"); - assertThat(context.getBeansOfType(SimpleXsdSchema.class)).hasSize(1) - .containsKey("types"); - }); + this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations=classpath:/wsdl").run((context) -> { + assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)).hasSize(1).containsKey("service"); + assertThat(context.getBeansOfType(SimpleXsdSchema.class)).hasSize(1).containsKey("types"); + }); } @Test public void withWsdlBeansAsList() { - this.contextRunner - .withPropertyValues( - "spring.webservices.wsdl-locations[0]=classpath:/wsdl") - .run((context) -> { - assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)) - .hasSize(1).containsKey("service"); - assertThat(context.getBeansOfType(SimpleXsdSchema.class)).hasSize(1) - .containsKey("types"); - }); + this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=classpath:/wsdl").run((context) -> { + assertThat(context.getBeansOfType(SimpleWsdl11Definition.class)).hasSize(1).containsKey("service"); + assertThat(context.getBeansOfType(SimpleXsdSchema.class)).hasSize(1).containsKey("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/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketMessagingAutoConfigurationTests.java index d0cd8330fdf..84384c21afb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 WebSocketMessagingAutoConfigurationTests { @Before 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,14 +132,11 @@ public class WebSocketMessagingAutoConfigurationTests { private List getDefaultConverters() { CompositeMessageConverter compositeDefaultConverter = new DelegatingWebSocketMessageBrokerConfiguration() .brokerMessageConverter(); - return (List) ReflectionTestUtils - .getField(compositeDefaultConverter, "converters"); + 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(); @@ -153,8 +147,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 @@ -177,8 +170,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(); } @@ -208,12 +201,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 411e880a622..258c155f6d7 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 13adb49ca1e..7e6c0b580ce 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class ServiceCapabilitiesReportGenerator { return report.toString(); } - private void reportAvailableDependencies(InitializrServiceMetadata metadata, - StringBuilder report) { + private void reportAvailableDependencies(InitializrServiceMetadata metadata, StringBuilder report) { report.append("Available dependencies:" + NEW_LINE); report.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:" + NEW_LINE); report.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,8 +129,7 @@ class ServiceCapabilitiesReportGenerator { report.append("]"); } - private void reportDefaults(StringBuilder report, - InitializrServiceMetadata metadata) { + private void reportDefaults(StringBuilder report, InitializrServiceMetadata metadata) { report.append("Defaults:" + NEW_LINE); report.append("---------" + NEW_LINE); List defaultsKeys = new ArrayList<>(metadata.getDefaults().keySet()); 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 d7f58cd0571..6b7f121c77a 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 2600b7c6c49..44511bf096f 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 e27492fbf29..ee56f1476af 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.core.annotation.Order; * @since 1.3.0 */ @Order(DependencyManagementBomTransformation.ORDER) -public class DependencyManagementBomTransformation - extends AnnotatedNodeASTTransformation { +public class DependencyManagementBomTransformation extends AnnotatedNodeASTTransformation { /** * The order of the transformation. @@ -70,14 +69,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; } @@ -104,10 +101,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) { @@ -136,13 +131,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 @@ -150,9 +144,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; @@ -160,16 +152,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 { @@ -178,34 +166,28 @@ 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 { @@ -219,18 +201,15 @@ 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 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 6af45e25baa..9185b385bcb 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. @@ -84,8 +84,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; @@ -148,16 +147,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; } @@ -231,8 +228,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 05d9254cd60..6e6aad81917 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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); @@ -317,8 +303,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 5fee4dc4e6a..3536ea923dd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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 ea522eba421..724167b9c98 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 f166912ae5a..a48e808e0d3 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,45 +45,36 @@ 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 1e7dc88f64e..f81ec67f3ba 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +81,9 @@ public class CliTester implements TestRule { updatedArgs.add(arg); } if (!classpathUpdated) { - updatedArgs.add( - "--classpath=.:" + new File("target/test-classes").getAbsolutePath()); + updatedArgs.add("--classpath=.:" + new File("target/test-classes").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(); } @@ -102,8 +100,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(() -> { @@ -111,8 +108,7 @@ public class CliTester implements TestRule { System.setProperty("server.port", "0"); System.setProperty("spring.application.class.name", "org.springframework.boot.cli.CliTesterSpringApplication"); - System.setProperty("portfile", - new File("target/server.port").getAbsolutePath()); + System.setProperty("portfile", new File("target/server.port").getAbsolutePath()); try { command.run(sources); return command; @@ -168,16 +164,13 @@ public class CliTester implements TestRule { @Override public Statement apply(Statement base, Description description) { - final Statement statement = CliTester.this.outputCapture - .apply(new RunLauncherStatement(base), description); + final Statement statement = CliTester.this.outputCapture.apply(new RunLauncherStatement(base), 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(); } }; @@ -189,10 +182,8 @@ public class CliTester implements TestRule { public String getHttpOutput(String uri) { try { - int port = Integer.parseInt( - FileCopyUtils.copyToString(new FileReader("target/server.port"))); - InputStream stream = URI.create("http://localhost:" + port + uri).toURL() - .openStream(); + int port = Integer.parseInt(FileCopyUtils.copyToString(new FileReader("target/server.port"))); + 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 b6d68019c9d..4d81794feb4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 GrabCommandIntegrationTests { // Use --autoconfigure=false to limit the amount of downloaded dependencies String output = this.cli.grab("grab.groovy", "--autoconfigure=false"); - assertThat(new File("target/repository/joda-time/joda-time").isDirectory()) - .isTrue(); + assertThat(new File("target/repository/joda-time/joda-time").isDirectory()).isTrue(); // Should be resolved from local repository cache assertThat(output.contains("Downloading: file:")).isTrue(); } @@ -69,20 +68,17 @@ public class GrabCommandIntegrationTests { fail(); } catch (Exception ex) { - assertThat(ex.getMessage()) - .contains("Duplicate @DependencyManagementBom annotation"); + assertThat(ex.getMessage()).contains("Duplicate @DependencyManagementBom annotation"); } } @Test public void customMetadata() throws Exception { System.setProperty("grape.root", "target"); - FileSystemUtils.copyRecursively( - new File("src/test/resources/grab-samples/repository"), + FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"), new File("target/repository")); this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false"); - assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()) - .isTrue(); + assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()).isTrue(); } } 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/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 ea3b463c8ee..b8c3b1378d3 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 09bb5984f81..66e0f0e09ed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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); } @@ -69,8 +68,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); } @@ -144,13 +143,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 bb60f6066ec..c33e00a7cbe 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -61,8 +60,8 @@ public class ProjectGenerationRequestTests { String customServerUrl = "http://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 @@ -83,8 +82,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 @@ -103,14 +102,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 @@ -134,9 +131,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 @@ -156,8 +152,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 @@ -191,8 +187,7 @@ public class ProjectGenerationRequestTests { 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 @@ -200,8 +195,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 @@ -238,8 +232,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); } @@ -247,13 +240,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 dab2e1a2105..f0bc5f90057 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -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(3); - assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", - "commons-logging-1.1.3.jar", "hamcrest-core-1.3.jar"); + assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", "commons-logging-1.1.3.jar", + "hamcrest-core-1.3.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 2d9451f75b8..04f570441d9 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +83,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"); } @@ -105,14 +100,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 8d88b0f3175..c35099b8341 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +38,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); this.thrown.expect(RuntimeException.class); this.thrown.expectMessage(equalTo("No classes found in '[foo, bar]'")); - new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }) - .compileAndRun(); + new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun(); } } 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 1e3c21790f5..c1091e417f6 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ExtendedGroovyClassLoaderTests { @Before public void setup() { this.contextClassLoader = Thread.currentThread().getContextClassLoader(); - this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader( - GroovyCompilerScope.DEFAULT); + this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(GroovyCompilerScope.DEFAULT); } @Test @@ -55,8 +54,7 @@ public class ExtendedGroovyClassLoaderTests { public void filtersNonGroovy() throws Exception { this.contextClassLoader.loadClass("org.springframework.util.StringUtils"); this.thrown.expect(ClassNotFoundException.class); - this.defaultScopeGroovyClassLoader - .loadClass("org.springframework.util.StringUtils"); + 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 5f8d8663acd..5c7a486800f 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 @@ -46,20 +46,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 @@ -77,8 +75,7 @@ public class AetherGrapeEngineTests { DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils .getField(grapeEngine, "session"); - assertThat(session.getProxySelector() instanceof CompositeProxySelector) - .isTrue(); + assertThat(session.getProxySelector() instanceof CompositeProxySelector).isTrue(); }); } @@ -104,8 +101,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"), @@ -118,8 +114,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); } @@ -141,10 +136,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); @@ -152,8 +146,7 @@ public class AetherGrapeEngineTests { @Test(expected = IllegalArgumentException.class) 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"); createGrapeEngine().grab(Collections.emptyMap(), dependency); @@ -162,8 +155,8 @@ public class AetherGrapeEngineTests { @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(); @@ -174,8 +167,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(); @@ -187,8 +180,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); @@ -200,12 +192,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); @@ -213,8 +203,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; @@ -235,8 +224,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 befa574458d..df65656d5df 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(REPOSITORY, ARTIFACT, - null, null); + private final TransferResource resource = new TransferResource(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 1a83cd31ff4..fe5aaa53625 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.context.ApplicationListener; * * @author Andy Wilkinson */ -class ConditionEvaluationDeltaLoggingListener - implements ApplicationListener { +class ConditionEvaluationDeltaLoggingListener implements ApplicationListener { private final Log logger = LogFactory.getLog(getClass()); @@ -39,17 +38,14 @@ class ConditionEvaluationDeltaLoggingListener @Override public void onApplicationEvent(ApplicationReadyEvent event) { - ConditionEvaluationReport report = event.getApplicationContext() - .getBean(ConditionEvaluationReport.class); + ConditionEvaluationReport report = event.getApplicationContext().getBean(ConditionEvaluationReport.class); 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 (this.logger.isInfoEnabled()) { this.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 5e6731b8afd..c9bf441c246 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @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/HateoasObjenesisCacheDisabler.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java index a1eae6fc455..bcbc9d07b95 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisabler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.ReflectionUtils; */ class HateoasObjenesisCacheDisabler implements InitializingBean { - private static final Log logger = LogFactory - .getLog(HateoasObjenesisCacheDisabler.class); + private static final Log logger = LogFactory.getLog(HateoasObjenesisCacheDisabler.class); private static boolean cacheDisabled; @@ -55,8 +54,7 @@ class HateoasObjenesisCacheDisabler implements InitializingBean { private void doDisableCaching() { try { - Class type = ClassUtils.forName( - "org.springframework.hateoas.core.DummyInvocationUtils", + Class type = ClassUtils.forName("org.springframework.hateoas.core.DummyInvocationUtils", getClass().getClassLoader()); removeObjenesisCache(type); } @@ -67,21 +65,17 @@ class HateoasObjenesisCacheDisabler implements InitializingBean { private void removeObjenesisCache(Class dummyInvocationUtils) { try { - Field objenesisField = ReflectionUtils.findField(dummyInvocationUtils, - "OBJENESIS"); + Field objenesisField = ReflectionUtils.findField(dummyInvocationUtils, "OBJENESIS"); if (objenesisField != null) { ReflectionUtils.makeAccessible(objenesisField); Object objenesis = ReflectionUtils.getField(objenesisField, null); - Field cacheField = ReflectionUtils.findField(objenesis.getClass(), - "cache"); + Field cacheField = ReflectionUtils.findField(objenesis.getClass(), "cache"); ReflectionUtils.makeAccessible(cacheField); ReflectionUtils.setField(cacheField, objenesis, null); } } catch (Exception ex) { - logger.warn( - "Failed to disable Spring HATEOAS's Objenesis cache. ClassCastExceptions may occur", - ex); + logger.warn("Failed to disable Spring HATEOAS's Objenesis cache. ClassCastExceptions may occur", ex); } } 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 7d5272a2f14..021421f420d 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 @@ -58,8 +58,7 @@ public class LocalDevToolsAutoConfiguration { * Local LiveReload configuration. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", matchIfMissing = true) static class LiveReloadConfiguration { private final DevToolsProperties properties; @@ -77,14 +76,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); } @@ -94,8 +91,7 @@ public class LocalDevToolsAutoConfiguration { * Local Restart Configuration. */ @Configuration - @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; @@ -107,8 +103,7 @@ public class LocalDevToolsAutoConfiguration { @EventListener public void onClassPathChanged(ClassPathChangedEvent event) { if (event.isRestartRequired()) { - Restarter.getInstance().restart( - new FileWatchingFailureHandler(fileSystemWatcherFactory())); + Restarter.getInstance().restart(new FileWatchingFailureHandler(fileSystemWatcherFactory())); } } @@ -116,8 +111,8 @@ public class LocalDevToolsAutoConfiguration { @ConditionalOnMissingBean public ClassPathFileSystemWatcher classPathFileSystemWatcher() { URL[] urls = Restarter.getInstance().getInitialUrls(); - ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher( - fileSystemWatcherFactory(), classPathRestartStrategy(), urls); + ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher(fileSystemWatcherFactory(), + classPathRestartStrategy(), urls); watcher.setStopWatcherOnRestart(true); return watcher; } @@ -125,8 +120,7 @@ public class LocalDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean public ClassPathRestartStrategy classPathRestartStrategy() { - return new PatternClassPathRestartStrategy( - this.properties.getRestart().getAllExclude()); + return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean @@ -140,16 +134,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)) { 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 e2d3d220b85..fc1c6000ddd 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 @@ -61,15 +61,13 @@ 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; private final ServerProperties serverProperties; - public RemoteDevToolsAutoConfiguration(DevToolsProperties properties, - ServerProperties serverProperties) { + public RemoteDevToolsAutoConfiguration(DevToolsProperties properties, ServerProperties serverProperties) { this.properties = properties; this.serverProperties = serverProperties; } @@ -78,19 +76,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() { Handler handler = new HttpStatusHandler(); Servlet servlet = this.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 @@ -105,8 +99,7 @@ public class RemoteDevToolsAutoConfiguration { * Configuration for remote update and restarts. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", matchIfMissing = true) static class RemoteRestartConfiguration { @Autowired @@ -123,8 +116,7 @@ public class RemoteDevToolsAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpRestartServer remoteRestartHttpRestartServer( - SourceFolderUrlFilter sourceFolderUrlFilter) { + public HttpRestartServer remoteRestartHttpRestartServer(SourceFolderUrlFilter sourceFolderUrlFilter) { return new HttpRestartServer(sourceFolderUrlFilter); } @@ -133,8 +125,7 @@ public class RemoteDevToolsAutoConfiguration { public UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server) { Servlet servlet = this.serverProperties.getServlet(); RemoteDevToolsProperties remote = this.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 314121f31a6..aec8db32794 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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) { File home = getHomeFolder(); File propertyFile = (home != null) ? new File(home, FILE_NAME) : null; if (propertyFile != null && propertyFile.exists() && propertyFile.isFile()) { @@ -50,8 +49,7 @@ 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 669456ab6e5..58a1424cec1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +62,9 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (isLocalApplication(environment) && canAddProperties(environment)) { - PropertySource propertySource = new MapPropertySource("refresh", - PROPERTIES); + PropertySource propertySource = new MapPropertySource("refresh", PROPERTIES); environment.getPropertySources().addLast(propertySource); } } 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 801cca77612..b442d06491d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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; } @@ -132,8 +128,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 { @@ -144,26 +139,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 2c379b01b6e..05b3cd4546d 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 - @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.livereload", name = "enabled", matchIfMissing = true) static class LiveReloadConfiguration { @Autowired @@ -159,8 +156,8 @@ public class RemoteClientConfiguration implements InitializingBean { @EventListener public void onClassPathChanged(ClassPathChangedEvent event) { String url = this.remoteUrl + this.properties.getRemote().getContextPath(); - this.executor.execute(new DelayedLiveReloadTrigger(optionalLiveReloadServer(), - this.clientHttpRequestFactory, url)); + this.executor.execute( + new DelayedLiveReloadTrigger(optionalLiveReloadServer(), this.clientHttpRequestFactory, url)); } @Bean @@ -178,8 +175,7 @@ public class RemoteClientConfiguration implements InitializingBean { * Client configuration for remote update and restarts. */ @Configuration - @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", - matchIfMissing = true) + @ConditionalOnProperty(prefix = "spring.devtools.remote.restart", name = "enabled", matchIfMissing = true) static class RemoteRestartClientConfiguration { @Autowired @@ -195,8 +191,7 @@ public class RemoteClientConfiguration implements InitializingBean { if (urls == null) { urls = new URL[0]; } - return new ClassPathFileSystemWatcher(getFileSystemWatcherFactory(), - classPathRestartStrategy(), urls); + return new ClassPathFileSystemWatcher(getFileSystemWatcherFactory(), classPathRestartStrategy(), urls); } @Bean @@ -206,8 +201,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)) { @@ -218,15 +212,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 6fca5aece95..a56a41a0f8b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 fc76811780d..3acc3a10a59 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,8 +116,7 @@ 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()) { @@ -132,8 +125,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe ClassLoaderFile file = entry.getValue(); if (entry.getValue().getKind() != Kind.DELETED && this.antPathMatcher.match(trimmedLocationPattern, name)) { - URL url = new URL("reloaded", null, -1, "/" + name, - new ClassLoaderFileURLStreamHandler(file)); + URL url = new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); UrlResource resource = new UrlResource(url); additionalResources.add(resource); } @@ -163,8 +155,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 +196,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 +214,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 +226,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 +253,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 +264,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 3d21989cab1..eebdb9e07e3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 d8b62bf81f4..c07a00a70cf 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.Ordered; * @since 1.3.0 * @see Restarter */ -public class RestartApplicationListener - implements ApplicationListener, Ordered { +public class RestartApplicationListener implements ApplicationListener, Ordered { private int order = HIGHEST_PRECEDENCE; @@ -47,8 +46,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) { 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 8f1466a0635..a14300ec724 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 fb3f8bce2ca..165a0f62ac5 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. @@ -111,8 +111,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); @@ -139,8 +138,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)); } @@ -198,8 +196,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; } @@ -251,8 +248,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); @@ -284,8 +280,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(); } @@ -297,8 +292,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); } } @@ -335,8 +329,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); @@ -345,8 +338,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(); @@ -390,8 +382,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; } @@ -450,8 +441,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 424343b1c2d..5ed6495cffb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 RemoteUrlPropertyExtractorTests { @After public void preventRunFailuresFromPollutingLoggerContext() { - ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)) - .getLoggerContext().getTurboFilterList().clear(); + ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() + .getTurboFilterList().clear(); } @Test @@ -71,17 +71,14 @@ public class RemoteUrlPropertyExtractorTests { @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 fc377488756..b00c237a7d7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void singleManuallyConfiguredDataSourceIsNotClosed() throws SQLException { - ConfigurableApplicationContext context = createContext( - SingleDataSourceConfiguration.class); + ConfigurableApplicationContext context = createContext(SingleDataSourceConfiguration.class); DataSource dataSource = context.getBean(DataSource.class); Statement statement = configureDataSourceBehavior(dataSource); verify(statement, never()).execute("SHUTDOWN"); @@ -59,10 +58,8 @@ public abstract class AbstractDevToolsDataSourceAutoConfigurationTests { @Test public void multipleDataSourcesAreIgnored() throws SQLException { - ConfigurableApplicationContext context = createContext( - MultipleDataSourcesConfiguration.class); - Collection dataSources = context.getBeansOfType(DataSource.class) - .values(); + ConfigurableApplicationContext context = createContext(MultipleDataSourcesConfiguration.class); + Collection dataSources = context.getBeansOfType(DataSource.class).values(); for (DataSource dataSource : dataSources) { Statement statement = configureDataSourceBehavior(dataSource); verify(statement, never()).execute("SHUTDOWN"); @@ -73,16 +70,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(); @@ -94,20 +89,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); @@ -154,8 +146,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); } @@ -163,8 +154,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 bbdf875140b..ea5b5e287e3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.mockito.Mockito.verify; * * @author Andy Wilkinson */ -public class DevToolsPooledDataSourceAutoConfigurationTests - extends AbstractDevToolsDataSourceAutoConfigurationTests { +public class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDataSourceAutoConfigurationTests { @Before public void before() { @@ -52,10 +51,9 @@ public class DevToolsPooledDataSourceAutoConfigurationTests @Test public void autoConfiguredInMemoryDataSourceIsShutdown() 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).execute("SHUTDOWN"); } @@ -64,74 +62,61 @@ public class DevToolsPooledDataSourceAutoConfigurationTests public void autoConfiguredExternalDataSourceIsNotShutdown() throws SQLException { ConfigurableApplicationContext context = createContext("org.postgresql.Driver", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.close(); verify(statement, never()).execute("SHUTDOWN"); } @Test public void h2ServerIsNotShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext("org.h2.Driver", - "jdbc:h2:hsql://localhost", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = 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 SQLException { - ConfigurableApplicationContext context = createContext("org.h2.Driver", - "jdbc:h2:mem:test", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = 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 SQLException { - ConfigurableApplicationContext context = createContext("org.hsqldb.jdbcDriver", - "jdbc:hsqldb:hsql://localhost", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = 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 SQLException { - ConfigurableApplicationContext context = createContext("org.hsqldb.jdbcDriver", - "jdbc:hsqldb:mem:test", DataSourceAutoConfiguration.class, - DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = 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 SQLException { - ConfigurableApplicationContext context = createContext( - "org.apache.derby.jdbc.ClientDriver", "jdbc:derby://localhost", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = 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"); } @Test public void inMemoryDerbyIsShutdown() throws SQLException { - ConfigurableApplicationContext context = createContext( - "org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:test", - DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); - Statement statement = configureDataSourceBehavior( - context.getBean(DataSource.class)); + ConfigurableApplicationContext context = createContext("org.apache.derby.jdbc.EmbeddedDriver", + "jdbc:derby:memory:test", DataSourceAutoConfiguration.class, DataSourceSpyConfiguration.class); + Statement statement = configureDataSourceBehavior(context.getBean(DataSource.class)); context.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/HateoasObjenesisCacheDisablerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java index 5f6d2246d9a..e178990d0a2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/HateoasObjenesisCacheDisablerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +41,9 @@ public class HateoasObjenesisCacheDisablerTests { @Before @After public void resetCacheField() { - ReflectionTestUtils.setField(HateoasObjenesisCacheDisabler.class, "cacheDisabled", - false); - this.objenesis = (ObjenesisStd) ReflectionTestUtils - .getField(DummyInvocationUtils.class, "OBJENESIS"); - ReflectionTestUtils.setField(this.objenesis, "cache", - new ConcurrentHashMap>()); + ReflectionTestUtils.setField(HateoasObjenesisCacheDisabler.class, "cacheDisabled", false); + this.objenesis = (ObjenesisStd) ReflectionTestUtils.getField(DummyInvocationUtils.class, "OBJENESIS"); + ReflectionTestUtils.setField(this.objenesis, "cache", new ConcurrentHashMap>()); } @Test 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 cc64629efe8..1ddf972349c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,28 +88,24 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void thymeleafCacheIsFalse() { this.context = 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() { this.context = initializeAndRun(Config.class, "--spring.thymeleaf.cache=true"); - SpringResourceTemplateResolver resolver = this.context - .getBean(SpringResourceTemplateResolver.class); + SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } @Test public void defaultPropertyCanBeOverriddenFromUserHomeProperties() { 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 = initializeAndRun(Config.class); - SpringResourceTemplateResolver resolver = this.context - .getBean(SpringResourceTemplateResolver.class); + SpringResourceTemplateResolver resolver = this.context.getBean(SpringResourceTemplateResolver.class); assertThat(resolver.isCacheable()).isTrue(); } finally { @@ -145,8 +141,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = 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(); } @@ -156,8 +151,7 @@ public class LocalDevToolsAutoConfigurationTests { this.context = 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(); } @@ -174,8 +168,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartTriggeredOnClassPathChangeWithRestart() { this.context = 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)); } @@ -183,8 +176,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartNotTriggeredOnClassPathChangeWithRestart() { this.context = 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(); } @@ -192,8 +184,7 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void restartWatchingClassPath() { this.context = initializeAndRun(Config.class); - ClassPathFileSystemWatcher watcher = this.context - .getBean(ClassPathFileSystemWatcher.class); + ClassPathFileSystemWatcher watcher = this.context.getBean(ClassPathFileSystemWatcher.class); assertThat(watcher).isNotNull(); } @@ -211,10 +202,8 @@ public class LocalDevToolsAutoConfigurationTests { Map properties = new HashMap<>(); properties.put("spring.devtools.restart.trigger-file", "somefile.txt"); this.context = 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); } @@ -222,18 +211,13 @@ public class LocalDevToolsAutoConfigurationTests { @Test public void watchingAdditionalPaths() { 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 = 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()); } @@ -249,13 +233,12 @@ public class LocalDevToolsAutoConfigurationTests { assertThat(options.getDevelopment()).isTrue(); } - 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)); @@ -263,8 +246,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); @@ -274,15 +256,15 @@ public class LocalDevToolsAutoConfigurationTests { } @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ThymeleafAutoConfiguration.class }) public static class Config { } @Configuration - @Import({ ServletWebServerFactoryAutoConfiguration.class, - LocalDevToolsAutoConfiguration.class, ThymeleafAutoConfiguration.class }) + @Import({ ServletWebServerFactoryAutoConfiguration.class, LocalDevToolsAutoConfiguration.class, + ThymeleafAutoConfiguration.class }) public static class ConfigWithMockLiveReload { @Bean @@ -293,8 +275,8 @@ public class LocalDevToolsAutoConfigurationTests { } @Configuration - @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/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index fc8edfd71b7..aafcef5b45f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,8 +131,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void invokeRestartWithCustomServerContextPath() throws Exception { - 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"); @@ -142,8 +141,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void disableRestart() { - loadContext("spring.devtools.remote.secret:supersecret", - "spring.devtools.remote.restart.enabled:false"); + loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.restart.enabled:false"); this.thrown.expect(NoSuchBeanDefinitionException.class); this.context.getBean("remoteRestartHandlerMapper"); } @@ -161,8 +159,7 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void devToolsHealthWithCustomServerContextPathReturns200() throws Exception { - 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"); @@ -172,8 +169,7 @@ 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 void loadContext(String... properties) { @@ -190,8 +186,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 46cc5895b35..d8c5d2f5bdd 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ClassPathChangedEventTests { @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 ad158695e1d..dcf01b0cfb2 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-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,16 +72,14 @@ public class ClassPathFileChangeListenerTests { public void eventPublisherMustNotBeNull() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("EventPublisher must not be null"); - new ClassPathFileChangeListener(null, this.restartStrategy, - this.fileSystemWatcher); + new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher); } @Test public void restartStrategyMustNotBeNull() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("RestartStrategy must not be null"); - new ClassPathFileChangeListener(this.eventPublisher, null, - this.fileSystemWatcher); + new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher); } @Test @@ -97,8 +95,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); @@ -113,8 +111,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 616aeb24f23..f682dc9645e 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 @@ -60,8 +60,8 @@ public class ClassPathFileSystemWatcherTests { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Urls must not be null"); URL[] urls = null; - new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), - mock(ClassPathRestartStrategy.class), urls); + new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), mock(ClassPathRestartStrategy.class), + urls); } @Test @@ -89,8 +89,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(); } @@ -105,11 +105,9 @@ public class ClassPathFileSystemWatcherTests { @Bean public ClassPathFileSystemWatcher watcher() { - FileSystemWatcher watcher = new FileSystemWatcher(false, - Duration.ofMillis(100), Duration.ofMillis(10)); + 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 @@ -139,8 +137,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 c352e2b3983..7f6feba6fda 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DevToolPropertiesIntegrationTests { @Test public void classPropertyConditionIsAffectedByDevToolProperties() { - SpringApplication application = new SpringApplication( - ClassConditionConfiguration.class); + SpringApplication application = new SpringApplication(ClassConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); this.context.getBean(ClassConditionConfiguration.class); @@ -71,8 +70,7 @@ public class DevToolPropertiesIntegrationTests { @Test public void beanMethodPropertyConditionIsAffectedByDevToolProperties() { - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); this.context.getBean(MyBean.class); @@ -82,8 +80,7 @@ public class DevToolPropertiesIntegrationTests { public void postProcessWhenRestarterDisabledAndRemoteSecretNotSetShouldNotAddPropertySource() { Restarter.clearInstance(); Restarter.disable(); - SpringApplication application = new SpringApplication( - BeanConditionConfiguration.class); + SpringApplication application = new SpringApplication(BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); this.thrown.expect(NoSuchBeanDefinitionException.class); @@ -94,11 +91,9 @@ public class DevToolPropertiesIntegrationTests { public void postProcessWhenRestarterDisabledAndRemoteSecretSetShouldAddPropertySource() { 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 = application.run(); this.context.getBean(MyBean.class); } 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 a977f6d35e4..ca3512d6830 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -72,8 +71,7 @@ public class DevToolsHomePropertiesPostProcessorTests { assertThat(environment.getProperty("abc")).isNull(); } - 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 2aed54d40e9..58ea9f466cc 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 16597277f6b..ad206a541f1 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ExpectedException thrown = ExpectedException.none(); @@ -102,8 +101,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 401dc4f4419..726ac82cb9e 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. @@ -51,8 +51,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(); @@ -260,8 +259,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); @@ -276,10 +274,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 edf0acd1b29..a595edd431f 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. @@ -115,8 +115,7 @@ public class FolderSnapshotTests { public void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Snapshot source folder must be '" + this.folder + "'"); - this.initialSnapshot - .getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null); + this.initialSnapshot.getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null); } @Test @@ -135,8 +134,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 c9e593a1873..a0d402211d5 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 b50f097af63..09299deb4d3 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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); @@ -66,8 +63,7 @@ public class ConnectionInputStreamTests { @Test public void checkedRead() throws Exception { - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(NO_BYTES)); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); this.thrown.expect(IOException.class); this.thrown.expectMessage("End of stream"); inputStream.checkedRead(); @@ -75,8 +71,7 @@ public class ConnectionInputStreamTests { @Test public void checkedReadArray() throws Exception { - ConnectionInputStream inputStream = new ConnectionInputStream( - new ByteArrayInputStream(NO_BYTES)); + ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); this.thrown.expect(IOException.class); this.thrown.expectMessage("End of stream"); byte[] buffer = new byte[100]; 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 e4583e1d5dd..fc3b2d2c409 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 0ec634822c5..7fa6177edd2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -119,8 +118,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) @@ -138,13 +136,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"); @@ -164,10 +160,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 c3740bf4956..4419e2a9a79 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +75,9 @@ 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 @@ -112,8 +110,7 @@ public class DelayedLiveReloadTriggerTests { @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); @@ -124,8 +121,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 145896cef47..2b8532f15a9 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 HttpHeaderInterceptorTests { @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 2b057052211..d9868427410 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -145,8 +144,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(); @@ -154,11 +152,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 925a04733c2..d33808eaf8b 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +103,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 24d45512a13..5ed4412fbb9 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +91,11 @@ public class DispatcherTests { @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); @@ -105,23 +103,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/UrlHandlerMapperTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index c1751e40694..093c8056aec 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 308deb47690..f7f4be442e8 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. @@ -69,8 +69,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); @@ -79,8 +78,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) { @@ -88,8 +86,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 90c4faafe19..4465bb423fb 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 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 197f89f3dec..4ecd29ef96a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 fccfeb85032..dfad7f2ecb9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,56 +56,46 @@ public class RestartApplicationListenerTests { @Test public void isHighestPriority() { - assertThat(new RestartApplicationListener().getOrder()) - .isEqualTo(Ordered.HIGHEST_PRECEDENCE); + assertThat(new RestartApplicationListener().getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test public void initializeWithReady() { testInitialize(false); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")) - .isEqualTo(ARGS); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")).isEqualTo(ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); - assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), - "rootContexts")).isNotEmpty(); + assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isNotEmpty(); } @Test public void initializeWithFail() { testInitialize(true); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")) - .isEqualTo(ARGS); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "args")).isEqualTo(ARGS); assertThat(Restarter.getInstance().isFinished()).isTrue(); - assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), - "rootContexts")).isEmpty(); + assertThat((List) ReflectionTestUtils.getField(Restarter.getInstance(), "rootContexts")).isEmpty(); } @Test public void disableWithSystemProperty() { System.setProperty(ENABLED_PROPERTY, "false"); testInitialize(false); - assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "enabled")) - .isEqualTo(false); + assertThat(ReflectionTestUtils.getField(Restarter.getInstance(), "enabled")).isEqualTo(false); } 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 bf6ef197e1c..b1e411629fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 3b60f54e57d..5b6db440c2e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -134,10 +133,8 @@ public class RestarterTests { Restarter restarter = Restarter.getInstance(); restarter.addClassLoaderFiles(classLoaderFiles); restarter.restart(); - ClassLoader classLoader = ((TestableRestarter) restarter) - .getRelaunchClassLoader(); - assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f"))) - .isEqualTo("abc".getBytes()); + ClassLoader classLoader = ((TestableRestarter) restarter).getRelaunchClassLoader(); + assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f"))).isEqualTo("abc".getBytes()); } @Test @@ -222,8 +219,7 @@ public class RestarterTests { } - private static class CloseCountingApplicationListener - implements ApplicationListener { + private static class CloseCountingApplicationListener implements ApplicationListener { static int closed = 0; @@ -239,12 +235,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/ClassLoaderFilesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index 00f753491e6..cc57d922b6c 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +91,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 @@ -125,8 +123,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 812e5943eec..5bf8ffeace0 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. @@ -49,8 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; @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('.', '/'); @@ -76,8 +75,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 { @@ -109,22 +107,19 @@ public class RestartClassLoaderTests { @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); } @@ -177,8 +172,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 @@ -200,8 +194,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); @@ -212,8 +205,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/HttpRestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 13e8814c7ab..d88cd2b06d2 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -98,8 +97,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); @@ -110,8 +108,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 1ba7e6a051a..1e83f1ab46b 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,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(); @@ -117,8 +116,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 a453c0b662e..4734bae0599 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -151,8 +151,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 { @@ -160,8 +159,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 1201b887e72..008db45550c 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-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -122,8 +122,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/HttpTunnelPayloadTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index deefad83c1f..a9a18b47e0d 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-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -120,8 +120,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); @@ -134,8 +133,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/HttpTunnelServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index 03df57ebf7a..8f8125b16a2 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. @@ -299,11 +299,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(() -> { @@ -371,8 +369,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(); } @@ -442,17 +439,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 dda5bd588cf..1896fbab845 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -152,8 +152,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 d7b03bea168..342ac4ee07f 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 f34916ac736..91d31869981 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 3a5bf7a598e..32b10d79aff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 HibernateSearchElasticsearchExample { * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean. */ @Configuration - 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 3687c54a98d..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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 d421c0236c1..9ce867e7879 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 7886f668f0a..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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/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 f2b83f3429c..6a8853d26e2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/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 ab5157beaa6..8c8b4fbe860 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +60,11 @@ 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(UserService.class)).isSameAs( - context.getBean(UserConfiguration.class).myUserService()); - }); + this.contextRunner.withUserConfiguration(UserConfiguration.class).run((context) -> { + assertThat(context).hasSingleBean(UserService.class); + assertThat(context.getBean(UserService.class)) + .isSameAs(context.getBean(UserConfiguration.class).myUserService()); + }); } @Configuration 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 f96a222f23b..4db40b8a290 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 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 21d711c325c..9009440422e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 393ad57cb58..88a26320c3f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +34,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 @@ -44,9 +43,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 31d191e8bec..e289d9cea66 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. @@ -46,8 +46,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 3063633317b..20aa2098314 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 ce8cbac8a4d..ae863866db6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +33,13 @@ 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) { - OverrideAutoConfiguration annotation = AnnotatedElementUtils - .findMergedAnnotation(testClass, OverrideAutoConfiguration.class); + OverrideAutoConfiguration annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, + OverrideAutoConfiguration.class); if (annotation != null && !annotation.enabled()) { return new DisableAutoConfigurationContextCustomizer(); } @@ -50,15 +49,11 @@ class OverrideAutoConfigurationContextCustomizerFactory /** * {@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/ldap/DataLdapTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTypeExcludeFilter.java index 7f991b3eec2..3e4eec3d9be 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DataLdapTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter private final DataLdapTest annotation; DataLdapTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataLdapTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataLdapTest.class); } @Override 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 41b626b88be..e726e83a26d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DataMongoTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter private final DataMongoTest annotation; DataMongoTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataMongoTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataMongoTest.class); } @Override 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 ff1b10633e4..11c3e913d39 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 DataNeo4jTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter private final DataNeo4jTest annotation; DataNeo4jTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataNeo4jTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataNeo4jTest.class); } @Override 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 d9bca9d28b5..1dd66fd8375 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DataRedisTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter private final DataRedisTest annotation; DataRedisTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataRedisTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataRedisTest.class); } @Override 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/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 19ca1841204..7400246e546 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac @Override public ContextCustomizer createContextCustomizer(Class testClass, List configurationAttributes) { - TypeExcludeFilters annotation = AnnotatedElementUtils - .findMergedAnnotation(testClass, TypeExcludeFilters.class); + TypeExcludeFilters annotation = AnnotatedElementUtils.findMergedAnnotation(testClass, TypeExcludeFilters.class); if (annotation != null) { Set> filterClasses = new LinkedHashSet<>( Arrays.asList(annotation.value())); 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 94571c3730a..27d35df7d56 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 JdbcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final JdbcTest annotation; JdbcTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - JdbcTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JdbcTest.class); } @Override 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 1ea7fe0bc72..75a1c20f656 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 @@ -64,67 +64,56 @@ 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() { return new EmbeddedDataSourceFactory(this.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"); - registry.registerBeanDefinition(beanName, - createEmbeddedBeanDefinition(primary)); + logger.info("Replacing '" + beanName + "' DataSource bean with " + (primary ? "primary " : "") + + "embedded version"); + 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) { @@ -138,8 +127,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; } @@ -188,19 +176,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/JooqTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTypeExcludeFilter.java index 47385f46ea8..0f5251c03c4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 JooqTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final JooqTest annotation; JooqTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - JooqTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JooqTest.class); } @Override 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 14530e59612..24a7c3bec10 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 @@ -52,8 +52,7 @@ class JsonExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final JsonTest annotation; JsonExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - JsonTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, JsonTest.class); } @Override 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 b4d4797619d..5ead515e2d3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.ReflectionUtils; @Configuration @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 @@ -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); } @@ -146,14 +143,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 @@ -166,21 +161,17 @@ public class JsonTestersAutoConfiguration { /** * {@link BeanPostProcessor} used to initialize JSON testers. */ - private static class JsonMarshalTestersBeanPostProcessor - extends InstantiationAwareBeanPostProcessorAdapter { + private 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/DataJpaTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTypeExcludeFilter.java index 06995099006..390485bcf33 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DataJpaTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final DataJpaTest annotation; DataJpaTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - DataJpaTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, DataJpaTest.class); } @Override 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 f9fdfce9fee..bd63e034bd6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 d12abf862dd..c94dc8d8065 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +65,15 @@ public class AnnotationsPropertySource extends EnumerablePropertySource return Collections.unmodifiableMap(properties); } - private void collectProperties(Class root, Class source, - Map properties, Set> seen) { + private void collectProperties(Class root, Class source, Map properties, Set> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : getMergedAnnotations(root, source)) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { - PropertyMapping typeMapping = annotation.annotationType() - .getAnnotation(PropertyMapping.class); - for (Method attribute : annotation.annotationType() - .getDeclaredMethods()) { + PropertyMapping typeMapping = annotation.annotationType().getAnnotation(PropertyMapping.class); + for (Method attribute : annotation.annotationType().getDeclaredMethods()) { collectProperties(annotation, attribute, typeMapping, properties); } - collectProperties(root, annotation.annotationType(), properties, - seen); + collectProperties(root, annotation.annotationType(), properties, seen); } } collectProperties(root, source.getSuperclass(), properties, seen); @@ -90,8 +86,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource if (annotations != null) { for (Annotation annotation : annotations) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { - Annotation mergedAnnotation = findMergedAnnotation(root, - annotation.annotationType()); + Annotation mergedAnnotation = findMergedAnnotation(root, annotation.annotationType()); if (mergedAnnotation != null) { mergedAnnotations.add(mergedAnnotation); } @@ -101,21 +96,18 @@ public class AnnotationsPropertySource extends EnumerablePropertySource return mergedAnnotations; } - private Annotation findMergedAnnotation(Class source, - Class annotationType) { + private Annotation findMergedAnnotation(Class source, Class annotationType) { if (source == null) { return null; } - Annotation mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(source, - annotationType); + Annotation mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(source, annotationType); return (mergedAnnotation != null) ? mergedAnnotation : findMergedAnnotation(source.getSuperclass(), annotationType); } - private void collectProperties(Annotation annotation, Method attribute, - PropertyMapping typeMapping, Map properties) { - PropertyMapping attributeMapping = AnnotationUtils.getAnnotation(attribute, - PropertyMapping.class); + private void collectProperties(Annotation annotation, Method attribute, PropertyMapping typeMapping, + Map properties) { + PropertyMapping attributeMapping = AnnotationUtils.getAnnotation(attribute, PropertyMapping.class); SkipPropertyMapping skip = getMappingType(typeMapping, attributeMapping); if (skip == SkipPropertyMapping.YES) { return; @@ -124,8 +116,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource ReflectionUtils.makeAccessible(attribute); Object value = ReflectionUtils.invokeMethod(attribute, annotation); if (skip == SkipPropertyMapping.ON_DEFAULT_VALUE) { - Object defaultValue = AnnotationUtils.getDefaultValue(annotation, - attribute.getName()); + Object defaultValue = AnnotationUtils.getDefaultValue(annotation, attribute.getName()); if (ObjectUtils.nullSafeEquals(value, defaultValue)) { return; } @@ -133,8 +124,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource putProperties(name, value, properties); } - private SkipPropertyMapping getMappingType(PropertyMapping typeMapping, - PropertyMapping attributeMapping) { + private SkipPropertyMapping getMappingType(PropertyMapping typeMapping, PropertyMapping attributeMapping) { if (attributeMapping != null) { return attributeMapping.skip(); } @@ -144,8 +134,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource return SkipPropertyMapping.YES; } - private String getName(PropertyMapping typeMapping, PropertyMapping attributeMapping, - Method attribute) { + private String getName(PropertyMapping typeMapping, PropertyMapping attributeMapping, Method attribute) { String prefix = (typeMapping != null) ? typeMapping.value() : ""; String name = (attributeMapping != null) ? attributeMapping.value() : ""; if (!StringUtils.hasText(name)) { @@ -158,8 +147,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); @@ -172,8 +160,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 85b9f41144c..5d619352fe1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -73,8 +72,7 @@ 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(); Set> components = new LinkedHashSet<>(); Set> propertyMappings = new LinkedHashSet<>(); @@ -93,19 +91,17 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { beanClass = beanClass.getSuperclass(); } 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)); } return bean; } - private boolean isAnnotated(Annotation element, - Class annotationType) { + private boolean isAnnotated(Annotation element, Class annotationType) { try { - return element.annotationType().equals(annotationType) || AnnotationUtils - .findAnnotation(element.annotationType(), annotationType) != null; + return element.annotationType().equals(annotationType) + || AnnotationUtils.findAnnotation(element.annotationType(), annotationType) != null; } catch (Throwable ex) { return false; @@ -125,8 +121,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 f8c2f10eece..5b4d5cf9ba8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +71,16 @@ public class RestDocsAutoConfiguration { } @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 - @ConditionalOnClass({ RequestSpecification.class, - RestAssuredRestDocumentation.class }) + @ConditionalOnClass({ RequestSpecification.class, RestAssuredRestDocumentation.class }) @EnableConfigurationProperties(RestDocsProperties.class) static class RestDocsRestAssuredConfiguration { @@ -103,8 +100,8 @@ public class RestDocsAutoConfiguration { } @Bean - public RestDocsRestAssuredBuilderCustomizer restAssuredBuilderCustomizer( - RestDocsProperties properties, RequestSpecification configurer) { + public RestDocsRestAssuredBuilderCustomizer restAssuredBuilderCustomizer(RestDocsProperties properties, + RequestSpecification configurer) { return new RestDocsRestAssuredBuilderCustomizer(properties, configurer); } @@ -132,8 +129,7 @@ public class RestDocsAutoConfiguration { } @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 67d19e38f00..4b0c163281f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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 @@ -44,8 +43,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 4cc5b6ae02a..f638d6d65c5 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 -@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 493ff63a86b..e0a0b859fcb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { 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); } @@ -59,8 +57,7 @@ class RestClientExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final RestClientTest annotation; RestClientExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - RestClientTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, RestClientTest.class); } @Override 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 047c1cfad7a..eaddcd105b7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +29,8 @@ 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)); } } 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 698ec55ac26..ebd6b1867e2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,7 @@ class WebFluxTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final WebFluxTest annotation; WebFluxTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - WebFluxTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, WebFluxTest.class); } @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 7f1e1f9ddbb..c0a2bd12080 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 WebTestClientAutoConfiguration { @ConditionalOnBean(WebHandler.class) public WebTestClient webTestClient(ApplicationContext applicationContext, List customizers) { - WebTestClient.Builder builder = WebTestClient - .bindToApplicationContext(applicationContext).configureClient(); + WebTestClient.Builder builder = WebTestClient.bindToApplicationContext(applicationContext).configureClient(); for (WebTestClientBuilderCustomizer customizer : customizers) { customizer.customize(builder); } @@ -67,8 +66,7 @@ public class WebTestClientAutoConfiguration { @ConfigurationProperties(prefix = "spring.test.webtestclient") public SpringBootWebTestClientBuilderCustomizer springBootWebTestClientBuilderCustomizer( ObjectProvider> codecCustomizers) { - return new SpringBootWebTestClientBuilderCustomizer( - codecCustomizers.getIfAvailable(Collections::emptyList)); + return new SpringBootWebTestClientBuilderCustomizer(codecCustomizers.getIfAvailable(Collections::emptyList)); } } 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 f5694adf079..6d1f709f315 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MockMvcAutoConfiguration { private final WebMvcProperties webMvcProperties; - MockMvcAutoConfiguration(WebApplicationContext context, - ServerProperties serverProperties, WebMvcProperties webMvcProperties) { + MockMvcAutoConfiguration(WebApplicationContext context, ServerProperties serverProperties, + WebMvcProperties webMvcProperties) { this.context = context; this.serverProperties = serverProperties; this.webMvcProperties = webMvcProperties; @@ -74,11 +74,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); } @@ -97,8 +95,7 @@ public class MockMvcAutoConfiguration { return builder.build(); } - private static class MockMvcDispatcherServletCustomizer - implements DispatcherServletCustomizer { + private static class MockMvcDispatcherServletCustomizer implements DispatcherServletCustomizer { private final WebMvcProperties webMvcProperties; @@ -108,12 +105,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/MockMvcSecurityAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java index 9051a44aedc..6e4c6cb586d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcSecurityAutoConfiguration.java @@ -29,8 +29,7 @@ import org.springframework.context.annotation.Import; * @since 1.4.0 */ @Configuration -@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure", - havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = "spring.test.mockmvc", name = "secure", havingValue = "true", matchIfMissing = true) @Import({ SecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class, MockMvcSecurityConfiguration.class }) public class MockMvcSecurityAutoConfiguration { 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 245909ce148..fd9e15b6d1e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 3789bf7fdb0..751fb75676d 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,8 +39,7 @@ import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; @Configuration @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 { private final Environment environment; @@ -53,8 +52,7 @@ public class MockMvcWebClientAutoConfiguration { @ConditionalOnMissingBean({ WebClient.class, MockMvcWebClientBuilder.class }) @ConditionalOnBean(MockMvc.class) public MockMvcWebClientBuilder mockMvcWebClientBuilder(MockMvc mockMvc) { - return MockMvcWebClientBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebClient(this.environment)); + return MockMvcWebClientBuilder.mockMvcSetup(mockMvc).withDelegate(new LocalHostWebClient(this.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 97d2ebb3b5a..070984c8fd6 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 @@ -41,8 +41,7 @@ import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDr @Configuration @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 final Environment environment; @@ -56,8 +55,7 @@ public class MockMvcWebDriverAutoConfiguration { @ConditionalOnBean(MockMvc.class) public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc) { return MockMvcHtmlUnitDriverBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(this.environment, - BrowserVersion.CHROME)); + .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(this.environment, BrowserVersion.CHROME)); } @Bean 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 0fcf36510db..b7e966ed8a3 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. @@ -104,17 +104,13 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi } private void addFilters(ConfigurableMockMvcBuilder builder) { - ServletContextInitializerBeans initializers = new ServletContextInitializerBeans( - this.context); + ServletContextInitializerBeans initializers = new ServletContextInitializerBeans(this.context); initializers.stream().filter(AbstractFilterRegistrationBean.class::isInstance) - .map(AbstractFilterRegistrationBean.class::cast) - .filter(AbstractFilterRegistrationBean::isEnabled) - .forEach((registration) -> addFilter(builder, registration.getFilter(), - registration.getUrlPatterns())); + .map(AbstractFilterRegistrationBean.class::cast).filter(AbstractFilterRegistrationBean::isEnabled) + .forEach((registration) -> addFilter(builder, registration.getFilter(), registration.getUrlPatterns())); } - private void addFilter(ConfigurableMockMvcBuilder builder, Filter filter, - Collection urls) { + private void addFilter(ConfigurableMockMvcBuilder builder, Filter filter, Collection urls) { if (urls.isEmpty()) { builder.addFilters(filter); } @@ -229,8 +225,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; } @@ -259,8 +254,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) { 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 b18a2138fcb..33ad66f0f08 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +29,8 @@ 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), ""); } } 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 d958c5d5bfe..2dc7b2f4149 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class WebMvcTypeExcludeFilter extends AnnotationCustomizableTypeExcludeFilter { private final WebMvcTest annotation; WebMvcTypeExcludeFilter(Class testClass) { - this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, - WebMvcTest.class); + this.annotation = AnnotatedElementUtils.getMergedAnnotation(testClass, WebMvcTest.class); } @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 75e427d9a82..0d28ec0f3e1 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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().keySet() - .contains(this.autoConfigurationClass.getName()); + .get((ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory()); + return report.getConditionAndOutcomesBySource().keySet().contains(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/OverrideAutoConfigurationEnabledTrueIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java index a223ff90d2d..d08ece69512 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/OverrideAutoConfigurationEnabledTrueIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 OverrideAutoConfigurationEnabledTrueIntegrationTests { public void autoConfiguredContext() { ApplicationContext context = this.context; assertThat(context.getBean(ExampleSpringBootApplication.class)).isNotNull(); - assertThat(context.getBean(ConfigurationPropertiesBindingPostProcessor.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/SpringBootDependencyInjectionTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java index d27fec0fdb1..e5c366c2643 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringBootDependencyInjectionTestExecutionListenerTests { @Test public void orderShouldBeSameAsDependencyInjectionTestExecutionListener() { Ordered injectionListener = new DependencyInjectionTestExecutionListener(); - assertThat(this.reportListener.getOrder()) - .isEqualTo(injectionListener.getOrder()); + assertThat(this.reportListener.getOrder()).isEqualTo(injectionListener.getOrder()); } @Test 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 8057da18421..1934097d47c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/ldap/DataLdapTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java index b64432ca7e5..7e4427c2916 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. @@ -63,11 +63,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 bccdbbf9a48..15cf78f7579 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 dd925019cb7..da9aac4088c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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 0b6414a2789..d5872115f64 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +77,11 @@ public class DataNeo4jTestIntegrationTests { 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=bolt://localhost:" + neo4j.getMappedPort()) + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of("spring.data.neo4j.uri=bolt://localhost:" + neo4j.getMappedPort()) .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 825b557476e..e410bd39455 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 @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez */ @RunWith(SpringRunner.class) -@ContextConfiguration( - initializers = DataNeo4jTestWithIncludeFilterIntegrationTests.Initializer.class) +@ContextConfiguration(initializers = DataNeo4jTestWithIncludeFilterIntegrationTests.Initializer.class) @DataNeo4jTest(includeFilters = @Filter(Service.class)) public class DataNeo4jTestWithIncludeFilterIntegrationTests { @@ -54,14 +53,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=bolt://localhost:" + neo4j.getMappedPort()) + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of("spring.data.neo4j.uri=bolt://localhost:" + neo4j.getMappedPort()) .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 d493bdd91d4..fa087d97b1a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +84,10 @@ public class DataRedisTestIntegrationTests { 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/DataRedisTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestWithIncludeFilterIntegrationTests.java index 19f01be375c..d69c9f6e16c 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 @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Jayaram Pradhan */ @RunWith(SpringRunner.class) -@ContextConfiguration( - initializers = DataRedisTestWithIncludeFilterIntegrationTests.Initializer.class) +@ContextConfiguration(initializers = DataRedisTestWithIncludeFilterIntegrationTests.Initializer.class) @DataRedisTest(includeFilters = @Filter(Service.class)) public class DataRedisTestWithIncludeFilterIntegrationTests { @@ -61,12 +60,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 81c069f6447..dd66b642f54 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a313f7dd2fe..606a6cda5ec 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 7730559a1ac..41c58bf216b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 c4197687dd8..a4ac05114b6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 091c80ac0f5..3d8b39914d4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 f29eb076028..82555d71f7b 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 @@ -73,8 +73,7 @@ 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"); } @@ -86,14 +85,12 @@ public class JdbcTestIntegrationTests { @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 e51e371be95..64870e63779 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 6a6fb9363c9..fc4d3ebd676 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 0f5ba609b95..9edb4fb4060 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 9716258270c..4bf613ad0fb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 00d0abc1d14..e34801b1de0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 3e2f2eea076..2a22f65c0d7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 8f4f694a2ad..829597489f8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 b016802515a..979d58bd28f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 @@ -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 41cd7e96a98..f590b0817a0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 57ccd90c742..66bbeac9033 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +59,13 @@ 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); } @@ -79,14 +78,12 @@ public class JooqTestIntegrationTests { @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 610f6b01890..646349b76af 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 9df73975cb5..c16414e4bd9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); } @@ -51,11 +51,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 aaed4824a5e..374fc6784f9 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 @@ -43,8 +43,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 { @Rule @@ -76,12 +75,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"); } @@ -96,8 +93,7 @@ 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"); } @@ -109,14 +105,12 @@ public class DataJpaTestIntegrationTests { @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 8a3121a53ba..a2225eb1284 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 698cfb38b1b..e2c4a94809f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 9f76fc95f6a..e9716183ac1 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -191,8 +190,8 @@ public class TestEntityManagerTests { public void getIdForTypeWhenTypeIsWrongShouldThrowException() { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); - this.thrown.expectMessage("ID mismatch: Object of class [java.lang.Integer] " - + "must be an instance of class java.lang.Long"); + this.thrown.expectMessage( + "ID mismatch: Object of class [java.lang.Integer] " + "must be an instance of class java.lang.Long"); this.testEntityManager.getId(entity, Long.class); } @@ -207,8 +206,7 @@ public class TestEntityManagerTests { @Test public void getEntityManagerShouldGetEntityManager() { bindEntityManager(); - assertThat(this.testEntityManager.getEntityManager()) - .isEqualTo(this.entityManager); + assertThat(this.testEntityManager.getEntityManager()).isEqualTo(this.entityManager); } @Test 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 f13012eac6e..9a5f334c074 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 @@ -47,8 +47,7 @@ public class AnnotationsPropertySourceTests { @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(); } @@ -62,40 +61,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(); } @@ -103,10 +97,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); @@ -125,25 +118,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"); @@ -151,8 +140,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"); } @@ -164,8 +152,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"); } @@ -180,15 +167,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(); } @@ -281,9 +266,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 { } @@ -384,8 +368,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 34287d08d8d..656084eb811 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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); @@ -65,35 +62,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"); @@ -101,8 +91,7 @@ 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); 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 cce336562ab..1f5c55b9932 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +64,11 @@ public class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTes @Test public void snippetGeneration() throws Exception { - this.mvc.perform(get("/")).andDo(this.documentationHandler.document(links( - linkWithRel("self").description("Canonical location of this resource")))); - File defaultSnippetsDir = new File( - "target/generated-snippets/snippet-generation"); + this.mvc.perform(get("/")).andDo(this.documentationHandler + .document(links(linkWithRel("self").description("Canonical location of this resource")))); + File defaultSnippetsDir = new File("target/generated-snippets/snippet-generation"); assertThat(defaultSnippetsDir).exists(); - assertThat(new File(defaultSnippetsDir, "curl-request.md")) - .has(contentContaining("'http://localhost:8080/'")); + assertThat(new File(defaultSnippetsDir, "curl-request.md")).has(contentContaining("'http://localhost:8080/'")); assertThat(new File(defaultSnippetsDir, "links.md")).isFile(); } @@ -79,8 +77,7 @@ public class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTes } @TestConfiguration - public static class CustomizationConfiguration - implements RestDocsMockMvcConfigurationCustomizer { + public static class CustomizationConfiguration implements RestDocsMockMvcConfigurationCustomizer { @Bean public RestDocumentationResultHandler restDocumentation() { 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 4b96d797ecb..5092421064c 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 MockMvcRestDocsAutoConfigurationIntegrationTests { assertThat(defaultSnippetsDir).exists(); assertThat(new File(defaultSnippetsDir, "curl-request.adoc")) .has(contentContaining("'https://api.example.com/'")); - assertThat(new File(defaultSnippetsDir, "http-request.adoc")) - .has(contentContaining("api.example.com")); + assertThat(new File(defaultSnippetsDir, "http-request.adoc")).has(contentContaining("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 d1fe000a58f..18841a6af72 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +67,13 @@ 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("target/generated-snippets/default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(new File(defaultSnippetsDir, "curl-request.md")) .has(contentContaining("'https://api.example.com/'")); - assertThat(new File(defaultSnippetsDir, "http-request.md")) - .has(contentContaining("api.example.com")); + assertThat(new File(defaultSnippetsDir, "http-request.md")).has(contentContaining("api.example.com")); assertThat(new File(defaultSnippetsDir, "http-response.md")).isFile(); } @@ -84,8 +82,7 @@ public class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegratio } @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-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 f2f5c7927b2..af60f51f9da 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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("target/generated-snippets/default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(new File(defaultSnippetsDir, "curl-request.adoc")) .has(contentContaining("'https://api.example.com/'")); - assertThat(new File(defaultSnippetsDir, "http-request.adoc")) - .has(contentContaining("api.example.com")); + assertThat(new File(defaultSnippetsDir, "http-request.adoc")).has(contentContaining("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/WebTestClientRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java index 8bc190ecf2a..c7ebf9e2b7f 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,14 +52,12 @@ public class WebTestClientRestDocsAutoConfigurationIntegrationTests { @Test public void defaultSnippetsAreWritten() throws Exception { - this.webTestClient.get().uri("/").exchange().expectBody() - .consumeWith(document("default-snippets")); + this.webTestClient.get().uri("/").exchange().expectBody().consumeWith(document("default-snippets")); File defaultSnippetsDir = new File("target/generated-snippets/default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(new File(defaultSnippetsDir, "curl-request.adoc")) .has(contentContaining("'https://api.example.com/'")); - assertThat(new File(defaultSnippetsDir, "http-request.adoc")) - .has(contentContaining("api.example.com")); + assertThat(new File(defaultSnippetsDir, "http-request.adoc")).has(contentContaining("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/MockMvcSecurityAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java index f8a5f10e7a1..18f0ec51d89 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +54,13 @@ public class MockMvcSecurityAutoConfigurationIntegrationTests { @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/AutoConfigureWebClientWithRestTemplateIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureWebClientWithRestTemplateIntegrationTests.java index ba57fa3c841..2cd042154fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 72f6df87c9e..7a97773666f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 82e2f700104..f95c3fe3346 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 RestClientTestNoComponentIntegrationTests { @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 008b6be61a4..b445f2f1b41 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +59,19 @@ public class RestClientTestTwoComponentsIntegrationTests { public void serverShouldNotWork() { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Unable to use auto-configured"); - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML)); } @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 6c49b3e5959..902d3f44f4c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 ea9862509a9..64c9024072c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 0240911376f..a77948d4275 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 WebTestClientAutoConfigurationTests { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebTestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); @Test public void shouldNotBeConfiguredWithoutWebHandler() { @@ -59,23 +58,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)); }); } 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 26644230301..d4028292912 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ExampleIdConverter implements GenericConverter { @Nullable @Override - public Object convert(@Nullable Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(@Nullable 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 873617b4e49..9f014cd3621 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +38,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 878e53903eb..fc29a902f9f 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 @@ -43,14 +43,12 @@ 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)); } } 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 ba1b856d4cd..be814c59884 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 f0dad2ec868..ed93849e101 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 06b24a18e5c..5f1f671e1c6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 2a6372e1ae4..1d577435dfa 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 @@ -39,9 +39,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 { @@ -53,20 +52,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 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 d581baae671..292866fd213 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,26 +44,22 @@ 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)); } } 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 e4428d8c1b3..b4b073cec0c 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 @@ -45,8 +45,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(); @@ -58,8 +57,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(); @@ -71,8 +69,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(); @@ -84,8 +81,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(); @@ -97,8 +93,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(); @@ -108,10 +103,8 @@ public class WebMvcTypeExcludeFilterTests { assertThat(excludes(filter, ExampleRepository.class)).isTrue(); } - 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); } @@ -135,8 +128,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 7287ea822c5..da790c1de2a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 a4685a57f3b..c8d2a153228 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a0755cf8b61..1c5e8dac194 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.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 00444592c5f..98ceb65475a 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 @@ -35,8 +35,7 @@ class HateoasController { @RequestMapping("/resource") public Resource> resource() { - return new Resource<>(new HashMap(), - new Link("self", "https://api.example.com")); + return new Resource<>(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 061c6d2ec2b..36fc3b5725b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 cd7a30db421..363994126ac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,26 +56,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 fb8e94757e1..ee62fd35d9a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 a704d6aac1e..320594ade6e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ public class WebMvcTestHateoasIntegrationTests { @Test public void plainResponse() throws Exception { - this.mockMvc.perform(get("/hateoas/plain")).andExpect(header() - .string(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")); + this.mockMvc.perform(get("/hateoas/plain")) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")); } @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 e7cf5be2352..f482a08671b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/WebMvcTestPrintAlwaysIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintAlwaysIntegrationTests.java index f48261ccfe1..591c43d0a51 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 9bc973a13cc..ab77fa604c4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +43,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 ef6a868a8e5..fe93a361640 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 5d70ae2a0b0..1f8d36c40c6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 4c04693f150..d4b0875e1fd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index c5998db12d4..f7cf87c5d15 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 { @Rule 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 3ee785f9c14..6ea4efffaf5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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.filters) { if (filter.test(name)) { throw new ClassNotFoundException(); 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 05bb98d830b..03943f0d129 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +76,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); } @@ -102,15 +98,14 @@ 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"); } @SuppressWarnings("unchecked") - 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); } @@ -166,12 +161,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; } } @@ -181,8 +173,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(); @@ -193,13 +184,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) { @@ -244,12 +233,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()) { @@ -261,13 +248,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); } } } @@ -281,15 +267,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 = new StandardAnnotationMetadata( - testClass); + AnnotationMetadata testClassMetadata = new StandardAnnotationMetadata(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; } @@ -306,12 +289,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)) { @@ -331,17 +312,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/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/SpringBootConfigurationFinder.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java index 70ba9a7e13d..348c4afd13f 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootConfigurationFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.ClassUtils; */ final class SpringBootConfigurationFinder { - private static final Map> cache = Collections - .synchronizedMap(new Cache(40)); + private static final Map> cache = Collections.synchronizedMap(new Cache(40)); private final ClassPathScanningCandidateComponentProvider scanner; SpringBootConfigurationFinder() { this.scanner = new ClassPathScanningCandidateComponentProvider(false); - this.scanner.addIncludeFilter( - new AnnotationTypeFilter(SpringBootConfiguration.class)); + this.scanner.addIncludeFilter(new AnnotationTypeFilter(SpringBootConfiguration.class)); this.scanner.setResourcePattern("*.class"); } @@ -67,10 +65,8 @@ final class SpringBootConfigurationFinder { Set components = this.scanner.findCandidateComponents(source); if (!components.isEmpty()) { Assert.state(components.size() == 1, - () -> "Found multiple @SpringBootConfiguration annotated classes " - + components); - return ClassUtils.resolveClassName( - components.iterator().next().getBeanClassName(), null); + () -> "Found multiple @SpringBootConfiguration 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/SpringBootContextLoader.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java index 0135e3e6137..4f51ecae1d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +78,13 @@ import org.springframework.web.context.support.GenericWebApplicationContext; public class SpringBootContextLoader extends AbstractContextLoader { @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)); @@ -98,16 +93,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)) { @@ -145,11 +137,8 @@ public class SpringBootContextLoader extends AbstractContextLoader { return new StandardEnvironment(); } - 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); } @@ -173,10 +162,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))); } /** @@ -191,8 +179,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)); @@ -203,15 +191,14 @@ 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) { - SpringBootTest annotation = AnnotatedElementUtils - .findMergedAnnotation(config.getTestClass(), SpringBootTest.class); + SpringBootTest annotation = AnnotatedElementUtils.findMergedAnnotation(config.getTestClass(), + SpringBootTest.class); if (annotation != null && annotation.webEnvironment().isEmbedded()) { return true; } @@ -219,12 +206,10 @@ public class SpringBootContextLoader extends AbstractContextLoader { } @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); } } @@ -239,14 +224,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 @@ -266,21 +250,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)); } } @@ -309,8 +290,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 c7581b1f0bf..7b5d9806c0c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +83,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()) { @@ -113,8 +110,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); } @@ -133,8 +129,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) { @@ -144,51 +139,39 @@ 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)) { + && (webEnvironment.isEmbedded() || webEnvironment == WebEnvironment.MOCK)) { WebAppConfiguration webAppConfiguration = AnnotatedElementUtils - .findMergedAnnotation(mergedConfig.getTestClass(), - WebAppConfiguration.class); - String resourceBasePath = (webAppConfiguration != null) - ? webAppConfiguration.value() : "src/main/webapp"; - mergedConfig = new WebMergedContextConfiguration(mergedConfig, - resourceBasePath); + .findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class); + String resourceBasePath = (webAppConfiguration != null) ? webAppConfiguration.value() + : "src/main/webapp"; + 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); } @@ -208,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; @@ -232,20 +212,15 @@ 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 SpringBootConfigurationFinder() - .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()); + Class found = new SpringBootConfigurationFinder().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()); return merge(found, classes); } @@ -265,8 +240,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(); @@ -294,8 +268,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); @@ -341,13 +314,11 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr && getAnnotation(WebAppConfiguration.class, testClass) != null) { 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 T getAnnotation(Class annotationType, - Class testClass) { + private T getAnnotation(Class annotationType, Class testClass) { return AnnotatedElementUtils.getMergedAnnotation(testClass, annotationType); } @@ -357,10 +328,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()); } /** @@ -371,13 +341,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 29b6923c039..85ae45a60c4 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. @@ -78,13 +78,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; } @@ -122,8 +121,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) { @@ -170,8 +168,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) { @@ -195,8 +192,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); @@ -222,8 +218,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()); @@ -269,19 +264,16 @@ 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); if (names.length > 1) { - 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 = (names.length != 0) ? getApplicationContext().getBean(names[0], type) - : null; - return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type, - getApplicationContext()); + T bean = (names.length != 0) ? getApplicationContext().getBean(names[0], type) : null; + return Assertions.assertThat(bean).as("Bean of type <%s> from <%s>", type, getApplicationContext()); } /** @@ -299,12 +291,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()); } /** @@ -327,8 +317,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)) { @@ -336,8 +326,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()); } @@ -386,8 +375,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()); @@ -419,8 +407,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; } @@ -448,10 +435,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); } /** @@ -465,14 +450,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); } @@ -484,46 +467,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 c419c9367b5..1e167c5de8b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.Assert; * @see AssertableReactiveWebApplicationContext * @see ApplicationContextAssert */ -public interface ApplicationContextAssertProvider extends - ApplicationContext, AssertProvider>, Closeable { +public interface ApplicationContextAssertProvider + extends ApplicationContext, AssertProvider>, Closeable { /** * Return an assert for AspectJ. @@ -100,17 +100,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 ea095e5a48a..dbf1bb0f17c 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.context.ConfigurableApplicationContext; * @see ApplicationContextRunner * @see ApplicationContext */ -public interface AssertableApplicationContext - extends ApplicationContextAssertProvider { +public interface AssertableApplicationContext extends ApplicationContextAssertProvider { /** * Factory method to create a new {@link AssertableApplicationContext} instance. @@ -44,8 +43,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 8a32c4d64e5..b331193c6d7 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.boot.web.reactive.context.ReactiveWebApplicationConte * @see ReactiveWebApplicationContext */ public interface AssertableReactiveWebApplicationContext extends - ApplicationContextAssertProvider, - ReactiveWebApplicationContext { + ApplicationContextAssertProvider, ReactiveWebApplicationContext { /** * Factory method to create a new {@link AssertableReactiveWebApplicationContext} @@ -47,8 +46,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 f007c517441..59d200569c0 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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, - WebApplicationContext { + extends ApplicationContextAssertProvider, WebApplicationContext { /** * 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 f11d76f238e..c2240a3388c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 TestTypeExcludeFilter extends TypeExcludeFilter { "org.junit.platform.commons.annotation.Testable" }; @Override - public boolean match(MetadataReader metadataReader, - MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { if (isTestConfiguration(metadataReader)) { return true; } @@ -50,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; } } @@ -63,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 647afab35ee..a4c9a8f739a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public abstract class AbstractApplicationContextRunner contextFactory) { - this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), - TestPropertyValues.empty(), null, null, Collections.emptyList()); + this(contextFactory, Collections.emptyList(), TestPropertyValues.empty(), TestPropertyValues.empty(), null, + null, Collections.emptyList()); } /** @@ -132,9 +132,8 @@ public abstract class AbstractApplicationContextRunner contextFactory, - List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, + List> initializers, TestPropertyValues environmentProperties, + TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent, List configurations) { Assert.notNull(contextFactory, "ContextFactory must not be null"); Assert.notNull(environmentProperties, "EnvironmentProperties must not be null"); @@ -156,12 +155,10 @@ public abstract class AbstractApplicationContextRunner initializer) { + public SELF withInitializer(ApplicationContextInitializer 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.configurations); + return newInstance(this.contextFactory, add(this.initializers, initializer), this.environmentProperties, + this.systemProperties, this.classLoader, this.parent, this.configurations); } /** @@ -175,9 +172,8 @@ public abstract class AbstractApplicationContextRunner contextFactory, - List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, + List> initializers, TestPropertyValues environmentProperties, + TestPropertyValues systemProperties, ClassLoader classLoader, ApplicationContext parent, List configurations); /** @@ -304,12 +295,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() { 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 7165e828860..c6d3d8d9708 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +54,25 @@ 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 configurations) { - super(contextFactory, initializers, environmentProperties, systemProperties, - classLoader, parent, configurations); - } - - @Override - protected ApplicationContextRunner newInstance( - Supplier contextFactory, - List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List configurations) { - return new ApplicationContextRunner(contextFactory, initializers, - environmentProperties, systemProperties, classLoader, parent, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List configurations) { + super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent, configurations); } + @Override + protected ApplicationContextRunner newInstance(Supplier contextFactory, + List> initializers, + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List configurations) { + return new ApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties, + classLoader, parent, 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 19a367cf1ab..954069bbe4f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +54,26 @@ 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 configurations) { - super(contextFactory, initializers, environmentProperties, systemProperties, - classLoader, parent, configurations); + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List configurations) { + super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent, + configurations); } @Override protected ReactiveWebApplicationContextRunner newInstance( Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List configurations) { - return new ReactiveWebApplicationContextRunner(contextFactory, initializers, - environmentProperties, systemProperties, classLoader, parent, - configurations); + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List configurations) { + return new ReactiveWebApplicationContextRunner(contextFactory, initializers, environmentProperties, + systemProperties, classLoader, parent, 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 847b3320602..fd2c882bd8a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +58,25 @@ 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 configurations) { - super(contextFactory, initializers, environmentProperties, systemProperties, - classLoader, parent, configurations); + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List configurations) { + super(contextFactory, initializers, environmentProperties, systemProperties, classLoader, parent, + configurations); } @Override - protected WebApplicationContextRunner newInstance( - Supplier contextFactory, + protected WebApplicationContextRunner newInstance(Supplier contextFactory, List> initializers, - TestPropertyValues environmentProperties, TestPropertyValues systemProperties, - ClassLoader classLoader, ApplicationContext parent, - List configurations) { - return new WebApplicationContextRunner(contextFactory, initializers, - environmentProperties, systemProperties, classLoader, parent, - configurations); + TestPropertyValues environmentProperties, TestPropertyValues systemProperties, ClassLoader classLoader, + ApplicationContext parent, List configurations) { + return new WebApplicationContextRunner(contextFactory, initializers, environmentProperties, systemProperties, + classLoader, parent, 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 29f4915ffc9..ad2ff53cf4e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -309,8 +309,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)"); } @@ -321,8 +320,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 @@ -332,8 +330,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); } @@ -345,8 +342,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 @@ -359,8 +355,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; } @@ -378,8 +373,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); @@ -391,12 +385,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 0f82f2fa1ac..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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 afe00a22f16..38c5d42b2ec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +79,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; @@ -93,8 +91,7 @@ public class JacksonTester extends AbstractJsonMarshalTester { } @Override - protected T readObject(InputStream inputStream, ResolvableType type) - throws IOException { + protected T readObject(InputStream inputStream, ResolvableType type) throws IOException { return getObjectReader(type).readValue(inputStream); } @@ -146,8 +143,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); } @@ -158,8 +154,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); } /** @@ -172,8 +167,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/JsonContentAssert.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java index 76095c73ce2..6cf591811ef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JsonContentAssert extends AbstractAssert resourceLoadClass, Charset charset, - CharSequence json) { + public JsonContentAssert(Class resourceLoadClass, Charset charset, CharSequence json) { super(json, JsonContentAssert.class); this.loader = new JsonLoader(resourceLoadClass, charset); } @@ -198,8 +197,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)); } @@ -212,8 +210,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)); } @@ -313,8 +308,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)); } @@ -392,8 +383,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)); } @@ -598,8 +586,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)); } @@ -625,8 +611,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)); } @@ -707,8 +687,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)); } @@ -907,10 +875,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")); } /** @@ -921,10 +888,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")); } /** @@ -935,10 +900,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")); } /** @@ -951,10 +914,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")); } /** @@ -968,15 +929,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); @@ -984,14 +943,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 b2973870e28..4f3063c65d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,28 +63,23 @@ class DefinitionsParser { } private void parseElement(AnnotatedElement element) { - for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element, - MockBean.class, MockBeans.class)) { + for (MockBean annotation : AnnotationUtils.getRepeatableAnnotations(element, MockBean.class, MockBeans.class)) { parseMockBeanAnnotation(annotation, element); } - for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element, - SpyBean.class, SpyBeans.class)) { + for (SpyBean annotation : AnnotationUtils.getRepeatableAnnotations(element, SpyBean.class, SpyBeans.class)) { parseSpyBeanAnnotation(annotation, element); } } 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 +87,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 723141ee835..390af9d6240 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +74,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 final Set definitions; @@ -123,16 +121,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)) { @@ -145,19 +140,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); @@ -168,8 +159,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); } @@ -178,13 +169,12 @@ 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); - beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, - beanName); + beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, beanName); if (registry.containsBeanDefinition(transformedBeanName)) { registry.removeBeanDefinition(transformedBeanName); } @@ -199,13 +189,11 @@ 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()); definition.setFactoryBeanName(BEAN_NAME); definition.setFactoryMethodName("createMock"); - definition.getConstructorArgumentValues().addIndexedArgumentValue(0, - mockDefinition); + definition.getConstructorArgumentValues().addIndexedArgumentValue(0, mockDefinition); if (mockDefinition.getQualifier() != null) { mockDefinition.getQualifier().applyTo(definition); } @@ -222,9 +210,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return mockDefinition.createMock(name + " bean"); } - 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(); } @@ -235,14 +222,12 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda if (existingBeans.size() == 1) { return existingBeans.iterator().next(); } - 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 registerSpy(ConfigurableListableBeanFactory beanFactory, - BeanDefinitionRegistry registry, SpyDefinition definition, Field field) { + private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, + SpyDefinition definition, Field field) { String[] existingBeans = getExistingBeans(beanFactory, definition.getTypeToSpy()); if (ObjectUtils.isEmpty(existingBeans)) { createSpy(registry, definition, field); @@ -252,12 +237,10 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private Set findCandidateBeans(ConfigurableListableBeanFactory beanFactory, - MockDefinition mockDefinition) { + private Set findCandidateBeans(ConfigurableListableBeanFactory beanFactory, MockDefinition mockDefinition) { QualifierDefinition qualifier = mockDefinition.getQualifier(); Set candidates = new TreeSet<>(); - for (String candidate : getExistingBeans(beanFactory, - mockDefinition.getTypeToMock())) { + for (String candidate : getExistingBeans(beanFactory, mockDefinition.getTypeToMock())) { if (qualifier == null || qualifier.matches(beanFactory, candidate)) { candidates.add(candidate); } @@ -265,16 +248,13 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda return candidates; } - private String[] getExistingBeans(ConfigurableListableBeanFactory beanFactory, - ResolvableType type) { - Set beans = new LinkedHashSet<>( - Arrays.asList(beanFactory.getBeanNamesForType(type))); + private String[] getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) { + Set beans = new LinkedHashSet<>(Arrays.asList(beanFactory.getBeanNamesForType(type))); String resolvedTypeName = type.resolve(Object.class).getName(); for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class)) { beanName = BeanFactoryUtils.transformedBeanName(beanName); BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); - if (resolvedTypeName - .equals(beanDefinition.getAttribute(FACTORY_BEAN_OBJECT_TYPE))) { + if (resolvedTypeName.equals(beanDefinition.getAttribute(FACTORY_BEAN_OBJECT_TYPE))) { beans.add(beanName); } } @@ -291,25 +271,20 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - private void createSpy(BeanDefinitionRegistry registry, SpyDefinition definition, - Field field) { - RootBeanDefinition beanDefinition = new RootBeanDefinition( - definition.getTypeToSpy().resolve()); - String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, - registry); + private void createSpy(BeanDefinitionRegistry registry, SpyDefinition definition, Field field) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(definition.getTypeToSpy().resolve()); + String beanName = this.beanNameGenerator.generateBeanName(beanDefinition, registry); registry.registerBeanDefinition(beanName, beanDefinition); registerSpy(definition, field, beanName); } - private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition definition, - Field field, String[] existingBeans) { + private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition definition, Field field, + String[] existingBeans) { try { - registerSpy(definition, field, - determineBeanName(existingBeans, definition, registry)); + registerSpy(definition, field, determineBeanName(existingBeans, definition, registry)); } catch (RuntimeException ex) { - throw new IllegalStateException( - "Unable to register spy bean " + definition.getTypeToSpy(), ex); + throw new IllegalStateException("Unable to register spy bean " + definition.getTypeToSpy(), ex); } } @@ -321,19 +296,17 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda if (existingBeans.length == 1) { return existingBeans[0]; } - return determinePrimaryCandidate(registry, existingBeans, - definition.getTypeToSpy()); + return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy()); } - private String determinePrimaryCandidate(BeanDefinitionRegistry registry, - String[] candidateBeanNames, ResolvableType type) { + private String determinePrimaryCandidate(BeanDefinitionRegistry registry, String[] 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.length, + throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.length, "more than one 'primary' bean found among candidates: " + Arrays.asList(candidateBeanNames)); } @@ -351,8 +324,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda } } - protected Object createSpyIfNecessary(Object bean, String beanName) - throws BeansException { + protected Object createSpyIfNecessary(Object bean, String beanName) throws BeansException { SpyDefinition definition = this.spies.get(beanName); if (definition != null) { bean = definition.createSpy(beanName, bean); @@ -361,11 +333,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; } @@ -378,8 +348,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); } @@ -416,8 +385,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); } @@ -429,13 +397,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); @@ -447,10 +413,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; } @@ -461,8 +425,7 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda * {@link BeanPostProcessor} to handle {@link SpyBean} definitions. 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(); @@ -478,14 +441,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 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; } @@ -498,11 +459,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 e449e1587d0..fc17ce074f7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/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/util/EnvironmentTestUtils.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java index ac26c2e00e4..53f7e4e4417 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/EnvironmentTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 abstract class EnvironmentTestUtils { * @param context the context with an environment to modify * @param pairs the name:value pairs */ - public static void addEnvironment(ConfigurableApplicationContext context, - String... pairs) { + public static void addEnvironment(ConfigurableApplicationContext context, String... pairs) { addEnvironment(context.getEnvironment(), pairs); } @@ -55,8 +54,7 @@ public abstract class EnvironmentTestUtils { * @param environment the environment to modify * @param pairs the name:value pairs */ - public static void addEnvironment(ConfigurableEnvironment environment, - String... pairs) { + public static void addEnvironment(ConfigurableEnvironment environment, String... pairs) { addEnvironment("test", environment, pairs); } @@ -67,8 +65,7 @@ public abstract class EnvironmentTestUtils { * @param name the property source name * @param pairs the name:value pairs */ - public static void addEnvironment(String name, ConfigurableEnvironment environment, - String... pairs) { + public static void addEnvironment(String name, ConfigurableEnvironment environment, String... pairs) { MutablePropertySources sources = environment.getPropertySources(); Map map = getOrAdd(sources, name); for (String pair : pairs) { @@ -80,8 +77,7 @@ public abstract class EnvironmentTestUtils { } @SuppressWarnings("unchecked") - private static Map getOrAdd(MutablePropertySources sources, - String name) { + private static Map getOrAdd(MutablePropertySources sources, String name) { if (sources.contains(name)) { return (Map) sources.get(name).getSource(); } 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/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: getRequestFactoryClass( - RestTemplate restTemplate) { + private Class getRequestFactoryClass(RestTemplate restTemplate) { ClientHttpRequestFactory requestFactory = restTemplate.getRequestFactory(); - if (InterceptingClientHttpRequestFactory.class - .isAssignableFrom(requestFactory.getClass())) { - Field requestFactoryField = ReflectionUtils.findField(RestTemplate.class, - "requestFactory"); + if (InterceptingClientHttpRequestFactory.class.isAssignableFrom(requestFactory.getClass())) { + Field requestFactoryField = ReflectionUtils.findField(RestTemplate.class, "requestFactory"); ReflectionUtils.makeAccessible(requestFactoryField); - requestFactory = (ClientHttpRequestFactory) ReflectionUtils - .getField(requestFactoryField, restTemplate); + requestFactory = (ClientHttpRequestFactory) ReflectionUtils.getField(requestFactoryField, restTemplate); } return requestFactory.getClass(); } - private void addAuthentication(RestTemplate restTemplate, String username, - String password) { + private void addAuthentication(RestTemplate restTemplate, String username, String password) { if (username == null) { return; } @@ -215,8 +206,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); } @@ -233,8 +223,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); } @@ -266,8 +256,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); } @@ -284,8 +274,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); } @@ -299,8 +289,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); } @@ -314,8 +303,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); } @@ -329,8 +317,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); } @@ -363,8 +350,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); } @@ -386,8 +372,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); } @@ -428,8 +413,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); } @@ -452,8 +437,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); } @@ -472,10 +457,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); } /** @@ -497,8 +480,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); } @@ -521,9 +504,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); } @@ -542,10 +524,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); } /** @@ -562,8 +543,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); } @@ -581,8 +561,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); } @@ -619,8 +598,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); } @@ -642,8 +621,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); } @@ -662,10 +641,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); } @@ -691,8 +668,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); } @@ -716,8 +692,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); } @@ -731,8 +706,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); } @@ -764,11 +738,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); } /** @@ -788,11 +760,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); } /** @@ -809,11 +779,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); } /** @@ -837,11 +805,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); } /** @@ -865,11 +831,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); } /** @@ -892,11 +856,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); } /** @@ -914,10 +876,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); } /** @@ -937,10 +898,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); } /** @@ -961,10 +921,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); } /** @@ -985,10 +943,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); } /** @@ -1007,8 +963,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); } /** @@ -1034,27 +989,22 @@ public class TestRestTemplate { .messageConverters(getRestTemplate().getMessageConverters()) .interceptors(getRestTemplate().getInterceptors()) .uriTemplateHandler(getRestTemplate().getUriTemplateHandler()).build(); - TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, - password, this.httpClientOptions); - testRestTemplate.getRestTemplate() - .setErrorHandler(getRestTemplate().getErrorHandler()); + TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, password, + this.httpClientOptions); + testRestTemplate.getRestTemplate().setErrorHandler(getRestTemplate().getErrorHandler()); return testRestTemplate; } @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; } @@ -1084,19 +1034,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()); @@ -1106,9 +1053,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) { @@ -1124,8 +1069,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 07f6db91e0e..e5c583a51f7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 TestRestTemplateContextCustomizer implements ContextCustomizer { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { - SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation( - mergedContextConfiguration.getTestClass(), SpringBootTest.class); + SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedContextConfiguration.getTestClass(), + SpringBootTest.class); if (annotation.webEnvironment().isEmbedded()) { registerTestRestTemplate(context); } @@ -67,11 +67,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 @@ -108,10 +106,8 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { - if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory) this.beanFactory, + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { + if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory, TestRestTemplate.class).length == 0) { registry.registerBeanDefinition(TestRestTemplate.class.getName(), new RootBeanDefinition(TestRestTemplateFactory.class)); @@ -120,8 +116,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } @@ -129,8 +124,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 = {}; @@ -139,14 +133,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; } @@ -155,16 +148,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 0a397c6cb9b..cff983ebf17 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class TestRestTemplateContextCustomizerFactory implements ContextCustomizerFacto @Override public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { - if (AnnotatedElementUtils.findMergedAnnotation(testClass, - SpringBootTest.class) != null) { + if (AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) { return new TestRestTemplateContextCustomizer(); } return null; 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 3b8f67987d3..219469d3769 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,10 +53,9 @@ import org.springframework.web.reactive.function.client.ExchangeStrategies; class WebTestClientContextCustomizer implements ContextCustomizer { @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedConfig) { - SpringBootTest annotation = AnnotatedElementUtils - .getMergedAnnotation(mergedConfig.getTestClass(), SpringBootTest.class); + public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { + SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation(mergedConfig.getTestClass(), + SpringBootTest.class); if (annotation.webEnvironment().isEmbedded()) { registerWebTestClient(context); } @@ -70,11 +69,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 @@ -108,10 +105,8 @@ class WebTestClientContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { - if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors( - (ListableBeanFactory) this.beanFactory, + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { + if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) this.beanFactory, WebTestClient.class).length == 0) { registry.registerBeanDefinition(WebTestClient.class.getName(), new RootBeanDefinition(WebTestClientFactory.class)); @@ -120,8 +115,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer { } @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } @@ -129,16 +123,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; } @@ -162,8 +154,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); @@ -174,22 +165,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 738f954c54d..113627656f6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ class WebTestClientContextCustomizerFactory implements ContextCustomizerFactory @Override public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { - if (isWebClientPresent() && AnnotatedElementUtils.findMergedAnnotation(testClass, - SpringBootTest.class) != null) { + if (isWebClientPresent() + && AnnotatedElementUtils.findMergedAnnotation(testClass, SpringBootTest.class) != null) { return new WebTestClientContextCustomizer(); } return null; 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 0f144ad84fa..8cdb04452aa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 82e6222d434..c104c0466b0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); } @@ -88,8 +87,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/FilteredClassLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java index 29c61d7baab..9c0ede63c90 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 FilteredClassLoaderTests { public ExpectedException thrown = ExpectedException.none(); @Test - public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() - throws Exception { + public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception { FilteredClassLoader classLoader = new FilteredClassLoader( FilteredClassLoaderTests.class.getPackage().getName()); this.thrown.expect(ClassNotFoundException.class); @@ -44,8 +43,7 @@ public class FilteredClassLoaderTests { @Test public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { - try (FilteredClassLoader classLoader = new FilteredClassLoader( - FilteredClassLoaderTests.class)) { + try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) { this.thrown.expect(ClassNotFoundException.class); classLoader.loadClass(getClass().getName()); } 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 9904aae8015..b6b4472628c 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 @@ -49,39 +49,32 @@ 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); } @@ -94,8 +87,7 @@ public class ImportsContextCustomizerFactoryTests { @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(); @@ -104,8 +96,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 3596a168a83..b341aa4cedf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/SpringBootConfigurationFinderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java index 857d5137d17..2a6ecd82cb7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootConfigurationFinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringBootConfigurationFinderTests { @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/SpringBootContextLoaderMockMvcTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java index 8d6b5115cc7..d2f74291cbb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 74829b6f189..61cf76ca66d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 2461670d300..c08ffb335df 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringBootTestActiveProfileTests { @Test public void profiles() { - assertThat(this.context.getEnvironment().getActiveProfiles()) - .containsExactly("override"); + assertThat(this.context.getEnvironment().getActiveProfiles()).containsExactly("override"); } @Configuration 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 a2484e667a9..317d9a5491f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.web.reactive.config.EnableWebFlux; */ @RunWith(SpringRunner.class) @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 a642124a681..bc8dbf765e8 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 @@ -45,8 +45,7 @@ public class SpringBootTestReactiveWebEnvironmentUserDefinedTestRestTemplateTest @Test public void restTemplateIsUserDefined() { - assertThat(getContext().getBean("testRestTemplate")) - .isInstanceOf(RestTemplate.class); + assertThat(getContext().getBean("testRestTemplate")).isInstanceOf(RestTemplate.class); } @Configuration 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 93797703073..4ac81e24841 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @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 fd681be352b..ce83de8c5f1 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 @@ -44,8 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @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 eee8adf838b..a88e64edcbb 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 @@ -33,10 +33,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; */ @RunWith(SpringRunner.class) @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 @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 f6c07d55e12..fdbaafee394 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringBootTestWebEnvironmentMockTests { @Test public void resourcePath() { - assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath")) - .isEqualTo("src/main/webapp"); + assertThat(ReflectionTestUtils.getField(this.servletContext, "resourceBasePath")).isEqualTo("src/main/webapp"); } @Configuration 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 de2c569565a..39f84b1cf5d 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 @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @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 eeb6f9792b0..0b8cb02a8cf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" }) -public class SpringBootTestWebEnvironmentRandomPortTests - extends AbstractSpringBootTestWebServerWebEnvironmentTests { +public class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTestWebServerWebEnvironmentTests { @Test public void testRestTemplateShouldUseBuilder() { @@ -56,8 +55,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 ab99d3c8baa..75f776a6ea2 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 @@ -39,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest -@ContextConfiguration( - classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) +@ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) public class SpringBootTestWithContextConfigurationIntegrationTests { @Rule 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 614c2a1daac..00932514f5f 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 @@ -39,11 +39,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @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 { @@ -73,14 +72,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 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 3d07d053351..78d4c144783 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +67,21 @@ public class ApplicationContextAssertProviderTests { public void getWhenTypeIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Type must not be null"); - ApplicationContextAssertProvider.get(null, ApplicationContext.class, - this.mockContextSupplier); + ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier); } @Test public void getWhenTypeIsClassShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Type must not be null"); - ApplicationContextAssertProvider.get(null, ApplicationContext.class, - this.mockContextSupplier); + ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier); } @Test public void getWhenContextTypeIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Type must be an interface"); - ApplicationContextAssertProvider.get( - TestAssertProviderApplicationContextClass.class, ApplicationContext.class, + ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, ApplicationContext.class, this.mockContextSupplier); } @@ -92,22 +89,21 @@ public class ApplicationContextAssertProviderTests { public void getWhenContextTypeIsClassShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ContextType must not be null"); - ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, - null, this.mockContextSupplier); + ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, null, + this.mockContextSupplier); } @Test public void getWhenSupplierIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ContextType must be an interface"); - ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, - StaticApplicationContext.class, this.mockContextSupplier); + ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, StaticApplicationContext.class, + this.mockContextSupplier); } @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"); @@ -115,8 +111,7 @@ public class ApplicationContextAssertProviderTests { @Test public void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { - ApplicationContextAssertProvider context = get( - this.startupFailureSupplier); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat((Object) context).isNotNull(); expectStartupFailure(); context.getBean("foo"); @@ -124,53 +119,45 @@ public class ApplicationContextAssertProviderTests { @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); expectStartupFailure(); context.getSourceApplicationContext(); } @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); + ApplicationContextAssertProvider context = get(this.startupFailureSupplier); expectStartupFailure(); context.getSourceApplicationContext(ApplicationContext.class); } @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(); @@ -178,8 +165,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); @@ -187,28 +173,21 @@ 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(); } @@ -219,11 +198,9 @@ public class ApplicationContextAssertProviderTests { this.thrown.expectCause(equalTo(this.startupFailure)); } - 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 c54cdb89a53..b7381a7c4d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ApplicationContextAssertTests { @Test public void createWhenHasApplicationContextShouldSetActual() { - assertThat(getAssert(this.context).getSourceApplicationContext()) - .isSameAs(this.context); + assertThat(getAssert(this.context).getSourceApplicationContext()).isSameAs(this.context); } @Test @@ -92,8 +91,7 @@ public class ApplicationContextAssertTests { @Test public void hasBeanWhenNotStartedShouldFail() { this.thrown.expect(AssertionError.class); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).hasBean("foo"); } @@ -123,8 +121,7 @@ public class ApplicationContextAssertTests { public void hasSingleBeanWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("to have a single bean of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).hasSingleBean(Foo.class); } @@ -161,8 +158,7 @@ public class ApplicationContextAssertTests { public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("not to have any beans of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class); } @@ -177,8 +173,7 @@ public class ApplicationContextAssertTests { @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 @@ -206,8 +201,7 @@ public class ApplicationContextAssertTests { 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 @@ -219,8 +213,7 @@ public class ApplicationContextAssertTests { public void getBeanNamesWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("not to have any beans of name"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).doesNotHaveBean("foo"); } @@ -248,8 +241,7 @@ public class ApplicationContextAssertTests { public void getBeanOfTypeWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("to contain bean of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).getBean(Foo.class); } @@ -262,8 +254,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 @@ -279,8 +270,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 @@ -298,8 +288,7 @@ public class ApplicationContextAssertTests { public void getBeanOfNameWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("to contain a bean of name"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).getBean("foo"); } @@ -326,8 +315,7 @@ public class ApplicationContextAssertTests { public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("to contain a bean of name"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).getBean("foo", Foo.class); } @@ -335,8 +323,7 @@ public class ApplicationContextAssertTests { 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 @@ -348,8 +335,7 @@ public class ApplicationContextAssertTests { public void getBeansWhenFailedToStartShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("to get beans of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).getBeans(Foo.class); } @@ -357,16 +343,14 @@ public class ApplicationContextAssertTests { 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 @@ -397,8 +381,7 @@ public class ApplicationContextAssertTests { public void hasNotFailedWhenFailedShouldFail() { this.thrown.expect(AssertionError.class); this.thrown.expectMessage("to have not failed"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); + this.thrown.expectMessage(String.format("but context failed to start:%n java.lang.RuntimeException")); assertThat(getAssert(this.failure)).hasNotFailed(); } @@ -407,8 +390,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 5027c1bd111..ad0a4cbbfab 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringBootTestContextBootstrapperTests { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("@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."); buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class); } @@ -61,10 +60,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 4f454cf5866..3cb48773395 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 3757608b0d6..529f27b42cb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,61 +41,52 @@ 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(); } private MetadataReader getMetadataReader(Class source) throws IOException { 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 213df8f4f5b..d457056cd7c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 AbstractApplicationContextRunnerTests assertThat(System.getProperties()).containsEntry(key, - "value")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "value")); assertThat(System.getProperties().containsKey(key)).isFalse(); } @@ -77,8 +76,7 @@ public abstract class AbstractApplicationContextRunnerTests assertThat(context).hasFailed()); assertThat(System.getProperties().containsKey(key)).isFalse(); } @@ -90,8 +88,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 { @@ -106,8 +103,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 runWithMultipleConfigurationsShouldRegisterAllConfigurations() { - get().withUserConfiguration(FooConfig.class) - .withConfiguration(UserConfigurations.of(BarConfig.class)) + get().withUserConfiguration(FooConfig.class).withConfiguration(UserConfigurations.of(BarConfig.class)) .run((context) -> 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) -> { - try { - ClassUtils.forName(Gson.class.getName(), - context.getClassLoader()); - fail("Should have thrown a ClassNotFoundException"); - } - catch (ClassNotFoundException ex) { - // expected - } - }); + get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())).run((context) -> { + try { + ClassUtils.forName(Gson.class.getName(), context.getClassLoader()); + fail("Should have thrown a ClassNotFoundException"); + } + catch (ClassNotFoundException ex) { + // expected + } + }); } @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 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 9bee27bb75a..aec39677632 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 78d9393e28d..a1856b17e2d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -188,8 +187,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 af1a7f2c0a1..3168b4d5048 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/GsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index b2b7cd94b10..209244e1a93 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); } @@ -69,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()); } @@ -79,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 8342bb2aa00..2dccbf7ed47 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +60,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 @@ -77,8 +75,7 @@ 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 @@ -87,8 +84,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"); } @@ -97,8 +94,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); } @@ -107,8 +104,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 9954b299a18..09f635d7323 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); } @@ -68,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()); } @@ -78,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 ac38339f104..b3c545d8851 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @Rule public final ExpectedException thrown = ExpectedException.none(); @@ -233,8 +232,7 @@ public class JsonContentAssertTests { @Test(expected = AssertionError.class) public void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { - assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", - getClass()); + assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass()); } @Test @@ -264,8 +262,7 @@ public class JsonContentAssertTests { @Test(expected = AssertionError.class) public void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { - assertThat(forJson(SOURCE)) - .isStrictlyEqualToJson(createInputStream(LENIENT_SAME)); + assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME)); } @Test @@ -290,75 +287,62 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenResourcePathIsMatchingAndLenientShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", JSONCompareMode.LENIENT); } @Test(expected = AssertionError.class) public void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isEqualToJson("different.json", - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) public void isEqualToJsonWhenResourcePathAndClassIsNotMatchingAndLenientShouldFail() { - 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(expected = AssertionError.class) public void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) - public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), - JSONCompareMode.LENIENT); + public void isEqualToJsonWhenFileIsNotMatchingAndLenientShouldFail() throws Exception { + 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(expected = AssertionError.class) public void isEqualToJsonWhenInputStreamIsNotMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) public void isEqualToJsonWhenResourceIsNotMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), JSONCompareMode.LENIENT); } @Test @@ -383,14 +367,12 @@ public class JsonContentAssertTests { @Test public void isEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldPass() { - assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), - COMPARATOR); + assertThat(forJson(SOURCE)).isEqualToJson("lenient-same.json", getClass(), COMPARATOR); } @Test(expected = AssertionError.class) public void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() { - assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), - COMPARATOR); + assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR); } @Test @@ -404,33 +386,28 @@ public class JsonContentAssertTests { } @Test - public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() - throws Exception { + public void isEqualToJsonWhenFileIsMatchingAndComparatorShouldPass() throws Exception { assertThat(forJson(SOURCE)).isEqualToJson(createFile(LENIENT_SAME), COMPARATOR); } @Test(expected = AssertionError.class) - public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() - throws Exception { + public void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() throws Exception { 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(expected = AssertionError.class) public void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() { - assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), - COMPARATOR); + 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(expected = AssertionError.class) @@ -605,8 +582,7 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreNotMatchingShouldPass() { - assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", - getClass()); + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("lenient-same.json", getClass()); } @Test(expected = AssertionError.class) @@ -625,8 +601,7 @@ public class JsonContentAssertTests { } @Test - public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() - throws Exception { + public void isNotStrictlyEqualToJsonWhenFileIsNotMatchingShouldPass() throws Exception { assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(LENIENT_SAME)); } @@ -637,8 +612,7 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldPass() { - assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(LENIENT_SAME)); } @Test(expected = AssertionError.class) @@ -648,14 +622,12 @@ public class JsonContentAssertTests { @Test public void isNotStrictlyEqualToJsonWhenResourceIsNotMatchingShouldPass() { - assertThat(forJson(SOURCE)) - .isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); + assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(LENIENT_SAME)); } @Test(expected = AssertionError.class) public void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, - JSONCompareMode.LENIENT); + assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT); } @Test @@ -665,76 +637,62 @@ public class JsonContentAssertTests { @Test(expected = AssertionError.class) public void isNotEqualToJsonWhenResourcePathIsMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) public void isNotEqualToJsonWhenBytesAreMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) - public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), - JSONCompareMode.LENIENT); + public void isNotEqualToJsonWhenFileIsMatchingAndLenientShouldFail() throws Exception { + 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(expected = AssertionError.class) public void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) public void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), - JSONCompareMode.LENIENT); + 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(expected = AssertionError.class) @@ -759,14 +717,12 @@ public class JsonContentAssertTests { @Test(expected = AssertionError.class) public void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndComparatorShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass(), - COMPARATOR); + 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(expected = AssertionError.class) @@ -780,40 +736,33 @@ public class JsonContentAssertTests { } @Test(expected = AssertionError.class) - public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() - throws Exception { - assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), - COMPARATOR); + public void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() throws Exception { + 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(expected = AssertionError.class) public void isNotEqualToJsonWhenInputStreamIsMatchingAndComparatorShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME), - COMPARATOR); + 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(expected = AssertionError.class) public void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() { - assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), - COMPARATOR); + 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 @@ -833,8 +782,7 @@ public class JsonContentAssertTests { @Test public void hasJsonPathValueForIndefinitePathWithResults() { - assertThat(forJson(SIMPSONS)) - .hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); + assertThat(forJson(SIMPSONS)).hasJsonPathValue("$.familyMembers[?(@.name == 'Bart')]"); } @Test @@ -854,8 +802,7 @@ public class JsonContentAssertTests { public void doesNotHaveJsonPathValueForAnEmptyArray() { String expression = "$.emptyArray"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected no value at JSON path \"" + expression + "\" but found: []"); + this.thrown.expectMessage("Expected no value at JSON path \"" + expression + "\" but found: []"); assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression); } @@ -863,8 +810,7 @@ public class JsonContentAssertTests { public void doesNotHaveJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected no value at JSON path \"" + expression + "\" but found: {}"); + this.thrown.expectMessage("Expected no value at JSON path \"" + expression + "\" but found: {}"); assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression); } @@ -872,15 +818,14 @@ public class JsonContentAssertTests { public void doesNotHaveJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected no value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); + this.thrown.expectMessage( + "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression); } @Test public void doesNotHaveJsonPathValueForIndefinitePathWithEmptyResults() { - assertThat(forJson(SIMPSONS)) - .doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); + assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue("$.familyMembers[?(@.name == 'Dilbert')]"); } @Test @@ -900,16 +845,15 @@ 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')]"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); + this.thrown.expectMessage( + "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression); } @@ -917,8 +861,7 @@ public class JsonContentAssertTests { public void hasEmptyJsonPathValueForWhitespace() { String expression = "$.whitespace"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression - + "\" but found: ' '"); + this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression); } @@ -949,16 +892,14 @@ 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')]"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression); } @@ -966,8 +907,7 @@ public class JsonContentAssertTests { public void doesNotHaveEmptyJsonPathValueForAnEmptyString() { String expression = "$.emptyString"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: ''"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); } @@ -975,8 +915,7 @@ public class JsonContentAssertTests { public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { String expression = "$.emptyArray"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); } @@ -984,8 +923,7 @@ public class JsonContentAssertTests { public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: {}"); + this.thrown.expectMessage("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); } @@ -1003,8 +941,7 @@ public class JsonContentAssertTests { public void hasJsonPathStringValueForNonString() { String expression = "$.bool"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a string at JSON path \"" + expression + "\" but found: true"); + this.thrown.expectMessage("Expected a string at JSON path \"" + expression + "\" but found: true"); assertThat(forJson(TYPES)).hasJsonPathStringValue(expression); } @@ -1017,8 +954,7 @@ public class JsonContentAssertTests { public void hasJsonPathNumberValueForNonNumber() { String expression = "$.bool"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a number at JSON path \"" + expression + "\" but found: true"); + this.thrown.expectMessage("Expected a number at JSON path \"" + expression + "\" but found: true"); assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression); } @@ -1031,8 +967,7 @@ public class JsonContentAssertTests { public void hasJsonPathBooleanValueForNonBoolean() { String expression = "$.num"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a boolean at JSON path \"" + expression + "\" but found: 5"); + this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression); } @@ -1050,8 +985,7 @@ public class JsonContentAssertTests { public void hasJsonPathArrayValueForNonArray() { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression); } @@ -1069,8 +1003,7 @@ public class JsonContentAssertTests { public void hasJsonPathMapValueForNonMap() { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).hasJsonPathMapValue(expression); } @@ -1086,8 +1019,7 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathStringValue() { - assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str") - .isEqualTo("foo"); + assertThat(forJson(TYPES)).extractingJsonPathStringValue("@.str").isEqualTo("foo"); } @Test @@ -1097,16 +1029,14 @@ 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"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a string at JSON path \"" + expression + "\" but found: 5"); + this.thrown.expectMessage("Expected a string at JSON path \"" + expression + "\" but found: 5"); assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression); } @@ -1124,8 +1054,7 @@ public class JsonContentAssertTests { public void extractingJsonPathNumberValueForWrongType() { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression); } @@ -1143,15 +1072,13 @@ public class JsonContentAssertTests { public void extractingJsonPathBooleanValueForWrongType() { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression - + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression); } @Test public void extractingJsonPathArrayValue() { - assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr") - .containsExactly(42); + assertThat(forJson(TYPES)).extractingJsonPathArrayValue("@.arr").containsExactly(42); } @Test @@ -1168,15 +1095,13 @@ public class JsonContentAssertTests { public void extractingJsonPathArrayValueForWrongType() { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression); } @Test public void extractingJsonPathMapValue() { - assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap") - .contains(entry("red", "rojo")); + assertThat(forJson(TYPES)).extractingJsonPathMapValue("@.colorMap").contains(entry("red", "rojo")); } @Test @@ -1193,8 +1118,7 @@ public class JsonContentAssertTests { public void extractingJsonPathMapValueForWrongType() { String expression = "$.str"; this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + this.thrown.expectMessage("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression); } @@ -1219,8 +1143,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 50cf8696cdb..350ac14de3d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -76,8 +75,7 @@ public class JsonContentTests { @Test public void toStringWhenHasTypeShouldReturnString() { JsonContent content = new JsonContent<>(getClass(), TYPE, JSON); - 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 fd8f1dc30a7..f327abd0887 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); } @@ -70,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()); } @@ -80,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/ObjectContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index bf37485d4d1..fa1080b1277 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -67,8 +66,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 c7b2200c429..a1e88ee9f25 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 @@ -49,18 +49,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 @@ -70,8 +67,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); @@ -83,14 +79,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); } @@ -98,8 +92,7 @@ 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 @@ -113,17 +106,14 @@ 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() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The name attribute can only be used when mocking a single class"); + this.thrown.expectMessage("The name attribute can only be used when mocking a single class"); this.parser.parse(MockBeanMultipleClassesWithName.class); } @@ -131,18 +121,15 @@ public class DefinitionsParserTests { 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 @@ -151,8 +138,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(); } @@ -163,22 +149,19 @@ 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 @@ -192,17 +175,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() { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The name attribute can only be used when spying a single class"); + this.thrown.expectMessage("The name attribute can only be used when spying a single class"); this.parser.parse(SpyBeanMultipleClassesWithName.class); } @@ -228,10 +208,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 { } @@ -250,8 +228,7 @@ public class DefinitionsParserTests { } - @MockBean(name = "name", - classes = { ExampleService.class, ExampleServiceCaller.class }) + @MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class }) static class MockBeanMultipleClassesWithName { } @@ -273,8 +250,7 @@ public class DefinitionsParserTests { } - @SpyBeans({ @SpyBean(RealExampleService.class), - @SpyBean(ExampleServiceCaller.class) }) + @SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) }) static class RepeatSpyBean { } @@ -298,8 +274,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 14d99f83213..98488fbef76 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -73,8 +72,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 083de365b03..9d024480967 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 6358aee9694..02b5b2480e0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -52,8 +51,7 @@ public class MockDefinitionTests { @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(); @@ -67,12 +65,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); @@ -83,11 +80,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 61d0f9bfa8c..f80816b881b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 1d206b53f50..440b7062ae2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 b98fabd4663..e4de4696830 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 2e9e2f885f2..ec46ef9d089 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleBeans.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example2]"); + this.thrown.expectMessage("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + "but found [example1, example2]"); context.refresh(); } @@ -62,10 +60,8 @@ public class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example3]"); + this.thrown.expectMessage("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + "but found [example1, example3]"); context.refresh(); } @@ -73,15 +69,12 @@ public class MockitoPostProcessorTests { 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(); } @Configuration 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 6f48e1b62ce..1e834994bd7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MockitoTestExecutionListenerTests { @Before 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 c1b4dfecdd2..7696a761edc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 826fbe69406..2f230bad403 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -74,8 +73,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/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java index 6d41d8377a7..0e91a867bd0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { } @Configuration - @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 a6fcfa9eb45..68f819ef0f6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java index cf8933cba06..1ad94f94ac9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 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 478d7acf068..c2a29602a7c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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; */ 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); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -53,8 +52,7 @@ public class SpyDefinitionTests { @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); @@ -65,8 +63,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); @@ -76,11 +73,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); @@ -89,8 +84,7 @@ 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); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Instance must not be null"); definition.createSpy(null); @@ -98,8 +92,7 @@ public class SpyDefinitionTests { @Test public void createSpyWhenWrongInstanceShouldThrowException() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, - MockReset.BEFORE, true, null); + SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("must be an instance of"); definition.createSpy(new ExampleServiceCaller(null)); @@ -107,8 +100,7 @@ public class SpyDefinitionTests { @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 19750019edc..20c7789a6a4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 c090429a0b6..65abf6a9278 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/util/ApplicationContextTestUtilsTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java index 59c45c8c2cb..8622e67b101 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 38bcf98511f..92849c1743b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index a9525839c43..50e8bad99e1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +69,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"); } @@ -94,8 +91,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"); } @@ -105,10 +101,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 c90e4a5773e..3e1d06d86cf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -85,8 +84,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); @@ -122,8 +120,7 @@ public class MockServerRestTemplateCustomizerTests { 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 @@ -133,8 +130,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 @@ -161,14 +157,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 61fbdac566a..b3e6f5e9572 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -102,8 +101,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); @@ -114,13 +112,11 @@ 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:")); + .willThrow(new AssertionError("Request URI expected: was:")); this.thrown.expect(AssertionError.class); this.thrown.expectMessage("Request URI expected:"); this.manager.validateRequest(request); @@ -135,24 +131,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); } @@ -160,31 +154,26 @@ 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()); this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "expected: but was:"); + this.thrown.expectMessage("expected: but was:"); restTemplate.getForEntity("https://spring.io/hello", String.class); } 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 7a63d9bd136..cae38529a5a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerWithOverrideIntegrationTests.java index a36b2bb3a3a..4ef4563a640 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 e66c4116b0d..a824576b812 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); @@ -104,8 +103,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); @@ -118,15 +116,13 @@ public class TestRestTemplateTests { @Test public void authenticated() { - assertThat(new TestRestTemplate("user", "password").getRestTemplate() - .getRequestFactory()) - .isInstanceOf(InterceptingClientHttpRequestFactory.class); + assertThat(new TestRestTemplate("user", "password").getRestTemplate().getRequestFactory()) + .isInstanceOf(InterceptingClientHttpRequestFactory.class); } @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(); @@ -136,10 +132,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); @@ -147,14 +141,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); @@ -199,37 +192,30 @@ public class TestRestTemplateTests { @Test public void withBasicAuthAddsBasicAuthInterceptorWhenNotAlreadyPresent() { TestRestTemplate originalTemplate = new TestRestTemplate(); - TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", - "password"); + TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password"); assertThat(basicAuthTemplate.getRestTemplate().getMessageConverters()) - .containsExactlyElementsOf( - originalTemplate.getRestTemplate().getMessageConverters()); + .containsExactlyElementsOf(originalTemplate.getRestTemplate().getMessageConverters()); assertThat(basicAuthTemplate.getRestTemplate().getRequestFactory()) .isInstanceOf(InterceptingClientHttpRequestFactory.class); - assertThat(ReflectionTestUtils.getField( - basicAuthTemplate.getRestTemplate().getRequestFactory(), - "requestFactory")) + assertThat( + ReflectionTestUtils.getField(basicAuthTemplate.getRestTemplate().getRequestFactory(), "requestFactory")) .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); assertThat(basicAuthTemplate.getRestTemplate().getUriTemplateHandler()) .isSameAs(originalTemplate.getRestTemplate().getUriTemplateHandler()); assertThat(basicAuthTemplate.getRestTemplate().getInterceptors()).hasSize(1); - assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user", - "password"); + assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user", "password"); } @Test public void withBasicAuthReplacesBasicAuthInterceptorWhenAlreadyPresent() { - 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(basicAuth.getRestTemplate().getMessageConverters()) - .containsExactlyElementsOf( - original.getRestTemplate().getMessageConverters()); + .containsExactlyElementsOf(original.getRestTemplate().getMessageConverters()); assertThat(basicAuth.getRestTemplate().getRequestFactory()) .isInstanceOf(InterceptingClientHttpRequestFactory.class); - assertThat(ReflectionTestUtils.getField( - basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) - .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); + assertThat(ReflectionTestUtils.getField(basicAuth.getRestTemplate().getRequestFactory(), "requestFactory")) + .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); assertThat(basicAuth.getRestTemplate().getUriTemplateHandler()) .isSameAs(original.getRestTemplate().getUriTemplateHandler()); assertThat(basicAuth.getRestTemplate().getInterceptors()).hasSize(1); @@ -241,10 +227,8 @@ 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()) - .isSameAs(errorHandler); + TestRestTemplate basicAuthTemplate = originalTemplate.withBasicAuth("user", "password"); + assertThat(basicAuthTemplate.getRestTemplate().getErrorHandler()).isSameAs(errorHandler); } @Test @@ -253,55 +237,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 @@ -316,66 +292,57 @@ 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 assertBasicAuthorizationInterceptorCredentials( - TestRestTemplate testRestTemplate, String username, String password) { + private void assertBasicAuthorizationInterceptorCredentials(TestRestTemplate testRestTemplate, String username, + String password) { @SuppressWarnings("unchecked") List requestFactoryInterceptors = (List) ReflectionTestUtils - .getField(testRestTemplate.getRestTemplate().getRequestFactory(), - "interceptors"); + .getField(testRestTemplate.getRestTemplate().getRequestFactory(), "interceptors"); assertThat(requestFactoryInterceptors).hasSize(1); ClientHttpRequestInterceptor interceptor = requestFactoryInterceptors.get(0); assertThat(interceptor).isInstanceOf(BasicAuthorizationInterceptor.class); - assertThat(ReflectionTestUtils.getField(interceptor, "username")) - .isEqualTo(username); - assertThat(ReflectionTestUtils.getField(interceptor, "password")) - .isEqualTo(password); + assertThat(ReflectionTestUtils.getField(interceptor, "username")).isEqualTo(username); + assertThat(ReflectionTestUtils.getField(interceptor, "password")).isEqualTo(password); } 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 1412252ee37..ad925bd8658 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,13 +72,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); @@ -86,8 +84,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 9ccc1e0816c..ecad05e5aaa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,30 +92,25 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { @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); @@ -128,8 +123,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 2468506311b..f96f5dc36dd 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 @@ -42,8 +42,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; * @author Phillip Webb */ @RunWith(SpringRunner.class) -@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 { @@ -52,8 +51,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 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 32283519011..9f6ec8c5b52 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 @@ -46,8 +46,7 @@ import static org.mockito.Mockito.mock; * @author Phillip Webb */ @RunWith(SpringRunner.class) -@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 a5ade8fffc1..93afb42ff97 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. @@ -57,8 +57,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 Map annotations; @@ -71,16 +70,11 @@ 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("AutoConfigureBefore", - "org.springframework.boot.autoconfigure.AutoConfigureBefore"); - annotations.put("AutoConfigureAfter", - "org.springframework.boot.autoconfigure.AutoConfigureAfter"); - annotations.put("AutoConfigureOrder", - "org.springframework.boot.autoconfigure.AutoConfigureOrder"); + annotations.put("Configuration", "org.springframework.context.annotation.Configuration"); + annotations.put("ConditionalOnClass", "org.springframework.boot.autoconfigure.condition.ConditionalOnClass"); + annotations.put("AutoConfigureBefore", "org.springframework.boot.autoconfigure.AutoConfigureBefore"); + annotations.put("AutoConfigureAfter", "org.springframework.boot.autoconfigure.AutoConfigureAfter"); + annotations.put("AutoConfigureOrder", "org.springframework.boot.autoconfigure.AutoConfigureOrder"); } @Override @@ -89,8 +83,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()); } @@ -105,36 +98,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 = getQualifiedName(element); AnnotationMirror annotation = getAnnotation(element, annotationName); if (qualifiedName != null && annotation != null) { List values = getValues(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); } } @@ -159,9 +146,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } private List getValues(AnnotationMirror annotation) { - return annotation.getElementValues().entrySet().stream() - .filter(this::isNameOrValueAttribute).flatMap(this::getValues) - .collect(Collectors.toList()); + return annotation.getElementValues().entrySet().stream().filter(this::isNameOrValueAttribute) + .flatMap(this::getValues).collect(Collectors.toList()); } private boolean isNameOrValueAttribute(Entry entry) { @@ -173,8 +159,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { private Stream getValues(Entry entry) { Object value = entry.getValue().getValue(); if (value instanceof List) { - return ((List) value).stream() - .map((annotation) -> processValue(annotation.getValue())); + return ((List) value).stream().map((annotation) -> processValue(annotation.getValue())); } return Stream.of(processValue(value)); } @@ -191,8 +176,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { 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(); @@ -214,8 +198,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); } 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 b777ce703fa..aa4e8e3aa23 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 AutoConfigureAnnotationProcessorTests { Properties properties = compile(TestClassConfiguration.class); assertThat(properties).hasSize(3); assertThat(properties).containsEntry( - "org.springframework.boot.autoconfigureprocessor." - + "TestClassConfiguration.ConditionalOnClass", + "org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration.ConditionalOnClass", "java.io.InputStream,org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration$Nested"); - 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"); + 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"); } @Test @@ -69,38 +67,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/TestClassConfiguration.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java index 72ebf018da1..4a646492aa6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestClassConfiguration.java @@ -22,8 +22,7 @@ package org.springframework.boot.autoconfigureprocessor; * @author Madhura Bhave */ @TestConfiguration -@TestConditionalOnClass(name = "java.io.InputStream", - value = TestClassConfiguration.Nested.class) +@TestConditionalOnClass(name = "java.io.InputStream", value = TestClassConfiguration.Nested.class) public class TestClassConfiguration { @TestAutoConfigureOrder diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java index 9cba8263c2f..32c355644bf 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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.autoconfigureprocessor.TestAutoConfigureBefore", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureAfter", "org.springframework.boot.autoconfigureprocessor.TestAutoConfigureOrder" }) -public class TestConditionMetadataAnnotationProcessor - extends AutoConfigureAnnotationProcessor { +public class TestConditionMetadataAnnotationProcessor extends AutoConfigureAnnotationProcessor { private final File outputLocation; 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 8912b0612e3..b086fc8aae4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 = getSource(metadata, 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,20 +130,17 @@ 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()); } - private ConfigurationMetadataSource getSource(RawConfigurationMetadata metadata, - ConfigurationMetadataItem item) { + private ConfigurationMetadataSource getSource(RawConfigurationMetadata metadata, ConfigurationMetadataItem item) { if (item.getSourceType() != null) { return metadata.getSource(item.getSourceType()); } @@ -161,8 +154,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); @@ -184,8 +176,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 0cab69d8d6a..a534d2b1f21 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); 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 2c77acaca48..80a447d36f0 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. @@ -37,16 +37,15 @@ public abstract class AbstractConfigurationMetadataTests { @Rule public final ExpectedException thrown = ExpectedException.none(); - 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); @@ -61,8 +60,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 f360c0dbfe6..6978639f6d1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.assertj.core.api.Assertions.assertThat; * * @author Stephane Nicoll */ -public class ConfigurationMetadataRepositoryJsonBuilderTests - extends AbstractConfigurationMetadataTests { +public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests { @Test public void nullResource() throws IOException { @@ -41,12 +40,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @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); } } @@ -54,63 +51,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); } } @@ -118,8 +106,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"); @@ -129,15 +116,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @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 @@ -151,78 +134,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) { @@ -238,11 +206,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 0d4fdf37f8c..26b26346d1f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 +94,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 +124,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 +150,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 +164,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); } RawConfigurationMetadata readFor(String path) throws IOException { 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 38a4a502658..9de21acfe3b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ConfigurationMetadataAnnotationProcessor extends AbstractProcessor static final String DEPRECATED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot." + "context.properties.DeprecatedConfigurationProperty"; - 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"; @@ -143,25 +142,21 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor super.init(env); this.typeUtils = new TypeUtils(env); this.metadataStore = new MetadataStore(env); - this.metadataCollector = new MetadataCollector(env, - this.metadataStore.readMetadata()); + this.metadataCollector = new MetadataCollector(env, this.metadataStore.readMetadata()); try { this.fieldValuesParser = new JavaCompilerFieldValuesParser(env); } catch (Throwable ex) { this.fieldValuesParser = FieldValuesParser.NONE; - logWarning("Field value processing of @ConfigurationProperty meta-data is " - + "not supported"); + logWarning("Field value processing of @ConfigurationProperty meta-data is " + "not supported"); } } @Override - public boolean process(Set annotations, - RoundEnvironment roundEnv) { + public boolean process(Set annotations, RoundEnvironment roundEnv) { this.metadataCollector.processing(roundEnv); Elements elementUtils = this.processingEnv.getElementUtils(); - TypeElement annotationType = elementUtils - .getTypeElement(configurationPropertiesAnnotation()); + TypeElement annotationType = elementUtils.getTypeElement(configurationPropertiesAnnotation()); if (annotationType != null) { // Is @ConfigurationProperties available for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) { processElement(element); @@ -169,8 +164,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } TypeElement endpointType = elementUtils.getTypeElement(endpointAnnotation()); if (endpointType != null) { // Is @Endpoint available - getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType) - .forEach(this::processEndpoint); + getElementsAnnotatedOrMetaAnnotatedWith(roundEnv, endpointType).forEach(this::processEndpoint); } if (roundEnv.processingOver()) { try { @@ -183,8 +177,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()) { @@ -199,11 +193,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); @@ -220,8 +213,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor private void processElement(Element element) { try { - AnnotationMirror annotation = getAnnotation(element, - configurationPropertiesAnnotation()); + AnnotationMirror annotation = getAnnotation(element, configurationPropertiesAnnotation()); if (annotation != null) { String prefix = getPrefix(annotation); if (element instanceof TypeElement) { @@ -233,8 +225,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); } } @@ -245,20 +236,14 @@ 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.typeUtils.getQualifiedName(returns), - this.typeUtils.getQualifiedName(element.getEnclosingElement()), - element.toString()); + ItemMetadata group = ItemMetadata.newGroup(prefix, this.typeUtils.getQualifiedName(returns), + this.typeUtils.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); @@ -268,10 +253,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } } - private void processTypeElement(String prefix, TypeElement element, - ExecutableElement source) { - TypeElementMembers members = new TypeElementMembers(this.processingEnv, - this.fieldValuesParser, element); + private void processTypeElement(String prefix, TypeElement element, ExecutableElement source) { + TypeElementMembers members = new TypeElementMembers(this.processingEnv, this.fieldValuesParser, element); Map fieldValues = members.getFieldValues(); processSimpleTypes(prefix, element, source, members, fieldValues); processSimpleLombokTypes(prefix, element, source, members, fieldValues); @@ -279,15 +262,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor processNestedLombokTypes(prefix, element, source, members); } - private void processSimpleTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members, - Map fieldValues) { + private void processSimpleTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members, Map fieldValues) { members.getPublicGetters().forEach((name, getter) -> { TypeMirror returnType = getter.getReturnType(); ExecutableElement setter = members.getPublicSetter(name, returnType); VariableElement field = members.getFields().get(name); - Element returnTypeElement = this.processingEnv.getTypeUtils() - .asElement(returnType); + Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType); boolean isNested = isNested(returnTypeElement, field, element); boolean isCollection = this.typeUtils.isCollectionOrMap(returnType); @@ -296,18 +277,15 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor String sourceType = this.typeUtils.getQualifiedName(element); String description = this.typeUtils.getJavaDoc(field); Object defaultValue = fieldValues.get(name); - boolean deprecated = isDeprecated(getter) || isDeprecated(setter) - || isDeprecated(source); - this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, - dataType, sourceType, null, description, defaultValue, - deprecated ? getItemDeprecation(getter) : null)); + boolean deprecated = isDeprecated(getter) || isDeprecated(setter) || isDeprecated(source); + this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null, + description, defaultValue, deprecated ? getItemDeprecation(getter) : null)); } }); } private ItemDeprecation getItemDeprecation(ExecutableElement getter) { - AnnotationMirror annotation = getAnnotation(getter, - deprecatedConfigurationPropertyAnnotation()); + AnnotationMirror annotation = getAnnotation(getter, deprecatedConfigurationPropertyAnnotation()); String reason = null; String replacement = null; if (annotation != null) { @@ -320,16 +298,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return new ItemDeprecation(reason, replacement); } - private void processSimpleLombokTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members, - Map fieldValues) { + private void processSimpleLombokTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members, Map fieldValues) { members.getFields().forEach((name, field) -> { if (!isLombokField(field, element)) { return; } TypeMirror returnType = field.asType(); - Element returnTypeElement = this.processingEnv.getTypeUtils() - .asElement(returnType); + Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType); boolean isNested = isNested(returnTypeElement, field, element); boolean isCollection = this.typeUtils.isCollectionOrMap(returnType); @@ -340,29 +316,26 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor String description = this.typeUtils.getJavaDoc(field); Object defaultValue = fieldValues.get(name); boolean deprecated = isDeprecated(field) || isDeprecated(source); - this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, - dataType, sourceType, null, description, defaultValue, - deprecated ? new ItemDeprecation() : null)); + this.metadataCollector.add(ItemMetadata.newProperty(prefix, name, dataType, sourceType, null, + description, defaultValue, deprecated ? new ItemDeprecation() : null)); } }); } - private void processNestedTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members) { + private void processNestedTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members) { members.getPublicGetters().forEach((name, getter) -> { VariableElement field = members.getFields().get(name); - processNestedType(prefix, element, source, name, getter, field, - getter.getReturnType()); + processNestedType(prefix, element, source, name, getter, field, getter.getReturnType()); }); } - private void processNestedLombokTypes(String prefix, TypeElement element, - ExecutableElement source, TypeElementMembers members) { + private void processNestedLombokTypes(String prefix, TypeElement element, ExecutableElement source, + TypeElementMembers members) { members.getFields().forEach((name, field) -> { if (isLombokField(field, element)) { ExecutableElement getter = members.getPublicGetter(name, field.asType()); - processNestedType(prefix, element, source, name, getter, field, - field.asType()); + processNestedType(prefix, element, source, name, getter, field, field.asType()); } }); } @@ -372,8 +345,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } private boolean hasLombokSetter(VariableElement field, TypeElement element) { - return !field.getModifiers().contains(Modifier.FINAL) - && hasLombokPublicAccessor(field, element, false); + return !field.getModifiers().contains(Modifier.FINAL) && hasLombokPublicAccessor(field, element, false); } /** @@ -385,16 +357,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor * write accessor * @return {@code true} if this field has a public accessor of the specified type */ - private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element, - boolean getter) { - String annotation = (getter ? LOMBOK_GETTER_ANNOTATION - : LOMBOK_SETTER_ANNOTATION); + private boolean hasLombokPublicAccessor(VariableElement field, TypeElement element, boolean getter) { + String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION); AnnotationMirror lombokMethodAnnotationOnField = getAnnotation(field, annotation); if (lombokMethodAnnotationOnField != null) { return isAccessLevelPublic(lombokMethodAnnotationOnField); } - AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element, - annotation); + AnnotationMirror lombokMethodAnnotationOnElement = getAnnotation(element, annotation); if (lombokMethodAnnotationOnElement != null) { return isAccessLevelPublic(lombokMethodAnnotationOnElement); } @@ -407,19 +376,16 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC)); } - private void processNestedType(String prefix, TypeElement element, - ExecutableElement source, String name, ExecutableElement getter, - VariableElement field, TypeMirror returnType) { + private void processNestedType(String prefix, TypeElement element, ExecutableElement source, String name, + ExecutableElement getter, VariableElement field, TypeMirror returnType) { Element returnElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isNested = isNested(returnElement, field, element); - AnnotationMirror annotation = getAnnotation(getter, - configurationPropertiesAnnotation()); + AnnotationMirror annotation = getAnnotation(getter, configurationPropertiesAnnotation()); if (returnElement instanceof TypeElement && annotation == null && isNested) { String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, name); - this.metadataCollector.add(ItemMetadata.newGroup(nestedPrefix, - this.typeUtils.getQualifiedName(returnElement), - this.typeUtils.getQualifiedName(element), - (getter != null) ? getter.toString() : null)); + this.metadataCollector + .add(ItemMetadata.newGroup(nestedPrefix, this.typeUtils.getQualifiedName(returnElement), + this.typeUtils.getQualifiedName(element), (getter != null) ? getter.toString() : null)); processTypeElement(nestedPrefix, (TypeElement) returnElement, source); } } @@ -433,8 +399,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); } } @@ -444,27 +409,22 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor 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.typeUtils.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())) { - if (hasAnnotation(method, readOperationAnnotation()) - && (TypeKind.VOID != method.getReturnType().getKind()) + for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) { + if (hasAnnotation(method, readOperationAnnotation()) && (TypeKind.VOID != method.getReturnType().getKind()) && hasNoOrOptionalParameters(method)) { return true; } @@ -481,16 +441,14 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return true; } - private boolean isNested(Element returnType, VariableElement field, - TypeElement element) { + private boolean isNested(Element returnType, VariableElement field, TypeElement element) { if (hasAnnotation(field, nestedConfigurationPropertyAnnotation())) { return true; } if (isCyclePresent(returnType, element)) { return false; } - return (isParentTheSame(returnType, element)) - && returnType.getKind() != ElementKind.ENUM; + return (isParentTheSame(returnType, element)) && returnType.getKind() != ElementKind.ENUM; } private boolean isCyclePresent(Element returnType, Element element) { @@ -562,8 +520,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor private Map getAnnotationElementValues(AnnotationMirror annotation) { Map values = new LinkedHashMap<>(); - annotation.getElementValues().forEach((name, value) -> values - .put(name.getSimpleName().toString(), value.getValue())); + annotation.getElementValues() + .forEach((name, value) -> values.put(name.getSimpleName().toString(), value.getValue())); return values; } @@ -577,8 +535,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/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/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/TypeElementMembers.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeElementMembers.java index d7d350efcbb..ade7c86f457 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 TypeElementMembers { private final FieldValuesParser fieldValuesParser; - TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser, - TypeElement element) { + TypeElementMembers(ProcessingEnvironment env, FieldValuesParser fieldValuesParser, TypeElement element) { this.env = env; this.typeUtils = new TypeUtils(this.env); this.fieldValuesParser = fieldValuesParser; @@ -69,12 +68,10 @@ 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); } try { @@ -89,8 +86,7 @@ class TypeElementMembers { } Element superType = this.env.getTypeUtils().asElement(element.getSuperclass()); - if (superType != null && superType instanceof TypeElement - && !OBJECT_CLASS_NAME.equals(superType.toString())) { + if (superType != null && superType instanceof TypeElement && !OBJECT_CLASS_NAME.equals(superType.toString())) { process((TypeElement) superType); } } @@ -103,8 +99,7 @@ class TypeElementMembers { } else if (isSetter(method)) { String propertyName = getAccessorName(name); - List matchingSetters = this.publicSetters - .get(propertyName); + List matchingSetters = this.publicSetters.get(propertyName); if (matchingSetters == null) { matchingSetters = new ArrayList<>(); this.publicSetters.put(propertyName, matchingSetters); @@ -119,13 +114,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)) { @@ -137,27 +130,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; } @@ -185,8 +175,7 @@ class TypeElementMembers { return candidate; } TypeMirror alternative = this.typeUtils.getWrapperOrPrimitiveFor(type); - if (alternative != null - && this.env.getTypeUtils().isSameType(returnType, alternative)) { + if (alternative != null && this.env.getTypeUtils().isSameType(returnType, alternative)) { return candidate; } } 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 098145ba0bb..6953c4c0488 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,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; } @@ -84,12 +83,10 @@ class TypeUtils { this.mapType = getDeclaredType(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); } @@ -138,8 +135,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 = javadoc.replaceAll("[\r\n]+", "").trim(); } @@ -149,8 +145,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) { @@ -183,8 +178,7 @@ class TypeUtils { public String visitDeclared(DeclaredType type, Void none) { TypeElement enclosingElement = getEnclosingTypeElement(type); if (enclosingElement != null) { - return getQualifiedName(enclosingElement) + "$" - + type.asElement().getSimpleName(); + return getQualifiedName(enclosingElement) + "$" + type.asElement().getSimpleName(); } String qualifiedName = getQualifiedName(type.asElement()); if (type.getTypeArguments().isEmpty()) { @@ -192,8 +186,8 @@ class TypeUtils { } StringBuilder name = new StringBuilder(); name.append(qualifiedName); - name.append("<").append(type.getTypeArguments().stream() - .map(TypeMirror::toString).collect(Collectors.joining(","))) + name.append("<") + .append(type.getTypeArguments().stream().map(TypeMirror::toString).collect(Collectors.joining(","))) .append(">"); return name.toString(); } @@ -220,8 +214,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) { 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 fbda9697fe6..a99dd5871d3 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. @@ -141,8 +141,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; 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 c23f2d05af6..2cd6f9a1b3f 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. @@ -152,8 +152,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); @@ -187,8 +186,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 { @@ -213,8 +211,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 0f6fcb56779..798f732fb22 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; @@ -194,8 +193,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); } @@ -206,22 +204,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 18833cec421..972083a61ef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.configurationprocessor.metadata.ItemMetadata.Ite */ class JsonConverter { - public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) - throws Exception { + public JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception { JSONArray jsonArray = new JSONArray(); for (ItemMetadata item : metadata.getItems()) { if (item.isOfItemType(itemType)) { @@ -115,8 +114,7 @@ class JsonConverter { return providers; } - private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) - throws Exception { + private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception { JSONObject result = new JSONOrderedObject(); result.put("name", provider.getName()); if (provider.getParameters() != null && !provider.getParameters().isEmpty()) { @@ -129,8 +127,7 @@ class JsonConverter { return result; } - private void putIfPresent(JSONObject jsonObject, String name, Object value) - throws Exception { + private void putIfPresent(JSONObject jsonObject, String name, Object value) throws Exception { if (value != null) { jsonObject.put(name, value); } 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 6406566e70e..0e0b95564db 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 JSONOrderedObject(); 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 7d7a9cef09a..fff58525f0f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,15 +127,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")); @@ -144,83 +141,59 @@ 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); - assertThat(metadata).has(Metadata.withGroup("hierarchical") - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class) - .fromSource(HierarchicalProperties.class)); - assertThat(metadata) - .has(Metadata.withProperty("hierarchical.second", String.class) - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class) - .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("hierarchical.first", String.class).fromSource(HierarchicalProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("hierarchical.second", String.class).fromSource(HierarchicalProperties.class)); + assertThat(metadata).has( + Metadata.withProperty("hierarchical.third", String.class).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.")); } @@ -231,11 +204,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 @@ -243,11 +215,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")); } @@ -256,12 +225,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 @@ -269,10 +236,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 @@ -281,17 +247,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>")); } @@ -299,47 +261,43 @@ 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 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 @@ -354,11 +312,9 @@ public class ConfigurationMetadataAnnotationProcessorTests { 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 @@ -368,35 +324,29 @@ public class ConfigurationMetadataAnnotationProcessorTests { 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)); } @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); } @@ -409,20 +359,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")); @@ -431,12 +378,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")); } @@ -452,16 +398,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 @@ -508,40 +450,36 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void genericTypes() { ConfigurationMetadata metadata = compile(GenericConfig.class); - assertThat(metadata).has(Metadata.withGroup("generic").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig")); - assertThat(metadata).has(Metadata.withGroup("generic.foo").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig$Foo")); - assertThat(metadata).has(Metadata.withGroup("generic.foo.bar").ofType( - "org.springframework.boot.configurationsample.specific.GenericConfig$Bar")); - assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz").ofType( - "org.springframework.boot.configurationsample.specific.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.specific.GenericConfig")); + assertThat(metadata).has(Metadata.withGroup("generic.foo") + .ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Foo")); + assertThat(metadata).has(Metadata.withGroup("generic.foo.bar") + .ofType("org.springframework.boot.configurationsample.specific.GenericConfig$Bar")); + assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz") + .ofType("org.springframework.boot.configurationsample.specific.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() throws IOException { 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); } @@ -560,63 +498,51 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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 @@ -629,14 +555,11 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); } @@ -644,8 +567,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); @@ -654,8 +576,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); } @@ -663,8 +584,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); } @@ -672,11 +592,10 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); @@ -685,8 +604,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); @@ -695,27 +613,26 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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); @@ -723,61 +640,50 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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."); } @Test @@ -787,97 +693,83 @@ public class ConfigurationMetadataAnnotationProcessorTests { 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); - 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)); } @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); } @@ -893,63 +785,53 @@ public class ConfigurationMetadataAnnotationProcessorTests { @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(this.compiler.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"); @@ -965,107 +847,91 @@ public class ConfigurationMetadataAnnotationProcessorTests { 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)); } @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)); } - 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); } @@ -1128,8 +994,7 @@ public class ConfigurationMetadataAnnotationProcessorTests { private File createAdditionalMetadataFile() throws IOException { File metaInfFolder = new File(this.compiler.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/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/TestConfigurationMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java index 8492de6ff5b..3d6ecc6af00 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestConfigurationMetadataAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.configurationprocessor.metadata.JsonMarshaller; */ @SupportedAnnotationTypes({ "*" }) @SupportedSourceVersion(SourceVersion.RELEASE_6) -public class TestConfigurationMetadataAnnotationProcessor - extends ConfigurationMetadataAnnotationProcessor { +public class TestConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor { static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties"; @@ -87,11 +86,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/TestProject.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java index a7d9d59166e..63d8834a135 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,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 @@ -133,15 +132,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/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 a9a887807d4..d198b7354d9 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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(); @@ -97,8 +96,7 @@ public abstract class AbstractFieldValuesProcessorTests { assertThat(values.get("durationDays")).isEqualTo("50d"); } - @SupportedAnnotationTypes({ - "org.springframework.boot.configurationsample.ConfigurationProperties" }) + @SupportedAnnotationTypes({ "org.springframework.boot.configurationsample.ConfigurationProperties" }) @SupportedSourceVersion(SourceVersion.RELEASE_6) private class TestProcessor extends AbstractProcessor { @@ -112,14 +110,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 78c904df257..802991e3519 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,49 +37,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")); } } 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 e61b29d3f18..4eac279f3ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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/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 5082650968b..cb1ce2684d8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.configurationsample.simple; * * @author Stephane Nicoll */ -public abstract class HierarchicalPropertiesParent - extends HierarchicalPropertiesGrandparent { +public abstract class HierarchicalPropertiesParent extends HierarchicalPropertiesGrandparent { private String second; 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 aca93c3c621..d410b6ff9c6 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 e6f5f114b2e..79a41b84967 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class SpringBootPlugin implements Plugin { private void verifyGradleVersion() { if (GradleVersion.current().compareTo(GradleVersion.version("4.0")) < 0) { - throw new GradleException("Spring Boot plugin requires Gradle 4.0 or later." - + " The current version is " + GradleVersion.current()); + throw new GradleException("Spring Boot plugin requires Gradle 4.0 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 eee816668b8..ce6595668ec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ import org.slf4j.LoggerFactory; */ class UnresolvedDependenciesAnalyzer { - private static final org.slf4j.Logger logger = LoggerFactory - .getLogger(SpringBootPlugin.class); + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SpringBootPlugin.class); private Set dependenciesWithNoVersion = new HashSet<>(); 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,11 +51,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(" " + dependency + "\n")); - message.append("\nDid you forget to apply the " - + "io.spring.dependency-management plugin to the " + project.getName() - + " project?\n"); + this.dependenciesWithNoVersion.forEach((dependency) -> message.append(" " + dependency + "\n")); + message.append("\nDid you forget to apply the " + "io.spring.dependency-management plugin to the " + + project.getName() + " 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 c7fd16ed86e..a09c2e8cacc 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 @@ -65,21 +65,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); } @@ -90,9 +87,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; @@ -101,8 +97,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() { @@ -150,8 +145,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 3e353e9c960..7d49f30e336 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 @@ -37,8 +37,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; @@ -57,16 +57,14 @@ public class BootJar extends Jar implements BootArchive { } 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(); } @@ -78,8 +76,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); } @@ -125,8 +122,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 26e786288c2..a4b8ef6ff7f 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 @@ -38,8 +38,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; @@ -50,15 +50,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())); } @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(); } @@ -70,8 +68,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); } @@ -127,9 +124,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); } /** @@ -174,8 +170,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 989d023f1a2..33a865ad5a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.boot.loader.tools.FileUtils; */ class BootZipCopyAction implements CopyAction { - private static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, - Calendar.FEBRUARY, 1, 0, 0, 0).getTimeInMillis(); + private 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 { @@ -120,13 +118,11 @@ class BootZipCopyAction implements CopyAction { } @SuppressWarnings("unchecked") - 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(); } @@ -134,8 +130,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) { @@ -160,15 +156,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]; @@ -189,19 +183,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; @@ -215,9 +208,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; @@ -241,14 +233,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); @@ -269,8 +259,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()); @@ -278,14 +268,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 15b2f8cd0a3..79649c9f07a 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. @@ -112,8 +112,7 @@ 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; } 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 351b5481300..9545dd9a78c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/BootRunApplication.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/BootRunApplication.java index 34ce55940fa..f70c5eca863 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/BootRunApplication.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/com/example/BootRunApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 BootRunApplication { 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 13f034f685a..8d03ecf500e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 GettingStartedDocumentationTests { @Test public void typicalPluginsAppliesExceptedPlugins() { - this.gradleBuild.script("src/main/gradle/getting-started/typical-plugins.gradle") - .build("verify"); + this.gradleBuild.script("src/main/gradle/getting-started/typical-plugins.gradle").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 53e356379a4..7f388861663 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 IntegratingWithActuatorDocumentationTests { @Test public void basicBuildInfo() throws IOException { - this.gradleBuild.script( - "src/main/gradle/integrating-with-actuator/build-info-basic.gradle") + this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-basic.gradle") .build("bootBuildInfo"); - assertThat(new File(this.gradleBuild.getProjectDir(), - "build/resources/main/META-INF/build-info.properties")).isFile(); + assertThat(new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties")) + .isFile(); } @Test public void buildInfoCustomValues() throws IOException { - this.gradleBuild.script( - "src/main/gradle/integrating-with-actuator/build-info-custom-values.gradle") + this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-custom-values.gradle") .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"); @@ -64,11 +61,9 @@ public class IntegratingWithActuatorDocumentationTests { @Test public void buildInfoAdditional() throws IOException { - this.gradleBuild.script( - "src/main/gradle/integrating-with-actuator/build-info-additional.gradle") + this.gradleBuild.script("src/main/gradle/integrating-with-actuator/build-info-additional.gradle") .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 2728505e4ff..1d21bd52b1c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +35,19 @@ public class ManagingDependenciesDocumentationTests { @Test public void dependenciesExampleEvaluatesSuccessfully() { - this.gradleBuild - .script("src/main/gradle/managing-dependencies/dependencies.gradle") - .build(); + this.gradleBuild.script("src/main/gradle/managing-dependencies/dependencies.gradle").build(); } @Test public void customManagedVersions() { - assertThat(this.gradleBuild - .script("src/main/gradle/managing-dependencies/custom-version.gradle") + assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/custom-version.gradle") .build("slf4jVersion").getOutput()).contains("1.7.20"); } @Test public void dependencyManagementInIsolation() { - assertThat(this.gradleBuild - .script("src/main/gradle/managing-dependencies/configure-bom.gradle") - .build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter "); + assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom.gradle") + .build("dependencyManagement").getOutput()).contains("org.springframework.boot:spring-boot-starter "); } } 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 b6bdb825a7e..5c58dd66b2f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +43,12 @@ public class PackagingDocumentationTests { @Test public void warContainerDependencyEvaluatesSuccessfully() { - this.gradleBuild - .script("src/main/gradle/packaging/war-container-dependency.gradle") - .build(); + this.gradleBuild.script("src/main/gradle/packaging/war-container-dependency.gradle").build(); } @Test public void bootJarMainClass() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-main-class.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-main-class.gradle").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -63,9 +60,7 @@ public class PackagingDocumentationTests { @Test public void bootJarManifestMainClass() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/boot-jar-manifest-main-class.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-manifest-main-class.gradle").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -77,9 +72,7 @@ public class PackagingDocumentationTests { @Test public void applicationPluginMainClass() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/application-plugin-main-class.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/application-plugin-main-class.gradle").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -91,9 +84,7 @@ public class PackagingDocumentationTests { @Test public void springBootDslMainClass() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/spring-boot-dsl-main-class.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/spring-boot-dsl-main-class.gradle").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -105,25 +96,19 @@ public class PackagingDocumentationTests { @Test public void bootWarIncludeDevtools() throws IOException { - new File(this.gradleBuild.getProjectDir(), - "spring-boot-devtools-1.2.3.RELEASE.jar").createNewFile(); - this.gradleBuild - .script("src/main/gradle/packaging/boot-war-include-devtools.gradle") - .build("bootWar"); + new File(this.gradleBuild.getProjectDir(), "spring-boot-devtools-1.2.3.RELEASE.jar").createNewFile(); + this.gradleBuild.script("src/main/gradle/packaging/boot-war-include-devtools.gradle").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(); } } @Test public void bootJarRequiresUnpack() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/boot-jar-requires-unpack.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-requires-unpack.gradle").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -136,37 +121,28 @@ public class PackagingDocumentationTests { @Test public void bootJarIncludeLaunchScript() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/boot-jar-include-launch-script.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-include-launch-script.gradle").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"); } @Test public void bootJarLaunchScriptProperties() throws IOException { - this.gradleBuild.script( - "src/main/gradle/packaging/boot-jar-launch-script-properties.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-launch-script-properties.gradle").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"); } @Test 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.gradle") - .build("bootJar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-custom-launch-script.gradle").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); @@ -175,9 +151,7 @@ public class PackagingDocumentationTests { @Test public void bootWarPropertiesLauncher() throws IOException { - this.gradleBuild - .script("src/main/gradle/packaging/boot-war-properties-launcher.gradle") - .build("bootWar"); + this.gradleBuild.script("src/main/gradle/packaging/boot-war-properties-launcher.gradle").build("bootWar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war"); assertThat(file).isFile(); @@ -189,8 +163,7 @@ public class PackagingDocumentationTests { @Test public void bootJarAndJar() throws IOException { - this.gradleBuild.script("src/main/gradle/packaging/boot-jar-and-jar.gradle") - .build("assemble"); + this.gradleBuild.script("src/main/gradle/packaging/boot-jar-and-jar.gradle").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 9514880391e..ed89c6cd83d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +37,15 @@ public class PublishingDocumentationTests { @Test public void mavenUpload() throws IOException { - assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven.gradle") - .build("deployerRepository").getOutput()) - .contains("https://repo.example.com"); + assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven.gradle").build("deployerRepository") + .getOutput()).contains("https://repo.example.com"); } @Test public void mavenPublish() throws IOException { - assertThat( - this.gradleBuild.script("src/main/gradle/publishing/maven-publish.gradle") - .build("publishingConfiguration").getOutput()) - .contains("MavenPublication") - .contains("https://repo.example.com"); + assertThat(this.gradleBuild.script("src/main/gradle/publishing/maven-publish.gradle") + .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 f362f67a7a4..79014814cd8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,33 +38,26 @@ public class RunningDocumentationTests { @Test public void bootRunMain() throws IOException { - assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-main.gradle") - .build("configuredMainClass").getOutput()) - .contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-main.gradle").build("configuredMainClass") + .getOutput()).contains("com.example.ExampleApplication"); } @Test public void applicationPluginMainClassName() throws IOException { - assertThat(this.gradleBuild.script( - "src/main/gradle/running/application-plugin-main-class-name.gradle") - .build("configuredMainClass").getOutput()) - .contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/main/gradle/running/application-plugin-main-class-name.gradle") + .build("configuredMainClass").getOutput()).contains("com.example.ExampleApplication"); } @Test public void springBootDslMainClassName() throws IOException { - assertThat(this.gradleBuild - .script("src/main/gradle/running/spring-boot-dsl-main-class-name.gradle") - .build("configuredMainClass").getOutput()) - .contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/main/gradle/running/spring-boot-dsl-main-class-name.gradle") + .build("configuredMainClass").getOutput()).contains("com.example.ExampleApplication"); } @Test public void bootRunSourceResources() throws IOException { - assertThat(this.gradleBuild - .script("src/main/gradle/running/boot-run-source-resources.gradle") - .build("configuredClasspath").getOutput()) - .contains(new File("src/main/resources").getPath()); + assertThat(this.gradleBuild.script("src/main/gradle/running/boot-run-source-resources.gradle") + .build("configuredClasspath").getOutput()).contains(new File("src/main/resources").getPath()); } } 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 af4d7b85b42..bfbd45c1f4d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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"); @@ -68,24 +65,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"); @@ -93,13 +87,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"); @@ -108,13 +100,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/GradleCompatibilitySuite.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilitySuite.java index 84d3619e94c..47685b045d2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilitySuite.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilitySuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.boot.gradle.testkit.GradleBuild; */ public final class GradleCompatibilitySuite extends Suite { - private static final List GRADLE_VERSIONS = Arrays.asList("default", "4.1", - "4.2", "4.3", "4.4.1", "4.5.1", "4.6", "4.7", "4.8.1", "4.9", "4.10.2"); + private static final List GRADLE_VERSIONS = Arrays.asList("default", "4.1", "4.2", "4.3", "4.4.1", "4.5.1", + "4.6", "4.7", "4.8.1", "4.9", "4.10.2"); public GradleCompatibilitySuite(Class clazz) throws InitializationError { super(clazz, createRunners(clazz)); @@ -53,13 +53,11 @@ public final class GradleCompatibilitySuite extends Suite { return runners; } - private static final class GradleCompatibilityClassRunner - extends BlockJUnit4ClassRunner { + private static final class GradleCompatibilityClassRunner extends BlockJUnit4ClassRunner { private final String gradleVersion; - private GradleCompatibilityClassRunner(Class klass, String gradleVersion) - throws InitializationError { + private GradleCompatibilityClassRunner(Class klass, String gradleVersion) throws InitializationError { super(klass); this.gradleVersion = gradleVersion; } 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 4d3cdad0164..8551d65424c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,120 +51,100 @@ public class ApplicationPluginActionIntegrationTests { @Test 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"); } @Test 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"); } @Test 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"); } @Test 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"); } @Test 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]"); } @Test 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"); } @Test 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"); } @Test 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"); } @Test 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"); } @Test 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"); } @Test 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; @@ -190,8 +170,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()); @@ -200,10 +179,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 1fd5f3c3f44..1f6cd3a6459 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,35 +45,28 @@ public class DependencyManagementPluginActionIntegrationTests { @Test 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); } @Test 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); } @Test 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 15119c7a069..2d51a823d8a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JavaPluginActionIntegrationTests { @Test 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"); } @Test @@ -64,16 +63,14 @@ public class JavaPluginActionIntegrationTests { @Test 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"); } @Test 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"); } @Test @@ -108,8 +105,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"); } @Test @@ -120,42 +116,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")); } @Test - 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()); } @Test - 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 373339f41c5..ca104cb57a1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +38,27 @@ public class KotlinPluginActionIntegrationTests { @Test public void noKotlinVersionPropertyWithoutKotlinPlugin() { - assertThat(this.gradleBuild.build("kotlinVersion").getOutput()) - .contains("Kotlin version: none"); + assertThat(this.gradleBuild.build("kotlinVersion").getOutput()).contains("Kotlin version: none"); } @Test public void kotlinVersionMatchesKotlinPluginVersion() { - String output = this.gradleBuild.build("kotlinVersion", "dependencies", - "--configuration", "compileClasspath").getOutput(); + String output = this.gradleBuild.build("kotlinVersion", "dependencies", "--configuration", "compileClasspath") + .getOutput(); assertThat(output).contains("Kotlin version: 1.2.10"); - assertThat(output) - .containsPattern("org.jetbrains.kotlin:kotlin-stdlib-jdk8:* -> 1.2.10"); + assertThat(output).containsPattern("org.jetbrains.kotlin:kotlin-stdlib-jdk8:* -> 1.2.10"); } @Test 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"); } @Test 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 e87d242af32..1d619928bd6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,36 +41,33 @@ public class MainClassConventionTests { @Before public void createConvention() throws IOException { - this.project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder()) - .build(); + this.project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder()).build(); this.convention = new MainClassConvention(this.project, () -> null); } @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 177db641186..92c5f76b9ad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 MavenPluginActionIntegrationTests { @Test 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 c61d0d6f60a..3063c9bd377 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class SpringBootPluginIntegrationTests { @Test public void failFastWithVersionOfGradleLowerThanRequired() { BuildResult result = this.gradleBuild.gradleVersion("3.5.1").buildAndFail(); - assertThat(result.getOutput()).contains("Spring Boot plugin requires Gradle 4.0" - + " or later. The current version is Gradle 3.5.1"); + assertThat(result.getOutput()) + .contains("Spring Boot plugin requires Gradle 4.0" + " or later. The current version is Gradle 3.5.1"); } @Test @@ -55,19 +55,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 c6542454fdf..234d41066ed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +48,8 @@ public class WarPluginActionIntegrationTests { @Test 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"); } @Test @@ -68,16 +67,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")); } @Test 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 7946429dda1..5957464ab0c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +45,18 @@ public class BuildInfoIntegrationTests { @Test 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"); } @Test 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"); @@ -71,32 +68,28 @@ public class BuildInfoIntegrationTests { @Test 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); } @Test 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); } @Test 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); } 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 97b179afb86..9e84032a27a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -128,8 +127,7 @@ public class BuildInfoTests { private Project createProject(String projectName) { try { File projectDir = this.temp.newFolder(projectName); - return ProjectBuilder.builder().withProjectDir(projectDir) - .withName(projectName).build(); + return ProjectBuilder.builder().withProjectDir(projectDir).withName(projectName).build(); } catch (IOException ex) { throw new RuntimeException(ex); @@ -142,8 +140,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 fd80e8095c0..4014b320c27 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,80 +51,72 @@ public abstract class AbstractBootArchiveIntegrationTests { } @Test - 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); } @Test - 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); } @Test - 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); } @Test 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); } @Test 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); } @Test 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); } @Test 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); } @Test 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"); } @@ -132,11 +124,9 @@ public abstract class AbstractBootArchiveIntegrationTests { @Test 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"); } @@ -144,8 +134,8 @@ public abstract class AbstractBootArchiveIntegrationTests { @Test 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 0725e306f58..6d94910962a 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 @@ -66,8 +66,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; @@ -77,10 +76,8 @@ public abstract class AbstractBootArchiveTests { @Before public void createTask() { try { - Project project = ProjectBuilder.builder() - .withProjectDir(this.temp.newFolder()).build(); - this.task = configure( - project.getTasks().create("testArchive", this.taskClass)); + Project project = ProjectBuilder.builder().withProjectDir(this.temp.newFolder()).build(); + this.task = configure(project.getTasks().create("testArchive", this.taskClass)); } catch (IOException ex) { throw new RuntimeException(ex); @@ -93,17 +90,12 @@ public abstract class AbstractBootArchiveTests { this.task.execute(); 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(); } } @@ -122,16 +114,13 @@ public abstract class AbstractBootArchiveTests { public void classpathFoldersArePackagedBeneathClassesPath() throws IOException { this.task.setMainClassName("com.example.Main"); File classpathFolder = this.temp.newFolder(); - 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(); } } @@ -139,8 +128,7 @@ public abstract class AbstractBootArchiveTests { public void classpathCanBeSetUsingAFileCollection() throws IOException { this.task.setMainClassName("com.example.Main"); this.task.classpath(this.temp.newFile("one.jar")); - this.task - .setClasspath(this.task.getProject().files(this.temp.newFile("two.jar"))); + this.task.setClasspath(this.task.getProject().files(this.temp.newFile("two.jar"))); this.task.execute(); try (JarFile jarFile = new JarFile(this.task.getArchivePath())) { assertThat(jarFile.getEntry(this.libPath + "one.jar")).isNull(); @@ -165,24 +153,18 @@ public abstract class AbstractBootArchiveTests { this.task.setMainClassName("com.example.Main"); this.task.execute(); 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"); this.task.execute(); - 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(); } } @@ -194,8 +176,7 @@ public abstract class AbstractBootArchiveTests { this.task.requiresUnpack("**/one.jar"); this.task.execute(); 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(); } } @@ -207,8 +188,7 @@ public abstract class AbstractBootArchiveTests { this.task.requiresUnpack((element) -> element.getName().endsWith("two.jar")); this.task.execute(); 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(); } } @@ -221,8 +201,7 @@ public abstract class AbstractBootArchiveTests { assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())) .startsWith(new DefaultLaunchScript(null, null).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) { @@ -234,19 +213,17 @@ public abstract class AbstractBootArchiveTests { public void customLaunchScriptCanBePrepended() throws IOException { this.task.setMainClassName("com.example.Main"); File customScript = this.temp.newFile("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)); this.task.execute(); - assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())) - .startsWith("custom script".getBytes()); + assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())).startsWith("custom script".getBytes()); } @Test public void launchScriptPropertiesAreReplaced() throws IOException { this.task.setMainClassName("com.example.Main"); - this.task.launchScript((configuration) -> configuration.getProperties() - .put("initInfoProvides", "test property value")); + this.task.launchScript( + (configuration) -> configuration.getProperties().put("initInfoProvides", "test property value")); this.task.execute(); assertThat(Files.readAllBytes(this.task.getArchivePath().toPath())) .containsSequence("test property value".getBytes()); @@ -255,31 +232,25 @@ public abstract class AbstractBootArchiveTests { @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"); this.task.execute(); 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"); this.task.execute(); 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"); } @@ -295,8 +266,7 @@ public abstract class AbstractBootArchiveTests { Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - assertThat(entry.getTime()) - .isEqualTo(GUtil.CONSTANT_TIME_FOR_ZIP_ENTRIES); + assertThat(entry.getTime()).isEqualTo(GUtil.CONSTANT_TIME_FOR_ZIP_ENTRIES); } } } @@ -329,8 +299,7 @@ public abstract class AbstractBootArchiveTests { this.task.execute(); 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(); } } @@ -342,8 +311,7 @@ public abstract class AbstractBootArchiveTests { this.task.execute(); 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(); } } @@ -369,24 +337,19 @@ public abstract class AbstractBootArchiveTests { } @Test - public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() - throws IOException { + public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException { this.task.setMainClassName("com.example.Main"); File classpathFolder = this.temp.newFolder(); - 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.temp.newFile("first-library.jar"), - this.temp.newFile("second-library.jar"), - this.temp.newFile("third-library.jar")); + this.temp.newFile("second-library.jar"), this.temp.newFile("third-library.jar")); this.task.requiresUnpack("second-library.jar"); this.task.execute(); - 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"); } private T configure(T task) 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 af641c3bd8b..0ac8d0ad64d 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.execute(); 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.execute(); 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 df24117e08b..7d024510fac 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,15 +32,13 @@ 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 public void providedClasspathJarsArePackagedInWebInfLibProvided() throws IOException { getTask().setMainClassName("com.example.Main"); - getTask().providedClasspath(this.temp.newFile("one.jar"), - this.temp.newFile("two.jar")); + getTask().providedClasspath(this.temp.newFile("one.jar"), this.temp.newFile("two.jar")); getTask().execute(); try (JarFile jarFile = new JarFile(getTask().getArchivePath())) { assertThat(jarFile.getEntry("WEB-INF/lib-provided/one.jar")).isNotNull(); @@ -52,8 +50,7 @@ public class BootWarTests extends AbstractBootArchiveTests { public void providedClasspathCanBeSetUsingAFileCollection() throws IOException { getTask().setMainClassName("com.example.Main"); getTask().providedClasspath(this.temp.newFile("one.jar")); - getTask().setProvidedClasspath( - getTask().getProject().files(this.temp.newFile("two.jar"))); + getTask().setProvidedClasspath(getTask().getProject().files(this.temp.newFile("two.jar"))); getTask().execute(); try (JarFile jarFile = new JarFile(getTask().getArchivePath())) { assertThat(jarFile.getEntry("WEB-INF/lib-provided/one.jar")).isNull(); @@ -74,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(this.temp.newFile("spring-boot-devtools-0.1.2.jar")); getTask().execute(); 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(this.temp.newFile("spring-boot-devtools-0.1.2.jar")); getTask().setExcludeDevtools(false); getTask().execute(); 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 = this.temp.newFolder("src", "main", "webapp"); File orgFolder = new File(webappFolder, "org"); orgFolder.mkdir(); @@ -125,8 +115,8 @@ public class BootWarTests extends AbstractBootArchiveTests { getTask().classpath(this.temp.newFile("library.jar")); getTask().providedClasspath(this.temp.newFile("provided-library.jar")); getTask().execute(); - 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"); } } 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 5061bda160f..e798d5fcb34 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +45,20 @@ public class MavenIntegrationTests { @Test 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()); } @Test 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 bf485689bb1..8ab7c32b473 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); } @Test @@ -58,9 +57,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 50585d9d6c5..6c0e96f32ac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +48,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")); } @Test @@ -61,54 +58,42 @@ public class BootRunIntegrationTests { copyApplication(); 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")); } @Test 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"); } @Test 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"); } @Test public void applicationPluginMainClassNameIsNotUsedWhenItIsNull() throws IOException { copyApplication(); BuildResult result = this.gradleBuild.build("echoMainClassName"); - assertThat(result.task(":echoMainClassName").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()) - .contains("Main class name = com.example.BootRunApplication"); + assertThat(result.task(":echoMainClassName").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.getOutput()).contains("Main class name = com.example.BootRunApplication"); } @Test public void applicationPluginJvmArgumentsAreUsed() throws IOException { BuildResult result = this.gradleBuild.build("echoJvmArguments"); - assertThat(result.task(":echoJvmArguments").getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); - assertThat(result.getOutput()) - .contains("JVM arguments = [-Dcom.foo=bar, -Dcom.bar=baz]"); + assertThat(result.task(":echoJvmArguments").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(result.getOutput()).contains("JVM arguments = [-Dcom.foo=bar, -Dcom.bar=baz]"); } private void copyApplication() throws IOException { - File output = new File(this.gradleBuild.getProjectDir(), - "src/main/java/com/example"); + File output = new File(this.gradleBuild.getProjectDir(), "src/main/java/com/example"); output.mkdirs(); FileSystemUtils.copyRecursively(new File("src/test/java/com/example"), output); } 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 b60314f665f..07e2fd8cf1d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +112,9 @@ public class GradleBuild implements TestRule { private String pluginClasspath() { return absolutePath("bin") + "," + absolutePath("build/classes/java/main") + "," - + absolutePath("build/resources/main") + "," - + pathOfJarContaining(LaunchScript.class) + "," - + pathOfJarContaining(ClassVisitor.class) + "," - + pathOfJarContaining(DependencyManagementPlugin.class) + "," - + pathOfJarContaining(ArchiveEntry.class); + + absolutePath("build/resources/main") + "," + pathOfJarContaining(LaunchScript.class) + "," + + pathOfJarContaining(ClassVisitor.class) + "," + pathOfJarContaining(DependencyManagementPlugin.class) + + "," + pathOfJarContaining(ArchiveEntry.class); } private String absolutePath(String path) { @@ -151,12 +149,10 @@ public class GradleBuild implements TestRule { } public GradleRunner prepareRunner(String... arguments) throws IOException { - String scriptContent = FileCopyUtils.copyToString(new FileReader(this.script)) - .replace("{version}", getBootVersion()); - FileCopyUtils.copy(scriptContent, - new FileWriter(new File(this.projectDir, "build.gradle"))); - GradleRunner gradleRunner = GradleRunner.create().withProjectDir(this.projectDir) - .withDebug(true); + String scriptContent = FileCopyUtils.copyToString(new FileReader(this.script)).replace("{version}", + getBootVersion()); + FileCopyUtils.copy(scriptContent, new FileWriter(new File(this.projectDir, "build.gradle"))); + GradleRunner gradleRunner = GradleRunner.create().withProjectDir(this.projectDir).withDebug(true); if (this.gradleVersion != null) { gradleRunner.withGradleVersion(this.gradleVersion); } @@ -187,8 +183,7 @@ public class GradleBuild implements TestRule { private static String getBootVersion() { return evaluateExpression( - "/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" - + "/text()"); + "/*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" + "/text()"); } private static String evaluateExpression(String expression) { @@ -196,8 +191,7 @@ public class GradleBuild implements TestRule { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression expr = xpath.compile(expression); - String version = expr - .evaluate(new InputSource(new FileReader(".flattened-pom.xml"))); + String version = expr.evaluate(new InputSource(new FileReader(".flattened-pom.xml"))); return version; } catch (Exception ex) { 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 14614dc89cb..e82887b64b0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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() + "'"); } } @@ -74,12 +73,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; } @@ -101,8 +98,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; @@ -112,8 +109,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) { @@ -152,8 +148,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 62d57407e77..81608492463 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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,13 +371,11 @@ 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")) + if ((entry.getName().startsWith("META-INF/") && !entry.getName().equals("META-INF/aop.xml")) || entry.getName().startsWith("BOOT-INF/")) { 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()); @@ -422,14 +412,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()); } } } @@ -446,16 +435,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 8d9fb3bc5c3..105627a9648 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. @@ -66,8 +66,7 @@ public class RunProcess { return run(waitForProcess, Arrays.asList(args)); } - protected int run(boolean waitForProcess, Collection args) - throws IOException { + protected int run(boolean waitForProcess, Collection args) 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 b14af91f353..e07f0b04c35 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 41b36bac5fa..65321d3eb67 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -49,8 +48,7 @@ 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 @@ -63,27 +61,19 @@ public class LayoutsTests { @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 881c8d96168..b09e1487262 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); + this.thrown + .expectMessage("Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]"); MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), ""); } @@ -93,8 +93,7 @@ public class MainClassFinderTests { 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"); } @@ -103,8 +102,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"); } @@ -139,8 +137,8 @@ public class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); + this.thrown + .expectMessage("Unable to find a single main class " + "from the following candidates [a.B, a.b.c.E]"); MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource()); } @@ -148,8 +146,7 @@ public class MainClassFinderTests { 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 ac1b9395da8..618b726ba13 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); } @@ -137,8 +136,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(); } @@ -151,8 +149,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(); } @@ -166,8 +163,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(); } @@ -178,8 +174,8 @@ public class RepackagerTests { File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.b.C, a.b.D]"); + this.thrown + .expectMessage("Unable to find a single main class " + "from the following candidates [a.b.C, a.b.D]"); repackager.repackage(NO_LIBRARIES); } @@ -199,8 +195,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(); } @@ -233,8 +228,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(); } @@ -245,8 +239,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(); } @@ -298,8 +291,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); @@ -309,8 +301,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); @@ -347,16 +338,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 @@ -371,12 +358,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 @@ -386,8 +370,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 @@ -397,24 +380,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 @@ -435,15 +417,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); } } @@ -460,8 +438,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 @@ -469,8 +446,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(); @@ -479,21 +455,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); @@ -505,16 +478,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); @@ -548,11 +519,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); @@ -581,10 +550,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(); @@ -596,31 +563,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:"); } @@ -636,15 +595,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)) { { @@ -666,8 +623,7 @@ public class RepackagerTests { 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 8467a79746a..ce892ff85ab 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 9454b1094ee..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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 461969e579b..8c4a3e99e43 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 ca7bae40c2f..5be09442025 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() { @@ -166,12 +161,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 190a70d4a2a..1a96213427a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +55,14 @@ 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 final Method OPEN_CONNECTION_METHOD; static { Method method = null; try { - method = URLStreamHandler.class.getDeclaredMethod("openConnection", - URL.class); + method = URLStreamHandler.class.getDeclaredMethod("openConnection", URL.class); } catch (Exception ex) { // Swallow and ignore @@ -92,8 +90,7 @@ public class Handler extends URLStreamHandler { @Override protected URLConnection openConnection(URL url) throws IOException { - if (this.jarFile != null - && url.toString().startsWith(this.jarFile.getUrl().toString())) { + if (this.jarFile != null && url.toString().startsWith(this.jarFile.getUrl().toString())) { return JarURLConnection.get(url, this.jarFile); } try { @@ -104,8 +101,7 @@ public class Handler extends URLStreamHandler { } } - private URLConnection openFallbackConnection(URL url, Exception reason) - throws IOException { + private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException { try { return openConnection(getFallbackHandler(), url); } @@ -151,11 +147,9 @@ 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 { if (OPEN_CONNECTION_METHOD == null) { - throw new IllegalStateException( - "Unable to invoke fallback open connection method"); + throw new IllegalStateException("Unable to invoke fallback open connection method"); } OPEN_CONNECTION_METHOD.setAccessible(true); return (URLConnection) OPEN_CONNECTION_METHOD.invoke(handler, url); @@ -195,8 +189,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; } @@ -204,8 +197,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); } @@ -218,8 +210,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) { @@ -238,8 +229,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); @@ -359,8 +349,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 331e47d95ab..22805568c73 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. @@ -104,14 +104,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; @@ -137,16 +136,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; } } @@ -250,8 +246,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); } } @@ -270,22 +265,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 @@ -335,8 +328,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(); @@ -377,8 +369,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 4dc3536ee50..fd7d264568d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; } @@ -86,8 +85,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]; @@ -206,16 +204,14 @@ 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) { int hashCode = AsciiBytes.hashCode(name); T entry = getEntry(hashCode, name, NO_SUFFIX, type, cacheEntry); if (entry == null) { @@ -225,8 +221,8 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { return entry; } - private T getEntry(int hashCode, CharSequence name, - char suffix, Class type, boolean cacheEntry) { + private T getEntry(int hashCode, CharSequence name, char suffix, Class type, + boolean cacheEntry) { int index = getFirstIndex(hashCode); while (index >= 0 && index < this.size && this.hashCodes[index] == hashCode) { T entry = getEntry(index, type, cacheEntry); @@ -239,16 +235,12 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { } @SuppressWarnings("unchecked") - private T getEntry(int index, Class type, - boolean cacheEntry) { + private T getEntry(int index, Class type, boolean cacheEntry) { 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)) { + 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); } if (cacheEntry && cached != 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 fb5d7290c5f..8b173346ea2 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 440d6e63438..b9a02122c3d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,28 +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(), - new URL("jar:" - + new File(explodedRoot, "BOOT-INF/lib/foo.jar").toURI().toURL() - + "!/")); + assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "BOOT-INF/classes").toURI().toURL(), + new URL("jar:" + 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 beb4809b2cd..3f5809e115f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -86,16 +85,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"); } @@ -104,8 +101,7 @@ public class PropertiesLauncherTests { System.setProperty("loader.home", "src/test/resources/nonexistent"); this.expected.expectMessage("Invalid source folder"); PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isNotEqualTo(new File(System.getProperty("loader.home"))); + assertThat(launcher.getHomeDirectory()).isNotEqualTo(new File(System.getProperty("loader.home"))); } @Test @@ -120,8 +116,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 @@ -135,16 +130,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!/")); } @@ -154,8 +147,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"); } @@ -165,16 +157,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!/]"); @@ -194,8 +184,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!/")); @@ -221,8 +210,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(); @@ -235,8 +223,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"); } @@ -246,8 +233,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"); } @@ -316,25 +302,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 c53cf7aadaa..04c153a2438 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ public abstract class TestJarCreator { } } - private static void writeNestedEntry(String name, boolean unpackNested, - JarOutputStream jarOutputStream) throws Exception { + private static void writeNestedEntry(String name, boolean unpackNested, JarOutputStream jarOutputStream) + throws Exception { JarEntry nestedEntry = new JarEntry(name); byte[] nestedJarData = getNestedJarData(); nestedEntry.setSize(nestedJarData.length); @@ -85,8 +85,7 @@ 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 { writeDirEntry(jarOutputStream, "META-INF/"); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue("Built-By", name); @@ -96,14 +95,12 @@ public abstract class TestJarCreator { 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 94231ab02ec..70336e7c286 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,28 +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(), - new URL("jar:" - + new File(explodedRoot, "WEB-INF/lib/foo.jar").toURI().toURL() - + "!/")); + assertThat(getUrls(archives)).containsOnly(new File(explodedRoot, "WEB-INF/classes").toURI().toURL(), + new URL("jar:" + 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 22247d31dc5..c035d6b322d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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("jar:" + this.rootFolder.toURI() + "nested.jar!/"); + assertThat(nested.getUrl().toString()).isEqualTo("jar:" + 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 5c89a64cb42..9cf483e9eec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -95,8 +94,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 @@ -122,12 +120,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()); } @@ -156,10 +152,8 @@ public class JarFileArchiveTests { output.closeEntry(); output.close(); JarFileArchive jarFileArchive = new JarFileArchive(file); - this.thrown.expectMessage( - equalTo("Failed to get nested archive for entry nested/zip64.jar")); - jarFileArchive - .getNestedArchive(getEntriesMap(jarFileArchive).get("nested/zip64.jar")); + this.thrown.expectMessage(equalTo("Failed to get nested archive for entry nested/zip64.jar")); + jarFileArchive.getNestedArchive(getEntriesMap(jarFileArchive).get("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 bcf519e234f..4a6d779827f 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. @@ -92,8 +92,7 @@ public class RandomAccessDataFileTests { public void fileExists() { File file = new File("/does/not/exist"); this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - String.format("File %s must exist", file.getAbsolutePath())); + this.thrown.expectMessage(String.format("File %s must exist", file.getAbsolutePath())); new RandomAccessDataFile(file); } @@ -110,23 +109,20 @@ public class RandomAccessDataFileTests { } @Test - public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() - throws Exception { + public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception { this.thrown.expect(IndexOutOfBoundsException.class); RandomAccessData subsection = this.file.getSubsection(0, 10); subsection.read(11, 0); } @Test - public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() - throws Exception { + public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception { this.thrown.expect(EOFException.class); this.file.read(256, 1); } @Test - public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() - throws Exception { + public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception { this.thrown.expect(EOFException.class); RandomAccessData subsection = this.file.getSubsection(0, 10); subsection.read(10, 1); @@ -297,8 +293,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 5b3aeede7fa..ceae26993e7 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. @@ -112,8 +112,7 @@ public class AsciiBytesTests { 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 1f48633b352..c475143aba4 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ -90,13 +89,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()); } @@ -115,14 +112,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 46a8de7aa1b..a8db2ebacc2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); @@ -42,8 +41,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()); @@ -51,8 +49,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()); @@ -60,23 +57,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 @@ -85,96 +78,77 @@ 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"); } - 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 d0ea2b09023..90cddcae42a 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. @@ -112,8 +112,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 @@ -142,8 +141,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(); } @@ -157,8 +155,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); @@ -187,8 +184,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(); @@ -204,19 +200,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"); @@ -229,8 +222,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"); this.thrown.expect(FileNotFoundException.class); ((JarURLConnection) url.openConnection()).getJarEntry(); } @@ -254,8 +246,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/"); @@ -265,18 +256,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"); @@ -291,31 +279,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); @@ -332,8 +315,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"); } @@ -344,8 +326,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 { @@ -357,15 +338,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); } @@ -380,8 +359,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 @@ -428,8 +407,7 @@ 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"); this.thrown.expect(FileNotFoundException.class); @@ -489,14 +467,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(); this.thrown.expect(FileNotFoundException.class); - 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); 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 cf1165c0fe5..41eba11b5a5 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. @@ -61,15 +61,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 @@ -87,8 +85,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 })); @@ -109,32 +106,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 })); } @@ -148,33 +139,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")); this.thrown.expect(FileNotFoundException.class); 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); } @@ -182,33 +170,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 e0510ab93c8..1b544f444de 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. @@ -65,22 +65,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 @@ -153,10 +149,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 b6d3a31a4a1..908a5d4132e 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. @@ -90,8 +90,8 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { this.excludeArtifactIds = excludeArtifactIds; } - 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)); @@ -112,10 +112,8 @@ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { for (ArtifactsFilter additionalFilter : additionalFilters) { filters.addFilter(additionalFilter); } - filters.addFilter( - new ArtifactIdFilter("", cleanFilterConfig(this.excludeArtifactIds))); - filters.addFilter( - new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); + filters.addFilter(new ArtifactIdFilter("", cleanFilterConfig(this.excludeArtifactIds))); + 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 6b33e1521c9..79c9eacad8b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -183,8 +183,7 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { * @return {@code true} if the application process should be forked */ protected boolean isFork() { - return (Boolean.TRUE.equals(this.fork) - || (this.fork == null && enableForkByDefault())); + return (Boolean.TRUE.equals(this.fork) || (this.fork == null && enableForkByDefault())); } /** @@ -208,11 +207,9 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { 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); } @@ -232,16 +229,14 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { getLog().warn("Fork mode disabled, ignoring agent"); } if (hasJvmArgs()) { - getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" - + this.jvmArguments + "]"); + getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" + this.jvmArguments + "]"); } if (hasWorkingDirectorySet()) { 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); @@ -357,8 +352,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; } @@ -390,8 +385,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); } } } @@ -400,12 +394,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()); @@ -461,9 +452,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); } } } @@ -498,9 +487,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 ba3a26bec32..9ec1c412b0f 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 @@ -58,8 +58,7 @@ import org.springframework.boot.loader.tools.Repackager.MainClassTimeoutWarningL * @author Dave Syer * @author Stephane Nicoll */ -@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 { @@ -214,10 +213,8 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { File source = this.project.getArtifact().getFile(); File target = getTargetFile(); Repackager repackager = getRepackager(source); - 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); @@ -236,14 +233,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); @@ -269,8 +265,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; } @@ -281,11 +276,9 @@ 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; } @@ -293,8 +286,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { return (description != null) ? description.replaceAll("\\s+", " ") : 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()) { @@ -317,10 +309,8 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { private void attachArtifact(File source, File repackaged) { if (this.classifier != null) { - getLog().info("Attaching archive: " + repackaged + ", with classifier: " - + this.classifier); - this.projectHelper.attachArtifact(this.project, this.project.getPackaging(), - this.classifier, repackaged); + getLog().info("Attaching archive: " + repackaged + ", with classifier: " + this.classifier); + this.projectHelper.attachArtifact(this.project, this.project.getPackaging(), this.classifier, repackaged); } else if (!source.equals(repackaged)) { this.project.getArtifact().setFile(repackaged); @@ -328,8 +318,7 @@ public class RepackageMojo extends AbstractDependencyFilterMojo { } } - 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 453dc925caf..f7602e0dfa5 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 @@ -65,19 +65,15 @@ public class RunMojo extends AbstractRunMojo { } @Override - protected void runWithForkedJvm(File workingDirectory, List args) - throws MojoExecutionException { + protected void runWithForkedJvm(File workingDirectory, List args) 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))); int exitCode = runProcess.run(true, args.toArray(new String[0])); 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); } catch (Exception ex) { throw new MojoExecutionException("Could not exec java", ex); @@ -85,11 +81,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 bc0c0ea3129..34094370023 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 @@ -49,8 +49,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 { @@ -102,11 +101,9 @@ public class StartMojo extends AbstractRunMojo { } } - private RunProcess runProcess(File workingDirectory, List args) - throws MojoExecutionException { + private RunProcess runProcess(File workingDirectory, List args) throws MojoExecutionException { try { - RunProcess runProcess = new RunProcess(workingDirectory, - new JavaExecutable().toString()); + RunProcess runProcess = new RunProcess(workingDirectory, new JavaExecutable().toString()); runProcess.run(false, args.toArray(new String[0])); return runProcess; } @@ -120,8 +117,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; } @@ -142,18 +138,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..."); @@ -161,8 +155,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 { @@ -170,18 +163,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(); @@ -191,26 +181,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(); @@ -221,21 +205,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); @@ -252,16 +233,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 { @@ -269,14 +248,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 { @@ -294,8 +271,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; } @@ -304,8 +280,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 80236740feb..38cfef4aa11 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,30 @@ public class DependencyFilterMojoTests { @Test public void filterDependencies() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.emptyList(), "com.foo", "exclude-id"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo", + "exclude-id"); Artifact artifact = createArtifact("com.bar", "one"); - Set artifacts = mojo.filterDependencies( - createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), - createArtifact("com.bar", "exclude-id"), artifact); + Set artifacts = mojo.filterDependencies(createArtifact("com.foo", "one"), + createArtifact("com.foo", "two"), createArtifact("com.bar", "exclude-id"), 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 +75,7 @@ public class DependencyFilterMojoTests { @Test public void filterArtifactIdKeepOrder() throws MojoExecutionException { - TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo( - Collections.emptyList(), "", "one,three"); + TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "", "one,three"); Artifact one = createArtifact("com.foo", "one"); Artifact two = createArtifact("com.foo", "two"); Artifact three = createArtifact("com.foo", "three"); @@ -91,8 +86,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"); @@ -106,8 +100,8 @@ 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"); @@ -120,8 +114,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); @@ -131,14 +124,12 @@ public class DependencyFilterMojoTests { return a; } - private static final class TestableDependencyFilterMojo - extends AbstractDependencyFilterMojo { + private static final class TestableDependencyFilterMojo extends AbstractDependencyFilterMojo { private final ArtifactsFilter[] additionalFilters; @SuppressWarnings("deprecation") - private TestableDependencyFilterMojo(List excludes, - String excludeGroupIds, String excludeArtifactIds, + private TestableDependencyFilterMojo(List excludes, String excludeGroupIds, String excludeArtifactIds, ArtifactsFilter... additionalFilters) { setExcludes(excludes); setExcludeGroupIds(excludeGroupIds); @@ -146,8 +137,7 @@ public class DependencyFilterMojoTests { 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/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/Verify.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java index f9dee9c3124..18f5f10dc74 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 = new String(FileCopyUtils.copyToByteArray(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 = new String(FileCopyUtils.copyToByteArray(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/javax.servlet-api-3"); - 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/javax.servlet-api-3"); - 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/javax.servlet-api-3"); + 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/javax.servlet-api-3"); - 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/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 23aab984cd3..0048abf1189 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +50,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()); } } } @@ -64,16 +63,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); } } @@ -82,13 +78,11 @@ public abstract class AbstractConfigurationClassTests { } private boolean isTestClass(Resource resource) throws IOException { - return resource.getFile().getAbsolutePath() - .contains("target" + File.separator + "test-classes"); + return resource.getFile().getAbsolutePath().contains("target" + File.separator + "test-classes"); } 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 893fe85b5fd..a6248903ab0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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); @@ -88,15 +87,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 { @@ -116,8 +114,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) { @@ -167,8 +165,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 { @@ -190,8 +187,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private List getAdditionalUrls(Class testClass) throws Exception { - ClassPathOverrides overrides = AnnotationUtils.findAnnotation(testClass, - ClassPathOverrides.class); + ClassPathOverrides overrides = AnnotationUtils.findAnnotation(testClass, ClassPathOverrides.class); if (overrides == null) { return Collections.emptyList(); } @@ -199,26 +195,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()); @@ -246,8 +235,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private ClassPathEntryFilter(Class testClass) throws Exception { this.exclusions = new ArrayList<>(); this.exclusions.add("log4j-*.jar"); - ClassPathExclusions exclusions = AnnotationUtils.findAnnotation(testClass, - ClassPathExclusions.class); + ClassPathExclusions exclusions = AnnotationUtils.findAnnotation(testClass, ClassPathExclusions.class); if (exclusions != null) { this.exclusions.addAll(Arrays.asList(exclusions.value())); } @@ -275,15 +263,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()); } @@ -293,28 +279,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(); @@ -345,11 +327,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)); } } @@ -363,8 +343,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/CassandraContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/CassandraContainer.java index 538bd2fb07d..e417ea9e9a4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/CassandraContainer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/CassandraContainer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 CassandraContainer extends Container { private static final int PORT = 9042; public CassandraContainer() { - super("cassandra:3.11.1", PORT, - (container) -> container.waitingFor(new WaitStrategy(container)) - .withStartupAttempts(5) - .withStartupTimeout(Duration.ofSeconds(120))); + super("cassandra:3.11.1", PORT, (container) -> container.waitingFor(new WaitStrategy(container)) + .withStartupAttempts(5).withStartupTimeout(Duration.ofSeconds(120))); } private static final class WaitStrategy extends HostPortWaitStrategy { @@ -57,8 +55,7 @@ public class CassandraContainer extends Container { super.waitUntilReady(); try { - Unreliables.retryUntilTrue((int) this.startupTimeout.getSeconds(), - TimeUnit.SECONDS, checkConnection()); + Unreliables.retryUntilTrue((int) this.startupTimeout.getSeconds(), TimeUnit.SECONDS, checkConnection()); } catch (TimeoutException ex) { throw new IllegalStateException(ex); @@ -67,8 +64,7 @@ public class CassandraContainer extends Container { private Callable checkConnection() { return () -> { - try (Cluster cluster = Cluster.builder() - .withPort(this.container.getMappedPort(CassandraContainer.PORT)) + try (Cluster cluster = Cluster.builder().withPort(this.container.getMappedPort(CassandraContainer.PORT)) .addContactPoint("localhost").build()) { cluster.connect(); return true; 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 d860a00ad6e..5fa0736aa3f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +46,10 @@ class Container implements TestRule { } @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); } @@ -79,8 +77,7 @@ class Container implements TestRule { @Override public void evaluate() { - throw new AssumptionViolatedException( - "Could not find a valid Docker environment."); + throw new AssumptionViolatedException("Could not find a valid Docker environment."); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Neo4jContainer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Neo4jContainer.java index f7ec7fee4fc..fdb4aa039c8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Neo4jContainer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/testcontainers/Neo4jContainer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 Neo4jContainer extends Container { private static final int PORT = 7687; public Neo4jContainer() { - super("neo4j:3.3.1", PORT, (container) -> container - .waitingFor(new WaitStrategy(container)).withEnv("NEO4J_AUTH", "none")); + super("neo4j:3.3.1", PORT, + (container) -> container.waitingFor(new WaitStrategy(container)).withEnv("NEO4J_AUTH", "none")); } private static final class WaitStrategy extends HostPortWaitStrategy { @@ -53,14 +53,12 @@ public class Neo4jContainer extends Container { public void waitUntilReady() { super.waitUntilReady(); Configuration configuration = new Configuration.Builder() - .uri("bolt://localhost:" - + this.container.getMappedPort(Neo4jContainer.PORT)) - .build(); + .uri("bolt://localhost:" + this.container.getMappedPort(Neo4jContainer.PORT)).build(); SessionFactory sessionFactory = new SessionFactory(configuration, "org.springframework.boot.test.autoconfigure.data.neo4j"); try { - Unreliables.retryUntilTrue((int) this.startupTimeout.getSeconds(), - TimeUnit.SECONDS, checkConnection(sessionFactory)); + Unreliables.retryUntilTrue((int) this.startupTimeout.getSeconds(), TimeUnit.SECONDS, + checkConnection(sessionFactory)); } catch (TimeoutException ex) { throw new IllegalStateException(ex); 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 4f48f39d8cd..6683dd91d36 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.hamcrest.CoreMatchers.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"; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -46,8 +45,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 79a2b4ef368..78311e82693 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -147,11 +147,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)) { @@ -171,8 +169,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); } @@ -184,8 +181,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)); @@ -261,14 +257,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; } @@ -287,8 +280,8 @@ class BeanDefinitionLoader { } // 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; @@ -298,8 +291,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/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 0166497fda8..b44c8ca1e4a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -256,8 +256,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(); } @@ -292,24 +291,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); @@ -329,8 +323,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(); @@ -338,8 +331,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; @@ -356,9 +349,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); @@ -369,8 +361,7 @@ public class SpringApplication { } // Add boot specific singleton beans - context.getBeanFactory().registerSingleton("springApplicationArguments", - applicationArguments); + context.getBeanFactory().registerSingleton("springApplicationArguments", applicationArguments); if (printedBanner != null) { context.getBeanFactory().registerSingleton("springBootBanner", printedBanner); } @@ -395,49 +386,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 = Thread.currentThread().getContextClassLoader(); // 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; @@ -468,8 +453,7 @@ 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) { configurePropertySources(environment, args); configureProfiles(environment, args); } @@ -481,20 +465,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); } @@ -522,12 +504,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()); } } @@ -548,10 +527,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); } @@ -582,8 +560,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); } } @@ -597,18 +574,15 @@ 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()); } } } @@ -622,8 +596,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); } @@ -636,8 +610,7 @@ public class SpringApplication { */ protected void logStartupInfo(boolean isRoot) { if (isRoot) { - new StartupInfoLogger(this.mainApplicationClass) - .logStarting(getApplicationLog()); + new StartupInfoLogger(this.mainApplicationClass).logStarting(getApplicationLog()); } } @@ -679,11 +652,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); } @@ -728,8 +699,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"); } @@ -740,8 +710,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); } @@ -759,8 +728,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) { @@ -796,10 +764,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); @@ -820,8 +786,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)) { @@ -851,8 +816,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) { @@ -865,8 +829,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); @@ -874,14 +837,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(); } @@ -904,8 +865,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()); } @@ -956,8 +916,7 @@ public class SpringApplication { */ @Deprecated public void setWebEnvironment(boolean webEnvironment) { - this.webApplicationType = (webEnvironment ? WebApplicationType.SERVLET - : WebApplicationType.NONE); + this.webApplicationType = (webEnvironment ? WebApplicationType.SERVLET : WebApplicationType.NONE); } /** @@ -1153,11 +1112,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); } /** @@ -1165,8 +1122,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<>(); this.initializers.addAll(initializers); } @@ -1225,8 +1181,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); } @@ -1237,8 +1192,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); } @@ -1269,15 +1223,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/StartupInfoLogger.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java index 17c4fc1a1f6..5ab77fb75bc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,7 @@ class StartupInfoLogger { } private String getApplicationName() { - return (this.sourceClass != null) ? ClassUtils.getShortName(this.sourceClass) - : "application"; + return (this.sourceClass != null) ? ClassUtils.getShortName(this.sourceClass) : "application"; } private String getVersion(Class source) { @@ -117,8 +116,7 @@ class StartupInfoLogger { String startedBy = getValue("started by ", () -> System.getProperty("user.name")); String in = getValue("in ", () -> System.getProperty("user.dir")); ApplicationHome home = new ApplicationHome(this.sourceClass); - String path = (home.getSource() != null) ? home.getSource().getAbsolutePath() - : ""; + String path = (home.getSource() != null) ? home.getSource().getAbsolutePath() : ""; if (startedBy == null && path == null) { return ""; } 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 391bedd4ac9..eaa037af397 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.Assert; * @author Andy Wilkinson * @since 1.3.0 */ -public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContextAware, - EnvironmentAware, InitializingBean, DisposableBean { +public class SpringApplicationAdminMXBeanRegistrar + implements ApplicationContextAware, EnvironmentAware, InitializingBean, DisposableBean { private static final Log logger = LogFactory.getLog(SpringApplicationAdmin.class); @@ -62,14 +62,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; @@ -99,8 +97,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 + "'"); } } @@ -123,8 +120,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 e102a844cc3..e15ef6f4e77 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 20ecc841e3e..d40983a4b3c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,8 +146,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))); } } @@ -208,9 +207,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); @@ -272,8 +270,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; } @@ -377,8 +374,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; } @@ -457,16 +453,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; } @@ -476,8 +469,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; } @@ -510,8 +502,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 96311fbe9e5..9bb0559a622 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"; @@ -113,24 +111,18 @@ 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(); - addWithPrefix(properties, getPropertiesFromApplication(environment), - "vcap.application."); - addWithPrefix(properties, getPropertiesFromServices(environment), - "vcap.services."); + addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application."); + addWithPrefix(properties, getPropertiesFromServices(environment), "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)); } } } @@ -168,15 +160,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") @@ -205,8 +195,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 70b7d16f966..d9d5d8c86cb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); } }, 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 3ef59e85b20..74d36c4d617 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +98,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"; @@ -168,33 +167,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()); } @@ -209,8 +203,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(); } @@ -220,8 +213,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) { @@ -261,8 +253,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; @@ -276,14 +267,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,10 +305,9 @@ public class ConfigFileApplicationListener Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { this.environment = environment; - this.resourceLoader = (resourceLoader != null) ? resourceLoader - : new DefaultResourceLoader(); - this.propertySourceLoaders = SpringFactoriesLoader.loadFactories( - PropertySourceLoader.class, getClass().getClassLoader()); + this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader(); + this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, + getClass().getClassLoader()); } public void load() { @@ -333,13 +321,11 @@ 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); } resetEnvironmentProfiles(this.processedProfiles); - load(null, this::getNegativeProfileFilter, - addToLoaded(MutablePropertySources::addFirst, true)); + load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true)); addLoadedPropertySources(); } @@ -379,8 +365,7 @@ public class ConfigFileApplicationListener private List getOtherActiveProfiles(Set activatedViaProperty) { return Arrays.stream(this.environment.getActiveProfiles()).map(Profile::new) - .filter((profile) -> !activatedViaProperty.contains(profile)) - .collect(Collectors.toList()); + .filter((profile) -> !activatedViaProperty.contains(profile)).collect(Collectors.toList()); } void addActiveProfiles(Set profiles) { @@ -389,23 +374,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) { @@ -413,20 +395,17 @@ public class ConfigFileApplicationListener if (profile == null) { return ObjectUtils.isEmpty(document.getProfiles()); } - return ObjectUtils.containsElement(document.getProfiles(), - profile.getName()) + return ObjectUtils.containsElement(document.getProfiles(), profile.getName()) && this.environment.acceptsProfiles(document.getProfiles()); }; } private DocumentFilter getNegativeProfileFilter(Profile profile) { - return (Document document) -> (profile == null - && !ObjectUtils.isEmpty(document.getProfiles()) + return (Document document) -> (profile == null && !ObjectUtils.isEmpty(document.getProfiles()) && this.environment.acceptsProfiles(document.getProfiles())); } - private DocumentConsumer addToLoaded( - BiConsumer> addMethod, + private DocumentConsumer addToLoaded(BiConsumer> addMethod, boolean checkForExisting) { return (profile, document) -> { if (checkForExisting) { @@ -442,23 +421,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; } } @@ -467,8 +443,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); } } } @@ -476,13 +452,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) { @@ -493,8 +467,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); } } @@ -503,22 +476,20 @@ 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()) { - this.logger.trace("Skipped missing config " - + getDescription(location, resource, profile)); + this.logger.trace("Skipped missing config " + getDescription(location, resource, profile)); } return; } - if (!StringUtils.hasText( - StringUtils.getFilenameExtension(resource.getFilename()))) { + if (!StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename()))) { if (this.logger.isTraceEnabled()) { - this.logger.trace("Skipped empty config extension " - + getDescription(location, resource, profile)); + this.logger + .trace("Skipped empty config extension " + getDescription(location, resource, profile)); } return; } @@ -526,8 +497,7 @@ public class ConfigFileApplicationListener List documents = loadDocuments(loader, name, resource); if (CollectionUtils.isEmpty(documents)) { if (this.logger.isTraceEnabled()) { - this.logger.trace("Skipped unloaded config " - + getDescription(location, resource, profile)); + this.logger.trace("Skipped unloaded config " + getDescription(location, resource, profile)); } return; } @@ -543,14 +513,13 @@ public class ConfigFileApplicationListener if (!loaded.isEmpty()) { loaded.forEach((document) -> consumer.accept(profile, document)); if (this.logger.isDebugEnabled()) { - this.logger.debug("Loaded config file " - + getDescription(location, resource, profile)); + this.logger.debug("Loaded config file " + getDescription(location, resource, profile)); } } } 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); } } @@ -562,8 +531,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) { @@ -579,22 +548,17 @@ 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), new PropertySourcesPlaceholdersResolver(this.environment)); return new Document(propertySource, - binder.bind("spring.profiles", Bindable.of(String[].class)) - .orElse(null), - getProfiles(binder, ACTIVE_PROFILES_PROPERTY), - getProfiles(binder, INCLUDE_PROFILES_PROPERTY)); + binder.bind("spring.profiles", Bindable.of(String[].class)).orElse(null), + getProfiles(binder, ACTIVE_PROFILES_PROPERTY), getProfiles(binder, INCLUDE_PROFILES_PROPERTY)); }).collect(Collectors.toList()); } - private String getDescription(String location, Resource resource, - Profile profile) { + private String getDescription(String location, Resource resource, Profile profile) { String description = getDescription(location, resource); - return (profile != null) ? description + " for profile " + profile - : description; + return (profile != null) ? description + " for profile " + profile : description; } private String getDescription(String location, Resource resource) { @@ -610,8 +574,7 @@ public class ConfigFileApplicationListener } private Set getProfiles(Binder binder, String name) { - return binder.bind(name, String[].class).map(this::asProfileSet) - .orElse(Collections.emptySet()); + return binder.bind(name, String[].class).map(this::asProfileSet).orElse(Collections.emptySet()); } private Set asProfileSet(String[] profileNames) { @@ -635,19 +598,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)) { @@ -669,9 +629,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); } @@ -683,8 +642,8 @@ public class ConfigFileApplicationListener */ private void resetEnvironmentProfiles(List processedProfiles) { String[] names = processedProfiles.stream() - .filter((profile) -> profile != null && !profile.isDefaultProfile()) - .map(Profile::getName).toArray(String[]::new); + .filter((profile) -> profile != null && !profile.isDefaultProfile()).map(Profile::getName) + .toArray(String[]::new); this.environment.setActiveProfiles(names); } @@ -704,8 +663,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); @@ -794,8 +753,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 @@ -818,8 +776,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/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 880cda13dd5..37cb1d09cc2 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. @@ -65,14 +65,13 @@ 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 @@ -88,26 +87,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 470647b7ca0..101c5ff32a0 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 fbd60d4b744..4b2a691c65c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.StringUtils; */ public class LoggingApplicationListener implements GenericApplicationListener { - 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); /** * The default order for the LoggingApplicationListener. @@ -127,11 +126,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 final Log logger = LogFactory.getLog(getClass()); @@ -170,14 +168,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) { @@ -186,23 +183,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); } @@ -226,8 +219,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) { @@ -255,10 +247,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); @@ -270,8 +260,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); } @@ -282,8 +272,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); } @@ -325,14 +314,11 @@ public class LoggingApplicationListener implements GenericApplicationListener { return LogLevel.valueOf(level.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 8bae0bcc68f..db64562988b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ConfigurationBeanFactoryMetadata implements BeanFactoryPostProcesso /** * 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 ConfigurableListableBeanFactory beanFactory; private final Map beansFactoryMetadata = new HashMap<>(); @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; for (String name : beanFactory.getBeanDefinitionNames()) { BeanDefinition definition = beanFactory.getBeanDefinition(name); @@ -63,8 +61,7 @@ public class ConfigurationBeanFactoryMetadata implements BeanFactoryPostProcesso } } - public Map getBeansWithFactoryAnnotation( - Class type) { + public Map getBeansWithFactoryAnnotation(Class type) { Map result = new HashMap<>(); for (String name : this.beansFactoryMetadata.keySet()) { if (findFactoryAnnotation(name, type) != null) { @@ -74,8 +71,7 @@ public class ConfigurationBeanFactoryMetadata implements BeanFactoryPostProcesso 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; } 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 d09a3551796..e61ba4a0633 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ConfigurationPropertiesBindException extends BeanCreationException private final ConfigurationProperties annotation; - ConfigurationPropertiesBindException(String beanName, Object bean, - ConfigurationProperties annotation, Exception cause) { + ConfigurationPropertiesBindException(String beanName, Object bean, ConfigurationProperties annotation, + Exception cause) { super(beanName, getMessage(bean, annotation), cause); this.beanType = bean.getClass(); this.annotation = annotation; @@ -58,8 +58,7 @@ public class ConfigurationPropertiesBindException extends BeanCreationException private static String getMessage(Object bean, ConfigurationProperties annotation) { StringBuilder message = new StringBuilder(); - message.append("Could not bind properties to '" - + ClassUtils.getShortName(bean.getClass()) + "' : "); + message.append("Could not bind properties to '" + ClassUtils.getShortName(bean.getClass()) + "' : "); message.append("prefix=").append(annotation.prefix()); message.append(", ignoreInvalidFields=").append(annotation.ignoreInvalidFields()); message.append(", ignoreUnknownFields=").append(annotation.ignoreUnknownFields()); 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 a91d86fa034..c922a257a13 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,29 +61,24 @@ class ConfigurationPropertiesBinder { private volatile Binder binder; - ConfigurationPropertiesBinder(ApplicationContext applicationContext, - String validatorBeanName) { + ConfigurationPropertiesBinder(ApplicationContext applicationContext, String validatorBeanName) { this.applicationContext = applicationContext; - this.propertySources = new PropertySourcesDeducer(applicationContext) - .getPropertySources(); - this.configurationPropertiesValidator = getConfigurationPropertiesValidator( - applicationContext, validatorBeanName); - this.jsr303Present = ConfigurationPropertiesJsr303Validator - .isJsr303Present(applicationContext); + this.propertySources = new PropertySourcesDeducer(applicationContext).getPropertySources(); + this.configurationPropertiesValidator = getConfigurationPropertiesValidator(applicationContext, + validatorBeanName); + this.jsr303Present = ConfigurationPropertiesJsr303Validator.isJsr303Present(applicationContext); } public void 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); 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); } @@ -106,14 +101,12 @@ class ConfigurationPropertiesBinder { 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); @@ -123,17 +116,15 @@ class ConfigurationPropertiesBinder { 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])); } return handler; } 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; } @@ -147,14 +138,12 @@ class ConfigurationPropertiesBinder { } 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 46df6b009c1..b6a43dc5f89 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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. @@ -63,8 +62,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; } @@ -72,11 +70,10 @@ 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 = new ConfigurationPropertiesBinder( - this.applicationContext, VALIDATOR_BEAN_NAME); + this.configurationPropertiesBinder = new ConfigurationPropertiesBinder(this.applicationContext, + VALIDATOR_BEAN_NAME); } @Override @@ -85,10 +82,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) { bind(bean, beanName, annotation); } @@ -98,17 +93,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, annotation, - ex); + throw new ConfigurationPropertiesBindException(beanName, bean, annotation, ex); } } @@ -120,8 +112,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 b523b8efede..6e1a12b94e2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,36 +29,29 @@ import org.springframework.core.type.AnnotationMetadata; * @author Dave Syer * @author Phillip Webb */ -public class ConfigurationPropertiesBindingPostProcessorRegistrar - implements ImportBeanDefinitionRegistrar { +public class ConfigurationPropertiesBindingPostProcessorRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { - if (!registry.containsBeanDefinition( - ConfigurationPropertiesBindingPostProcessor.BEAN_NAME)) { + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + if (!registry.containsBeanDefinition(ConfigurationPropertiesBindingPostProcessor.BEAN_NAME)) { registerConfigurationPropertiesBindingPostProcessor(registry); registerConfigurationBeanFactoryMetadata(registry); } } - 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/ConversionServiceDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java index 4e66ce62fc7..b25ce349c80 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. @@ -44,13 +44,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 this.applicationContext.getAutowireCapableBeanFactory() - .createBean(Factory.class).create(); + return this.applicationContext.getAutowireCapableBeanFactory().createBean(Factory.class).create(); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java index fa9f7c18308..e15f5081419 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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; */ class EnableConfigurationPropertiesImportSelector implements ImportSelector { - private static final String[] IMPORTS = { - ConfigurationPropertiesBeanRegistrar.class.getName(), + private static final String[] IMPORTS = { ConfigurationPropertiesBeanRegistrar.class.getName(), ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() }; @Override @@ -61,32 +60,26 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { /** * {@link ImportBeanDefinitionRegistrar} for configuration properties support. */ - public static class ConfigurationPropertiesBeanRegistrar - implements ImportBeanDefinitionRegistrar { + public static class ConfigurationPropertiesBeanRegistrar implements ImportBeanDefinitionRegistrar { @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { - getTypes(metadata).forEach((type) -> register(registry, - (ConfigurableListableBeanFactory) registry, type)); + public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { + getTypes(metadata).forEach((type) -> register(registry, (ConfigurableListableBeanFactory) registry, type)); } private List> getTypes(AnnotationMetadata metadata) { MultiValueMap attributes = metadata - .getAllAnnotationAttributes( - EnableConfigurationProperties.class.getName(), false); - return collectClasses((attributes != null) ? attributes.get("value") - : Collections.emptyList()); + .getAllAnnotationAttributes(EnableConfigurationProperties.class.getName(), false); + return collectClasses((attributes != null) ? attributes.get("value") : Collections.emptyList()); } private List> collectClasses(List values) { - return values.stream().flatMap((value) -> Arrays.stream((Object[]) value)) - .map((o) -> (Class) o).filter((type) -> void.class != type) - .collect(Collectors.toList()); + return values.stream().flatMap((value) -> Arrays.stream((Object[]) value)).map((o) -> (Class) o) + .filter((type) -> void.class != type).collect(Collectors.toList()); } - private void register(BeanDefinitionRegistry registry, - ConfigurableListableBeanFactory beanFactory, Class type) { + private void register(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory, + Class type) { String name = getName(type); if (!containsBeanDefinition(beanFactory, name)) { registerBeanDefinition(registry, name, type); @@ -94,28 +87,23 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { } private String getName(Class type) { - ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type, - ConfigurationProperties.class); + ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type, ConfigurationProperties.class); String prefix = (annotation != null) ? annotation.prefix() : ""; - return (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() - : type.getName()); + return (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() : type.getName()); } - private boolean containsBeanDefinition( - ConfigurableListableBeanFactory beanFactory, String name) { + private boolean containsBeanDefinition(ConfigurableListableBeanFactory beanFactory, String name) { if (beanFactory.containsBeanDefinition(name)) { return true; } BeanFactory parent = beanFactory.getParentBeanFactory(); if (parent instanceof ConfigurableListableBeanFactory) { - return containsBeanDefinition((ConfigurableListableBeanFactory) parent, - name); + return containsBeanDefinition((ConfigurableListableBeanFactory) parent, name); } return false; } - private void registerBeanDefinition(BeanDefinitionRegistry registry, String name, - Class type) { + private void registerBeanDefinition(BeanDefinitionRegistry registry, String name, Class type) { assertHasAnnotation(type); GenericBeanDefinition definition = new GenericBeanDefinition(); definition.setBeanClass(type); @@ -123,10 +111,9 @@ class EnableConfigurationPropertiesImportSelector implements ImportSelector { } private void assertHasAnnotation(Class type) { - Assert.notNull( - AnnotationUtils.findAnnotation(type, ConfigurationProperties.class), - () -> "No " + ConfigurationProperties.class.getSimpleName() - + " annotation found on '" + type.getName() + "'."); + Assert.notNull(AnnotationUtils.findAnnotation(type, ConfigurationProperties.class), + () -> "No " + ConfigurationProperties.class.getSimpleName() + " annotation found on '" + + type.getName() + "'."); } } 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 44c103b0735..1186ff01793 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. @@ -217,8 +217,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 8865f3830a7..cb62ad6b5ff 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 boolean onStart(ConfigurationPropertyName name, Bindable target, - BindContext context) { + public boolean 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 c298ff28698..20bf8ad6af4 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 39ec83df3b5..3da62b67986 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 BeanPropertyName { char[] chars = name.replace("_", "-").toCharArray(); for (int i = start; i < chars.length; i++) { char ch = chars[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 c7cae4d23c3..7e31438cfed 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. @@ -58,16 +58,14 @@ class BindConverter { private final ConversionService conversionService; - BindConverter(ConversionService conversionService, - Consumer propertyEditorInitializer) { + 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)); @@ -78,8 +76,7 @@ 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)); } @@ -102,8 +99,7 @@ class BindConverter { */ private static class ResolvableTypeDescriptor extends TypeDescriptor { - ResolvableTypeDescriptor(ResolvableType resolvableType, - Annotation[] annotations) { + ResolvableTypeDescriptor(ResolvableType resolvableType, Annotation[] annotations) { super(resolvableType, null, annotations); } @@ -123,8 +119,7 @@ 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)); } @@ -142,13 +137,11 @@ 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); @@ -159,8 +152,7 @@ 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); } } @@ -177,8 +169,7 @@ 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); @@ -189,8 +180,7 @@ 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); @@ -220,16 +210,14 @@ 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) { SimpleTypeConverter typeConverter = this.typeConverter; - 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 8ca549ebf61..9c35aa1aa17 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 interface BindHandler { * @param context the bind context * @return {@code true} if binding should proceed */ - default boolean onStart(ConfigurationPropertyName name, Bindable target, - BindContext context) { + default boolean onStart(ConfigurationPropertyName name, Bindable target, BindContext context) { return true; } @@ -56,8 +55,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; } @@ -72,8 +70,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; } @@ -85,8 +83,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 6c8dd07111c..e726ac81d43 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -111,8 +110,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); } @@ -127,14 +125,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; @@ -201,8 +196,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; @@ -211,15 +205,14 @@ 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 { if (!handler.onStart(name, target, context)) { 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,8 +244,8 @@ 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.streamSources(), name)) { return null; @@ -267,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; } @@ -292,31 +284,25 @@ 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; } - return context.streamSources() - .map((source) -> source.getConfigurationProperty(name)) - .filter(Objects::nonNull).findFirst().orElse(null); + return context.streamSources().map((source) -> source.getConfigurationProperty(name)).filter(Objects::nonNull) + .findFirst().orElse(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); @@ -324,29 +310,26 @@ public class Binder { return result; } - private Object bindBean(ConfigurationPropertyName name, Bindable target, - BindHandler handler, Context context, boolean allowRecursiveBinding) { - if (containsNoDescendantOf(context.streamSources(), name) - || isUnbindableBean(name, target, context)) { + private Object bindBean(ConfigurationPropertyName name, Bindable target, BindHandler handler, Context context, + boolean allowRecursiveBinding) { + if (containsNoDescendantOf(context.streamSources(), name) || isUnbindableBean(name, target, context)) { 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); Class type = target.getType().resolve(Object.class); if (!allowRecursiveBinding && context.hasBoundBean(type)) { return null; } 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) { - if (context.streamSources().anyMatch((s) -> s - .containsDescendantOf(name) == ConfigurationPropertyState.PRESENT)) { + private boolean isUnbindableBean(ConfigurationPropertyName name, Bindable target, Context context) { + if (context.streamSources() + .anyMatch((s) -> s.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT)) { // We know there are properties to bind so we can't bypass anything return false; } @@ -360,8 +343,7 @@ public class Binder { private boolean containsNoDescendantOf(Stream sources, ConfigurationPropertyName name) { - return sources.allMatch( - (s) -> s.containsDescendantOf(name) == ConfigurationPropertyState.ABSENT); + return sources.allMatch((s) -> s.containsDescendantOf(name) == ConfigurationPropertyState.ABSENT); } /** @@ -384,8 +366,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; @@ -394,8 +375,7 @@ public class Binder { private ConfigurationProperty configurationProperty; Context() { - this.converter = new BindConverter(Binder.this.conversionService, - Binder.this.propertyEditorInitializer); + this.converter = new BindConverter(Binder.this.conversionService, Binder.this.propertyEditorInitializer); } private void increaseDepth() { @@ -406,8 +386,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(); } @@ -445,8 +424,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 d3fb0aff203..091c2f992e4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -55,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; @@ -91,8 +89,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/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 5b6b76cf41c..cab572c1873 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JavaBeanBinder implements BeanBinder { @Override public T bind(ConfigurationPropertyName name, Bindable target, Context context, BeanPropertyBinder propertyBinder) { - boolean hasKnownBindableProperties = context.streamSources().anyMatch(( - s) -> s.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT); + boolean hasKnownBindableProperties = context.streamSources() + .anyMatch((s) -> s.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT); Bean bean = Bean.get(target, hasKnownBindableProperties); if (bean == null) { return null; @@ -55,8 +55,7 @@ class JavaBeanBinder implements BeanBinder { return (bound ? beanSupplier.get() : null); } - private boolean bind(BeanPropertyBinder propertyBinder, Bean bean, - BeanSupplier beanSupplier) { + private boolean bind(BeanPropertyBinder propertyBinder, Bean bean, BeanSupplier beanSupplier) { boolean bound = false; for (Map.Entry entry : bean.getProperties().entrySet()) { bound |= bind(beanSupplier, propertyBinder, entry.getValue()); @@ -64,8 +63,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); @@ -79,8 +77,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; } @@ -120,8 +117,7 @@ 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()); } @@ -134,13 +130,10 @@ class JavaBeanBinder implements BeanBinder { private void addMethodIfPossible(Method method, String prefix, int parameterCount, BiConsumer consumer) { - if (method.getParameterCount() == parameterCount - && method.getName().startsWith(prefix) + if (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); } } @@ -277,12 +270,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() { @@ -304,8 +295,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); } }; } @@ -320,8 +310,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 f907570bcfe..1c54b93f23f 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. @@ -40,8 +40,7 @@ import org.springframework.util.ClassUtils; */ 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); @@ -55,17 +54,16 @@ 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 = getContext().streamSources().anyMatch((source) -> source - .containsDescendantOf(name) == ConfigurationPropertyState.PRESENT); + boolean hasDescendants = getContext().streamSources() + .anyMatch((source) -> source.containsDescendantOf(name) == ConfigurationPropertyState.PRESENT); 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); } @@ -83,8 +81,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; @@ -137,8 +134,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(); @@ -146,16 +142,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)); } } } @@ -173,15 +166,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++) { @@ -196,8 +187,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); String packageName = ClassUtils.getPackageName(resolved); if (!packageName.startsWith("java.lang") && !resolved.isEnum()) { @@ -214,8 +204,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 4f1ab5e123b..13a1356f937 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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,23 +84,20 @@ 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) { return name.isAncestorOf(candidate) && !this.boundNames.contains(candidate); } 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 87cf907e7b2..18de7b4370d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 BindValidationException extends RuntimeException { StringBuilder message = new StringBuilder("Binding validation errors"); if (errors != null) { message.append(" on " + 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 5b18fa46caa..146bdd6475c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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,8 +66,8 @@ 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); if (context.getDepth() == 0 && !this.exceptions.isEmpty()) { throw this.exceptions.pop(); @@ -76,15 +75,13 @@ public class ValidationBindHandler extends AbstractBindHandler { super.onFinish(name, target, context, 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(); validate(name, validationTarget, validationType); } - private Object getValidationTarget(Bindable target, BindContext context, - Object result) { + private Object getValidationTarget(Bindable target, BindContext context, Object result) { if (result != null) { return result; } @@ -105,13 +102,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 742cbcfbe54..204ad0e1c79 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +50,14 @@ import org.springframework.util.ObjectUtils; * @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( - new String[0]); + public static final ConfigurationPropertyName EMPTY = new ConfigurationPropertyName(new String[0]); private final CharSequence[] elements; @@ -73,8 +71,7 @@ public final class ConfigurationPropertyName this(elements, new CharSequence[elements.length]); } - private ConfigurationPropertyName(CharSequence[] elements, - CharSequence[] uniformElements) { + private ConfigurationPropertyName(CharSequence[] elements, CharSequence[] uniformElements) { this.elements = elements; this.uniformElements = uniformElements; } @@ -111,8 +108,7 @@ public final class ConfigurationPropertyName * @return {@code true} if the element is indexed and numeric */ public boolean isNumericIndex(int elementIndex) { - return isIndexed(elementIndex) - && isNumeric(getElement(elementIndex, Form.ORIGINAL)); + return isIndexed(elementIndex) && isNumeric(getElement(elementIndex, Form.ORIGINAL)); } private boolean isNumeric(CharSequence element) { @@ -155,8 +151,7 @@ public final class ConfigurationPropertyName result = result.subSequence(1, result.length() - 1); } else { - result = cleanupCharSequence(result, (c, i) -> c == '-' || c == '_', - CharProcessor.LOWERCASE); + result = cleanupCharSequence(result, (c, i) -> c == '-' || c == '_', CharProcessor.LOWERCASE); } this.uniformElements[elementIndex] = result; } @@ -182,8 +177,7 @@ public final class ConfigurationPropertyName if (elementValue == null) { return this; } - process(elementValue, '.', (value, start, end, indexed) -> Assert.isTrue( - start == 0, + process(elementValue, '.', (value, start, end, indexed) -> Assert.isTrue(start == 0, () -> "Element value '" + elementValue + "' must be a single item")); if (!isIndexed(elementValue)) { InvalidConfigurationPropertyNameException.throwIfHasInvalidChars(elementValue, @@ -374,8 +368,7 @@ public final class ConfigurationPropertyName boolean indexed = isIndexed(element); int offset = indexed ? 1 : 0; for (int i = 0 + offset; i < element.length() - offset; i++) { - char ch = (indexed ? element.charAt(i) - : Character.toLowerCase(element.charAt(i))); + char ch = (indexed ? element.charAt(i) : Character.toLowerCase(element.charAt(i))); hash = (ch == '-' || ch == '_') ? hash : 31 * hash + Character.hashCode(ch); } return hash; @@ -444,10 +437,8 @@ public final class ConfigurationPropertyName */ public static ConfigurationPropertyName of(CharSequence name) { Assert.notNull(name, "Name must not be null"); - if (name.length() >= 1 - && (name.charAt(0) == '.' || name.charAt(name.length() - 1) == '.')) { - throw new InvalidConfigurationPropertyNameException(name, - Collections.singletonList('.')); + if (name.length() >= 1 && (name.charAt(0) == '.' || name.charAt(name.length() - 1) == '.')) { + throw new InvalidConfigurationPropertyNameException(name, Collections.singletonList('.')); } if (name.length() == 0) { return EMPTY; @@ -501,8 +492,7 @@ public final class ConfigurationPropertyName elementValue = elementValueProcessor.apply(elementValue); if (!isIndexed(elementValue)) { elementValue = cleanupCharSequence(elementValue, - (ch, index) -> ch != '_' && !ElementValidator - .isValidChar(Character.toLowerCase(ch), index), + (ch, index) -> ch != '_' && !ElementValidator.isValidChar(Character.toLowerCase(ch), index), CharProcessor.NONE); } if (elementValue.length() > 0) { @@ -512,8 +502,7 @@ public final class ConfigurationPropertyName return new ConfigurationPropertyName(elements.toArray(new CharSequence[0])); } - private static void process(CharSequence name, char separator, - ElementProcessor processor) { + private static void process(CharSequence name, char separator, ElementProcessor processor) { int start = 0; boolean indexed = false; int length = name.length(); @@ -544,15 +533,14 @@ public final class ConfigurationPropertyName processElement(processor, name, start, length, false); } - private static void processElement(ElementProcessor processor, CharSequence name, - int start, int end, boolean indexed) { + private static void processElement(ElementProcessor processor, CharSequence name, int start, int end, + boolean indexed) { if ((end - start) >= 1) { processor.process(name.subSequence(start, end), start, end, indexed); } } - private static CharSequence cleanupCharSequence(CharSequence name, CharFilter filter, - CharProcessor processor) { + private static CharSequence cleanupCharSequence(CharSequence name, CharFilter filter, CharProcessor processor) { for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); char processed = processor.process(ch, i); @@ -643,8 +631,7 @@ public final class ConfigurationPropertyName private boolean valid = true; @Override - public void process(CharSequence elementValue, int start, int end, - boolean indexed) { + public void process(CharSequence elementValue, int start, int end, boolean indexed) { if (this.valid && !indexed) { this.valid = isValidElement(elementValue); } 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 3491ab429a3..57ea4028559 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 ee1fb611b18..79525f117fa 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,22 +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( - Iterable> sources) { - return StreamSupport.stream(sources.spliterator(), false) - .flatMap(ConfigurationPropertySources::flatten) + private static Stream> streamPropertySources(Iterable> sources) { + return StreamSupport.stream(sources.spliterator(), false).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 78bf0dd2832..d484282fc2e 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); } @@ -61,14 +59,12 @@ class ConfigurationPropertySourcesPropertySource return null; } - 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 8c4dfa6fd2e..733d541b419 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 InvalidConfigurationPropertyValueException extends RuntimeException * Starts with an upper-case and ends with a dots. 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 e77c72833d4..a46af92810d 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. @@ -55,8 +55,7 @@ import org.springframework.util.Assert; */ class SpringConfigurationPropertySource implements ConfigurationPropertySource { - private static final ConfigurationPropertyName RANDOM = ConfigurationPropertyName - .of("random"); + private static final ConfigurationPropertyName RANDOM = ConfigurationPropertyName.of("random"); private final PropertySource propertySource; @@ -71,28 +70,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); } @@ -101,8 +96,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); @@ -120,8 +114,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); } @@ -150,16 +143,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); } @@ -169,8 +159,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) { @@ -188,8 +177,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; @@ -203,8 +191,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; } @@ -224,8 +211,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { } @Override - public PropertyMapping[] map( - ConfigurationPropertyName configurationPropertyName) { + public PropertyMapping[] map(ConfigurationPropertyName configurationPropertyName) { return callMappers((mapper) -> mapper.map(configurationPropertyName)); } @@ -234,8 +220,7 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { return callMappers((mapper) -> mapper.map(propertySourceName)); } - private PropertyMapping[] callMappers( - Function function) { + private PropertyMapping[] callMappers(Function function) { List mappings = new ArrayList<>(); for (PropertyMapper mapper : this.mappers) { try { 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 fb82b6877b9..8088b9e668b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringIterableConfigurationPropertySource extends SpringConfigurationPrope private volatile Cache cache; - SpringIterableConfigurationPropertySource(EnumerablePropertySource propertySource, - PropertyMapper mapper) { + SpringIterableConfigurationPropertySource(EnumerablePropertySource propertySource, PropertyMapper mapper) { super(propertySource, mapper, null); assertEnumerablePropertySource(); } @@ -60,17 +59,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); } @@ -88,8 +84,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope } @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/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 59eb56ab555..344f322e1a5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ArrayToDelimitedStringConverter implements ConditionalGenericConvert @Override @Nullable - public Object convert(@Nullable Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(@Nullable 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 2817a06c031..415c0da7bc3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,39 +48,34 @@ 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 @Nullable - public Object convert(@Nullable Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(@Nullable 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 a68b2aae1e2..425b84cf153 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,46 +51,40 @@ 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 @Nullable - public Object convert(@Nullable Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(@Nullable 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/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/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/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/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 31dd9e42f7a..ebb0c9f6774 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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; * @author Stephane Nicoll */ class InvalidConfigurationPropertyValueFailureAnalyzer - extends AbstractFailureAnalyzer - implements EnvironmentAware { + extends AbstractFailureAnalyzer implements EnvironmentAware { private ConfigurableEnvironment environment; @@ -53,8 +52,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; @@ -67,35 +65,29 @@ 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() { - Iterable> sources = (this.environment != null) - ? this.environment.getPropertySources() : Collections.emptyList(); + Iterable> sources = (this.environment != null) ? this.environment.getPropertySources() + : Collections.emptyList(); return StreamSupport.stream(sources.spliterator(), false) - .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 '" + mainDescriptor.getValue() - + "' for configuration property '" + cause.getName() + "'"); + message.append("Invalid value '" + mainDescriptor.getValue() + "' for configuration property '" + + cause.getName() + "'"); 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 +95,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 '" + other.getPropertySource() + "'"); message.append(" with the value '" + other.getValue() + "'"); 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 7ab3356fd86..931d5b67412 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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.print("An attempt was made to call the method "); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java index cb70d23a22e..eb9c7f22edf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 Andy Wilkinson */ -class NoUniqueBeanDefinitionFailureAnalyzer - extends AbstractInjectionFailureAnalyzer +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().indexOf("but found") > -1) { - 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 767e06c3b39..636818d36db 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. @@ -32,8 +32,7 @@ import org.springframework.core.env.MapPropertySource; * @since 2.0.0 * @see OriginTrackedValue */ -public final class OriginTrackedMapPropertySource extends MapPropertySource - implements OriginLookup { +public final class OriginTrackedMapPropertySource extends MapPropertySource implements OriginLookup { @SuppressWarnings({ "unchecked", "rawtypes" }) public OriginTrackedMapPropertySource(String name, Map source) { 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 aa81f0de1ee..7317d9f43f9 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.getStyle()); + super(node.getTag(), node.getValue(), node.getStartMark(), node.getEndMark(), node.getStyle()); } 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 178a966adde..0b5508743ef 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,12 @@ 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, properties)); + return Collections.singletonList(new OriginTrackedMapPropertySource(name, properties)); } @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 1575d77b85a..fd017b604bd 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. @@ -53,8 +53,7 @@ import org.springframework.web.context.support.StandardServletEnvironment; * @author Madhura Bhave * @since 1.3.0 */ -public class SpringApplicationJsonEnvironmentPostProcessor - implements EnvironmentPostProcessor, Ordered { +public class SpringApplicationJsonEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { /** * Name of the {@code spring.application.json} property. @@ -74,8 +73,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor */ public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 5; - private static final Log logger = LogFactory - .getLog(SpringApplicationJsonEnvironmentPostProcessor.class); + private static final Log logger = LogFactory.getLog(SpringApplicationJsonEnvironmentPostProcessor.class); private int order = DEFAULT_ORDER; @@ -89,27 +87,22 @@ public class SpringApplicationJsonEnvironmentPostProcessor } @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, - SpringApplication application) { + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources propertySources = environment.getPropertySources(); - StreamSupport.stream(propertySources.spliterator(), false) - .map(JsonPropertyValue::get).filter(Objects::nonNull).findFirst() - .ifPresent((v) -> processJson(environment, v)); + StreamSupport.stream(propertySources.spliterator(), false).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) { try { 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))); } } catch (Exception ex) { - logger.warn("Cannot parse JSON for spring.application.json: " - + propertyValue.getJson(), ex); + logger.warn("Cannot parse JSON for spring.application.json: " + propertyValue.getJson(), ex); } } @@ -124,8 +117,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)); } @@ -147,8 +139,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)) { @@ -160,16 +151,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; @@ -196,8 +186,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; @@ -214,10 +203,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 d49776a683e..3d3c074663e 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()) { @@ -54,8 +53,7 @@ public class YamlPropertySourceLoader implements PropertySourceLoader { List> propertySources = new ArrayList<>(loaded.size()); for (int i = 0; i < loaded.size(); i++) { String documentNumber = (loaded.size() != 1) ? " (document #" + i + ")" : ""; - propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber, - loaded.get(i))); + propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber, loaded.get(i))); } return propertySources; } 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 f5739a6a3b5..153e651ef22 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -79,9 +77,8 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar addDeserializerWithDeducedType((JsonDeserializer) bean); } for (Class innerClass : bean.getClass().getDeclaredClasses()) { - if (!Modifier.isAbstract(innerClass.getModifiers()) - && (JsonSerializer.class.isAssignableFrom(innerClass) - || JsonDeserializer.class.isAssignableFrom(innerClass))) { + if (!Modifier.isAbstract(innerClass.getModifiers()) && (JsonSerializer.class.isAssignableFrom(innerClass) + || JsonDeserializer.class.isAssignableFrom(innerClass))) { try { addJsonBean(innerClass.newInstance()); } @@ -94,15 +91,13 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar @SuppressWarnings({ "unchecked" }) private void addSerializerWithDeducedType(JsonSerializer serializer) { - ResolvableType type = ResolvableType.forClass(JsonSerializer.class, - serializer.getClass()); + ResolvableType type = ResolvableType.forClass(JsonSerializer.class, serializer.getClass()); addSerializer((Class) type.resolveGeneric(), serializer); } @SuppressWarnings({ "unchecked" }) private void addDeserializerWithDeducedType(JsonDeserializer deserializer) { - ResolvableType type = ResolvableType.forClass(JsonDeserializer.class, - deserializer.getClass()); + ResolvableType type = ResolvableType.forClass(JsonDeserializer.class, deserializer.getClass()); addDeserializer((Class) type.resolveGeneric(), deserializer); } 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 d6f0166d738..81a960671c5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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 e8a72622a6e..29e7f2d21e6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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.jdbc.Driver", - "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "/* ping */ SELECT 1"), + MYSQL("MySQL", "com.mysql.jdbc.Driver", "com.mysql.jdbc.jdbc2.optional.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"), /** * jTDS. As it can be used for several databases, there isn't a single product name we @@ -113,8 +108,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); } @@ -123,8 +117,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() { @@ -141,13 +135,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/"); } }, @@ -155,8 +147,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() { @@ -170,8 +161,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"); } }, @@ -183,8 +173,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() { @@ -205,13 +194,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; @@ -266,8 +253,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 d453d0430b4..78342d63f06 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. @@ -38,14 +38,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/json/JsonSimpleJsonParser.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonSimpleJsonParser.java index d20cab1febd..daa9386c602 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonSimpleJsonParser.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonSimpleJsonParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 JsonSimpleJsonParser extends AbstractJsonParser { @Override @SuppressWarnings("unchecked") public Map parseMap(String json) { - return (Map) tryParse(() -> new JSONParser().parse(json), - ParseException.class); + return (Map) tryParse(() -> new JSONParser().parse(json), ParseException.class); } @Override @SuppressWarnings("unchecked") public List parseList(String json) { - return (List) tryParse(() -> new JSONParser().parse(json), - ParseException.class); + return (List) tryParse(() -> new JSONParser().parse(json), ParseException.class); } } 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 e2624a28b69..d413cdda0e0 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/jta/narayana/DataSourceXAResourceRecoveryHelper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java index 05be5ea879d..9c59515ecd4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,11 @@ import org.springframework.util.Assert; * @author Gytis Trikleris * @since 1.4.0 */ -public class DataSourceXAResourceRecoveryHelper - implements XAResourceRecoveryHelper, XAResource { +public class DataSourceXAResourceRecoveryHelper implements XAResourceRecoveryHelper, XAResource { private static final XAResource[] NO_XA_RESOURCES = {}; - private static final Log logger = LogFactory - .getLog(DataSourceXAResourceRecoveryHelper.class); + private static final Log logger = LogFactory.getLog(DataSourceXAResourceRecoveryHelper.class); private final XADataSource xaDataSource; @@ -69,8 +67,7 @@ public class DataSourceXAResourceRecoveryHelper * @param user the database user or {@code null} * @param password the database password or {@code null} */ - public DataSourceXAResourceRecoveryHelper(XADataSource xaDataSource, String user, - String password) { + public DataSourceXAResourceRecoveryHelper(XADataSource xaDataSource, String user, String password) { Assert.notNull(xaDataSource, "XADataSource must not be null"); this.xaDataSource = xaDataSource; this.user = user; @@ -182,8 +179,7 @@ public class DataSourceXAResourceRecoveryHelper } private XAResource getDelegate(boolean required) { - Assert.state(this.delegate != null || !required, - "Connection has not been opened"); + Assert.state(this.delegate != null || !required, "Connection has not been opened"); return this.delegate; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java index f2a4fd48794..408236bb47a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,44 +29,37 @@ import org.springframework.core.Ordered; * @author Gytis Trikleris * @since 1.4.0 */ -public class NarayanaBeanFactoryPostProcessor - implements BeanFactoryPostProcessor, Ordered { +public class NarayanaBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered { private static final String[] NO_BEANS = {}; private static final int ORDER = Ordered.LOWEST_PRECEDENCE; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - String[] transactionManagers = beanFactory - .getBeanNamesForType(TransactionManager.class, true, false); - String[] recoveryManagers = beanFactory - .getBeanNamesForType(NarayanaRecoveryManagerBean.class, true, false); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + String[] transactionManagers = beanFactory.getBeanNamesForType(TransactionManager.class, true, false); + String[] recoveryManagers = beanFactory.getBeanNamesForType(NarayanaRecoveryManagerBean.class, true, false); addBeanDependencies(beanFactory, transactionManagers, "javax.sql.DataSource"); addBeanDependencies(beanFactory, recoveryManagers, "javax.sql.DataSource"); - addBeanDependencies(beanFactory, transactionManagers, - "javax.jms.ConnectionFactory"); + addBeanDependencies(beanFactory, transactionManagers, "javax.jms.ConnectionFactory"); addBeanDependencies(beanFactory, recoveryManagers, "javax.jms.ConnectionFactory"); } - private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, - String[] beanNames, String dependencyType) { + private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, String[] beanNames, + String dependencyType) { for (String beanName : beanNames) { addBeanDependencies(beanFactory, beanName, dependencyType); } } - private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, - String beanName, String dependencyType) { - for (String dependentBeanName : getBeanNamesForType(beanFactory, - dependencyType)) { + private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory, String beanName, + String dependencyType) { + for (String dependentBeanName : getBeanNamesForType(beanFactory, dependencyType)) { beanFactory.registerDependentBean(beanName, 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/narayana/NarayanaConfigurationBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java index 13863f3f340..ad6ed057d68 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +56,10 @@ public class NarayanaConfigurationBean implements InitializingBean { setDefaultTimeout((int) this.properties.getDefaultTimeout().getSeconds()); } if (this.properties.getPeriodicRecoveryPeriod() != null) { - setPeriodicRecoveryPeriod( - (int) this.properties.getPeriodicRecoveryPeriod().getSeconds()); + setPeriodicRecoveryPeriod((int) this.properties.getPeriodicRecoveryPeriod().getSeconds()); } if (this.properties.getRecoveryBackoffPeriod() != null) { - setRecoveryBackoffPeriod( - (int) this.properties.getRecoveryBackoffPeriod().getSeconds()); + setRecoveryBackoffPeriod((int) this.properties.getRecoveryBackoffPeriod().getSeconds()); } setXaResourceOrphanFilters(this.properties.getXaResourceOrphanFilters()); setRecoveryModules(this.properties.getRecoveryModules()); @@ -69,29 +67,23 @@ public class NarayanaConfigurationBean implements InitializingBean { } private boolean isPropertiesFileAvailable() { - return Thread.currentThread().getContextClassLoader() - .getResource(JBOSSTS_PROPERTIES_FILE_NAME) != null; + return Thread.currentThread().getContextClassLoader().getResource(JBOSSTS_PROPERTIES_FILE_NAME) != null; } - private void setNodeIdentifier(String nodeIdentifier) - throws CoreEnvironmentBeanException { + private void setNodeIdentifier(String nodeIdentifier) throws CoreEnvironmentBeanException { getPopulator(CoreEnvironmentBean.class).setNodeIdentifier(nodeIdentifier); } private void setObjectStoreDir(String objectStoreDir) { if (objectStoreDir != null) { - getPopulator(ObjectStoreEnvironmentBean.class) - .setObjectStoreDir(objectStoreDir); - getPopulator(ObjectStoreEnvironmentBean.class, "communicationStore") - .setObjectStoreDir(objectStoreDir); - getPopulator(ObjectStoreEnvironmentBean.class, "stateStore") - .setObjectStoreDir(objectStoreDir); + getPopulator(ObjectStoreEnvironmentBean.class).setObjectStoreDir(objectStoreDir); + getPopulator(ObjectStoreEnvironmentBean.class, "communicationStore").setObjectStoreDir(objectStoreDir); + getPopulator(ObjectStoreEnvironmentBean.class, "stateStore").setObjectStoreDir(objectStoreDir); } } private void setCommitOnePhase(boolean isCommitOnePhase) { - getPopulator(CoordinatorEnvironmentBean.class) - .setCommitOnePhase(isCommitOnePhase); + getPopulator(CoordinatorEnvironmentBean.class).setCommitOnePhase(isCommitOnePhase); } private void setDefaultTimeout(int defaultTimeout) { @@ -99,28 +91,23 @@ public class NarayanaConfigurationBean implements InitializingBean { } private void setPeriodicRecoveryPeriod(int periodicRecoveryPeriod) { - getPopulator(RecoveryEnvironmentBean.class) - .setPeriodicRecoveryPeriod(periodicRecoveryPeriod); + getPopulator(RecoveryEnvironmentBean.class).setPeriodicRecoveryPeriod(periodicRecoveryPeriod); } private void setRecoveryBackoffPeriod(int recoveryBackoffPeriod) { - getPopulator(RecoveryEnvironmentBean.class) - .setRecoveryBackoffPeriod(recoveryBackoffPeriod); + getPopulator(RecoveryEnvironmentBean.class).setRecoveryBackoffPeriod(recoveryBackoffPeriod); } private void setXaResourceOrphanFilters(List xaResourceOrphanFilters) { - getPopulator(JTAEnvironmentBean.class) - .setXaResourceOrphanFilterClassNames(xaResourceOrphanFilters); + getPopulator(JTAEnvironmentBean.class).setXaResourceOrphanFilterClassNames(xaResourceOrphanFilters); } private void setRecoveryModules(List recoveryModules) { - getPopulator(RecoveryEnvironmentBean.class) - .setRecoveryModuleClassNames(recoveryModules); + getPopulator(RecoveryEnvironmentBean.class).setRecoveryModuleClassNames(recoveryModules); } private void setExpiryScanners(List expiryScanners) { - getPopulator(RecoveryEnvironmentBean.class) - .setExpiryScannerClassNames(expiryScanners); + getPopulator(RecoveryEnvironmentBean.class).setExpiryScannerClassNames(expiryScanners); } private T getPopulator(Class beanClass) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java index 8c78362602f..a64c01bf152 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 NarayanaDataSourceBean implements DataSource { } @Override - public Connection getConnection(String username, String password) - throws SQLException { + public Connection getConnection(String username, String password) throws SQLException { Properties properties = new Properties(); properties.put(TransactionalDriver.XADataSource, this.xaDataSource); properties.put(TransactionalDriver.userName, username); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java index cf140cc1aa8..659a0c3c405 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,22 +99,22 @@ public class NarayanaProperties { /** * Comma-separated list of orphan filters. */ - private List xaResourceOrphanFilters = new ArrayList<>(Arrays.asList( - "com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", - "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter")); + private List xaResourceOrphanFilters = new ArrayList<>( + Arrays.asList("com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", + "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter")); /** * Comma-separated list of recovery modules. */ - private List recoveryModules = new ArrayList<>(Arrays.asList( - "com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", - "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule")); + private List recoveryModules = new ArrayList<>( + Arrays.asList("com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", + "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule")); /** * Comma-separated list of expiry scanners. */ - private List expiryScanners = new ArrayList<>(Collections.singletonList( - "com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner")); + private List expiryScanners = new ArrayList<>(Collections + .singletonList("com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner")); public String getLogDir() { return this.logDir; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java index d09a1c030f1..2275ab19ecc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaRecoveryManagerBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 class NarayanaRecoveryManagerBean implements InitializingBean, Disposable this.recoveryManagerService.destroy(); } - void registerXAResourceRecoveryHelper( - XAResourceRecoveryHelper xaResourceRecoveryHelper) { + void registerXAResourceRecoveryHelper(XAResourceRecoveryHelper xaResourceRecoveryHelper) { getXARecoveryModule().addXAResourceRecoveryHelper(xaResourceRecoveryHelper); } private XARecoveryModule getXARecoveryModule() { - XARecoveryModule xaRecoveryModule = XARecoveryModule - .getRegisteredXARecoveryModule(); + XARecoveryModule xaRecoveryModule = XARecoveryModule.getRegisteredXARecoveryModule(); if (xaRecoveryModule != null) { return xaRecoveryModule; } - throw new IllegalStateException( - "XARecoveryModule is not registered with recovery manager"); + throw new IllegalStateException("XARecoveryModule is not registered with recovery manager"); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java index 70f9d066f94..fd03d30a817 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,17 @@ public class NarayanaXAConnectionFactoryWrapper implements XAConnectionFactoryWr } @Override - public ConnectionFactory wrapConnectionFactory( - XAConnectionFactory xaConnectionFactory) { + public ConnectionFactory wrapConnectionFactory(XAConnectionFactory xaConnectionFactory) { XAResourceRecoveryHelper recoveryHelper = getRecoveryHelper(xaConnectionFactory); this.recoveryManager.registerXAResourceRecoveryHelper(recoveryHelper); - return new ConnectionFactoryProxy(xaConnectionFactory, - new TransactionHelperImpl(this.transactionManager)); + return new ConnectionFactoryProxy(xaConnectionFactory, new TransactionHelperImpl(this.transactionManager)); } - private XAResourceRecoveryHelper getRecoveryHelper( - XAConnectionFactory xaConnectionFactory) { - if (this.properties.getRecoveryJmsUser() == null - && this.properties.getRecoveryJmsPass() == null) { + private XAResourceRecoveryHelper getRecoveryHelper(XAConnectionFactory xaConnectionFactory) { + if (this.properties.getRecoveryJmsUser() == null && this.properties.getRecoveryJmsPass() == null) { return new JmsXAResourceRecoveryHelper(xaConnectionFactory); } - return new JmsXAResourceRecoveryHelper(xaConnectionFactory, - this.properties.getRecoveryJmsUser(), + return new JmsXAResourceRecoveryHelper(xaConnectionFactory, this.properties.getRecoveryJmsUser(), this.properties.getRecoveryJmsPass()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java index c88bf144d99..c45a35dac2b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 NarayanaXADataSourceWrapper implements XADataSourceWrapper { * @param recoveryManager the underlying recovery manager * @param properties the Narayana properties */ - public NarayanaXADataSourceWrapper(NarayanaRecoveryManagerBean recoveryManager, - NarayanaProperties properties) { + public NarayanaXADataSourceWrapper(NarayanaRecoveryManagerBean recoveryManager, NarayanaProperties properties) { Assert.notNull(recoveryManager, "RecoveryManager must not be null"); Assert.notNull(properties, "Properties must not be null"); this.recoveryManager = recoveryManager; @@ -58,12 +57,11 @@ public class NarayanaXADataSourceWrapper implements XADataSourceWrapper { } private XAResourceRecoveryHelper getRecoveryHelper(XADataSource dataSource) { - if (this.properties.getRecoveryDbUser() == null - && this.properties.getRecoveryDbPass() == null) { + if (this.properties.getRecoveryDbUser() == null && this.properties.getRecoveryDbPass() == null) { return new DataSourceXAResourceRecoveryHelper(dataSource); } - return new DataSourceXAResourceRecoveryHelper(dataSource, - this.properties.getRecoveryDbUser(), this.properties.getRecoveryDbPass()); + return new DataSourceXAResourceRecoveryHelper(dataSource, this.properties.getRecoveryDbUser(), + this.properties.getRecoveryDbPass()); } } 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 273c0888344..d751ad0dbe9 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) { @@ -54,8 +52,7 @@ public class LiquibaseServiceLocatorApplicationListener public void replaceServiceLocator() { CustomResolverServiceLocator customResolverServiceLocator = new CustomResolverServiceLocator( new SpringPackageScanClassResolver(logger)); - customResolverServiceLocator.addPackageToScan( - CommonsLoggingLiquibaseLogger.class.getPackage().getName()); + customResolverServiceLocator.addPackageToScan(CommonsLoggingLiquibaseLogger.class.getPackage().getName()); ServiceLocator.setInstance(customResolverServiceLocator); liquibase.logging.LogFactory.reset(); } 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/LogFile.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LogFile.java index 7021d70814e..3ec58397298 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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; } 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 c81efdfd7dc..62d7b6b080c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); @@ -119,17 +118,14 @@ public class LoggingSystemProperties { if (this.environment instanceof ConfigurableEnvironment) { PropertyResolver resolver = new PropertySourcesPropertyResolver( ((ConfigurableEnvironment) this.environment).getPropertySources()); - ((PropertySourcesPropertyResolver) resolver) - .setIgnoreUnresolvableNestedPlaceholders(true); + ((PropertySourcesPropertyResolver) resolver).setIgnoreUnresolvableNestedPlaceholders(true); return resolver; } 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 4e6293f7147..0922f898b2a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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; } @@ -137,8 +134,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; @@ -149,8 +145,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); } @@ -160,8 +155,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); } @@ -175,8 +170,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 83e8dd139bf..629031713f7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,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; } @@ -87,8 +86,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 { @@ -113,8 +111,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); @@ -122,12 +119,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); @@ -137,29 +132,26 @@ 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.setFileNamePattern(logFile + ".%d{yyyy-MM-dd}.%i.gz"); - setMaxFileSize(rollingPolicy, - this.patterns.getProperty("logging.file.max-size", MAX_FILE_SIZE)); - rollingPolicy.setMaxHistory(this.patterns.getProperty("logging.file.max-history", - Integer.class, CoreConstants.UNBOUND_HISTORY)); + setMaxFileSize(rollingPolicy, this.patterns.getProperty("logging.file.max-size", MAX_FILE_SIZE)); + rollingPolicy.setMaxHistory( + this.patterns.getProperty("logging.file.max-history", Integer.class, CoreConstants.UNBOUND_HISTORY)); appender.setRollingPolicy(rollingPolicy); rollingPolicy.setParent(appender); config.start(rollingPolicy); } - private void setMaxFileSize( - SizeAndTimeBasedRollingPolicy rollingPolicy, - String maxFileSize) { + private void setMaxFileSize(SizeAndTimeBasedRollingPolicy rollingPolicy, String maxFileSize) { try { rollingPolicy.setMaxFileSize(FileSize.valueOf(maxFileSize)); } catch (NoSuchMethodError ex) { // Logback < 1.1.8 used String configuration - Method method = ReflectionUtils.findMethod( - SizeAndTimeBasedRollingPolicy.class, "setMaxFileSize", String.class); + Method method = ReflectionUtils.findMethod(SizeAndTimeBasedRollingPolicy.class, "setMaxFileSize", + String.class); ReflectionUtils.invokeMethod(method, rollingPolicy, maxFileSize); } } 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 91b3d2d23e5..0325b03e21c 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 8d1293e8a03..b1b7d342352 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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("configuration/springProperty"), new SpringPropertyAction(environment)); rs.addRule(new ElementSelector("*/springProfile"), new SpringProfileAction(this.initializationContext.getEnvironment())); 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 867c09d2f7b..960602dc9b1 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. @@ -54,8 +54,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; @@ -70,8 +69,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 6e05ae5a553..4005171a98a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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); } @@ -72,8 +70,7 @@ class SpringPropertyAction extends Action { int lastDot = source.lastIndexOf('.'); if (lastDot > 0) { String prefix = source.substring(0, lastDot + 1); - return this.environment.getProperty(prefix + source.substring(lastDot + 1), - defaultValue); + return this.environment.getProperty(prefix + source.substring(lastDot + 1), defaultValue); } return defaultValue; } 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 c329c027adc..6b7ce51f3c7 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. @@ -65,8 +65,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); } @@ -81,9 +81,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); @@ -204,14 +203,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); @@ -220,20 +218,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.callback != null) { - EntityManagerFactoryBuilder.this.callback - .execute(entityManagerFactoryBean); + EntityManagerFactoryBuilder.this.callback.execute(entityManagerFactoryBean); } 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/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/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 419da404f6b..a3a311bbcde 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) { @@ -192,8 +182,7 @@ public final class LambdaSafe { 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); if (message.startsWith(moduleName + "/" + argumentType.getName())) { return true; @@ -204,10 +193,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); @@ -227,13 +215,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; } @@ -257,8 +243,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)); } } @@ -269,13 +254,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; @@ -302,10 +285,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); } } @@ -327,8 +310,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. @@ -337,8 +319,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; } } @@ -350,10 +331,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/RestTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java index cd381da954a..405c7f023cc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 RestTemplateBuilder { 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); } @@ -109,20 +108,16 @@ public class RestTemplateBuilder { this.uriTemplateHandler = null; this.errorHandler = null; this.basicAuthorization = null; - this.restTemplateCustomizers = Collections - .unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); + this.restTemplateCustomizers = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(customizers))); this.requestFactoryCustomizers = Collections.emptySet(); this.interceptors = Collections.emptySet(); } private RestTemplateBuilder(boolean detectRequestFactory, String rootUri, - Set> messageConverters, - Supplier requestFactorySupplier, + Set> messageConverters, Supplier requestFactorySupplier, UriTemplateHandler uriTemplateHandler, ResponseErrorHandler errorHandler, - BasicAuthorizationInterceptor basicAuthorization, - Set restTemplateCustomizers, - Set requestFactoryCustomizers, - Set interceptors) { + BasicAuthorizationInterceptor basicAuthorization, Set restTemplateCustomizers, + Set requestFactoryCustomizers, Set interceptors) { this.detectRequestFactory = detectRequestFactory; this.rootUri = rootUri; this.messageConverters = messageConverters; @@ -143,11 +138,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.basicAuthorization, - this.restTemplateCustomizers, this.requestFactoryCustomizers, - this.interceptors); + return new RestTemplateBuilder(detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -157,11 +150,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.basicAuthorization, - this.restTemplateCustomizers, this.requestFactoryCustomizers, - this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -173,8 +164,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)); } @@ -188,15 +178,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.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + Collections.unmodifiableSet(new LinkedHashSet>(messageConverters)), + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -207,8 +194,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)); } @@ -225,9 +211,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.basicAuthorization, this.restTemplateCustomizers, + append(this.messageConverters, messageConverters), this.requestFactorySupplier, this.uriTemplateHandler, + this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } @@ -240,11 +225,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.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + Collections.unmodifiableSet(new LinkedHashSet<>(new RestTemplate().getMessageConverters())), + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -256,8 +239,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)); } @@ -271,12 +253,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.basicAuthorization, + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, this.requestFactoryCustomizers, Collections.unmodifiableSet(new LinkedHashSet<>(interceptors))); } @@ -289,8 +269,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)); } @@ -303,14 +282,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.basicAuthorization, - this.restTemplateCustomizers, this.requestFactoryCustomizers, - append(this.interceptors, interceptors)); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, append(this.interceptors, interceptors)); } /** @@ -319,14 +295,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); @@ -344,14 +318,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.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, 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.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -362,10 +333,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.basicAuthorization, this.restTemplateCustomizers, - this.requestFactoryCustomizers, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, uriTemplateHandler, this.errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -376,11 +346,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.basicAuthorization, - this.restTemplateCustomizers, this.requestFactoryCustomizers, - this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, errorHandler, this.basicAuthorization, + this.restTemplateCustomizers, this.requestFactoryCustomizers, this.interceptors); } /** @@ -391,12 +359,10 @@ public class RestTemplateBuilder { * @return a new builder instance */ public RestTemplateBuilder basicAuthorization(String username, String password) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, - new BasicAuthorizationInterceptor(username, password), - this.restTemplateCustomizers, this.requestFactoryCustomizers, - this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, + new BasicAuthorizationInterceptor(username, password), this.restTemplateCustomizers, + this.requestFactoryCustomizers, this.interceptors); } /** @@ -408,10 +374,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)); } @@ -424,15 +388,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.basicAuthorization, - 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.basicAuthorization, + Collections.unmodifiableSet(new LinkedHashSet(restTemplateCustomizers)), this.requestFactoryCustomizers, this.interceptors); } @@ -444,10 +404,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)); } @@ -459,14 +417,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.basicAuthorization, - append(this.restTemplateCustomizers, customizers), - this.requestFactoryCustomizers, this.interceptors); + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + append(this.restTemplateCustomizers, customizers), this.requestFactoryCustomizers, this.interceptors); } /** @@ -476,12 +431,10 @@ public class RestTemplateBuilder { * @return a new builder instance. */ public RestTemplateBuilder setConnectTimeout(int connectTimeout) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - append(this.requestFactoryCustomizers, - new ConnectTimeoutRequestFactoryCustomizer(connectTimeout)), + append(this.requestFactoryCustomizers, new ConnectTimeoutRequestFactoryCustomizer(connectTimeout)), this.interceptors); } @@ -492,12 +445,10 @@ public class RestTemplateBuilder { * @return a new builder instance. */ public RestTemplateBuilder setReadTimeout(int readTimeout) { - return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, - this.messageConverters, this.requestFactorySupplier, - this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, + return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri, this.messageConverters, + this.requestFactorySupplier, this.uriTemplateHandler, this.errorHandler, this.basicAuthorization, this.restTemplateCustomizers, - append(this.requestFactoryCustomizers, - new ReadTimeoutRequestFactoryCustomizer(readTimeout)), + append(this.requestFactoryCustomizers, new ReadTimeoutRequestFactoryCustomizer(readTimeout)), this.interceptors); } @@ -568,8 +519,7 @@ public class RestTemplateBuilder { requestFactory = detectRequestFactory(); } if (requestFactory != null) { - ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary( - requestFactory); + ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary(requestFactory); for (RequestFactoryCustomizer customizer : this.requestFactoryCustomizers) { customizer.customize(unwrappedRequestFactory); } @@ -577,32 +527,27 @@ public class RestTemplateBuilder { } } - private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary( - ClientHttpRequestFactory requestFactory) { + private ClientHttpRequestFactory unwrapRequestFactoryIfNecessary(ClientHttpRequestFactory requestFactory) { if (!(requestFactory instanceof AbstractClientHttpRequestFactoryWrapper)) { return requestFactory; } ClientHttpRequestFactory unwrappedRequestFactory = requestFactory; - Field field = ReflectionUtils.findField( - AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); + Field field = ReflectionUtils.findField(AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"); ReflectionUtils.makeAccessible(field); do { - unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils - .getField(field, unwrappedRequestFactory); + unwrappedRequestFactory = (ClientHttpRequestFactory) ReflectionUtils.getField(field, + unwrappedRequestFactory); } while (unwrappedRequestFactory instanceof AbstractClientHttpRequestFactoryWrapper); return unwrappedRequestFactory; } private ClientHttpRequestFactory detectRequestFactory() { - 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(); @@ -632,8 +577,7 @@ public class RestTemplateBuilder { /** * {@link RequestFactoryCustomizer} to call a "set timeout" method. */ - private abstract static class TimeoutRequestFactoryCustomizer - implements RequestFactoryCustomizer { + private abstract static class TimeoutRequestFactoryCustomizer implements RequestFactoryCustomizer { private final int timeout; @@ -650,13 +594,12 @@ public class RestTemplateBuilder { } 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"); } } @@ -664,8 +607,7 @@ public class RestTemplateBuilder { /** * {@link RequestFactoryCustomizer} to set the read timeout. */ - private static class ReadTimeoutRequestFactoryCustomizer - extends TimeoutRequestFactoryCustomizer { + private static class ReadTimeoutRequestFactoryCustomizer extends TimeoutRequestFactoryCustomizer { ReadTimeoutRequestFactoryCustomizer(int readTimeout) { super(readTimeout, "setReadTimeout"); @@ -676,8 +618,7 @@ public class RestTemplateBuilder { /** * {@link RequestFactoryCustomizer} to set the connect timeout. */ - private static class ConnectTimeoutRequestFactoryCustomizer - extends TimeoutRequestFactoryCustomizer { + private static class ConnectTimeoutRequestFactoryCustomizer extends TimeoutRequestFactoryCustomizer { ConnectTimeoutRequestFactoryCustomizer(int connectTimeout) { super(connectTimeout, "setConnectTimeout"); 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 93a1a037c19..b28920529f3 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 7f26b684be7..cfbd3d16f26 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. @@ -52,8 +52,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. @@ -114,8 +113,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); } @@ -141,12 +139,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); } @@ -160,14 +156,13 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact } 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 +170,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; } @@ -191,8 +184,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 cfe5f161880..26dfbe3ed6a 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,18 +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; - JettyWebServer.logger - .info("Jetty started on port(s) " + getActualPortsDescription() - + " with context path '" + getContextPath() + "'"); + JettyWebServer.logger.info("Jetty started on port(s) " + getActualPortsDescription() + + " with context path '" + getContextPath() + "'"); } catch (WebServerException ex) { stopSilently(); @@ -195,13 +191,11 @@ 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) { - JettyWebServer.logger - .info("could not determine port ( " + ex.getMessage() + ")"); + JettyWebServer.logger.info("could not determine port ( " + ex.getMessage() + ")"); return 0; } } @@ -212,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 5340e69dbf0..45fc964f97b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 sslContextFactory = new SslContextFactory(); 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 sslContextFactory, InetSocketAddress address) { + private ServerConnector createConnector(Server server, SslContextFactory 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 sslContextFactory, HttpConfiguration config) { + private ServerConnector createServerConnector(Server server, SslContextFactory 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 sslContextFactory) { + private ServerConnector createHttp11ServerConnector(Server server, HttpConfiguration config, + SslContextFactory 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 sslContextFactory) { + private ServerConnector createHttp2ServerConnector(Server server, HttpConfiguration config, + SslContextFactory 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 factory, Ssl ssl, - SslStoreProvider sslStoreProvider) { + protected void configureSsl(SslContextFactory 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 (IOException ex) { - throw new WebServerException( - "Could not find key store '" + ssl.getKeyStore() + "'", ex); + throw new WebServerException("Could not find 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 4a0aff7bfc3..1574496449e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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; @@ -53,8 +52,7 @@ final class CompressionCustomizer implements NettyServerCustomizer { if (this.compression.getMinResponseSize() >= 0) { builder.compression(this.compression.getMinResponseSize()); } - CompressionPredicate mimeTypes = getMimeTypesPredicate( - this.compression.getMimeTypes()); + CompressionPredicate mimeTypes = getMimeTypesPredicate(this.compression.getMimeTypes()); CompressionPredicate excludedUserAgents = getExcludedUserAgentsPredicate( this.compression.getExcludedUserAgents()); builder.compression(mimeTypes.and(excludedUserAgents)); @@ -65,8 +63,7 @@ final class CompressionCustomizer implements NettyServerCustomizer { return ALWAYS_COMPRESS; } 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; } @@ -76,20 +73,18 @@ final class CompressionCustomizer implements NettyServerCustomizer { }; } - 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 8194a670c41..e48ddc8964e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 NettyReactiveWebServerFactory extends AbstractReactiveWebServerFact @Override public WebServer getWebServer(HttpHandler httpHandler) { HttpServer httpServer = createHttpServer(); - ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter( - httpHandler); + ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler); return new NettyWebServer(httpServer, handlerAdapter, this.lifecycleTimeout); } @@ -74,8 +73,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); } @@ -102,13 +100,11 @@ public class NettyReactiveWebServerFactory extends AbstractReactiveWebServerFact return HttpServer.builder().options((options) -> { options.listenAddress(getListenAddress()); if (getSsl() != null && getSsl().isEnabled()) { - SslServerCustomizer sslServerCustomizer = new SslServerCustomizer( - getSsl(), getSslStoreProvider()); + SslServerCustomizer sslServerCustomizer = new SslServerCustomizer(getSsl(), getSslStoreProvider()); sslServerCustomizer.customize(options); } if (getCompression() != null && getCompression().getEnabled()) { - CompressionCustomizer compressionCustomizer = new CompressionCustomizer( - getCompression()); + CompressionCustomizer compressionCustomizer = new CompressionCustomizer(getCompression()); compressionCustomizer.customize(options); } applyCustomizers(options); 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 069c4e3c1d4..32fc5ee3e4b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 NettyWebServer implements WebServer { private BlockingNettyContext nettyContext; - 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; @@ -74,8 +73,7 @@ public class NettyWebServer implements WebServer { if (findBindException(ex) != null) { SocketAddress address = this.httpServer.options().getAddress(); if (address instanceof InetSocketAddress) { - throw new PortInUseException( - ((InetSocketAddress) address).getPort()); + throw new PortInUseException(((InetSocketAddress) address).getPort()); } } throw new WebServerException("Unable to start Netty", ex); @@ -122,8 +120,7 @@ public class NettyWebServer implements WebServer { if (this.nettyContext != null) { this.nettyContext.shutdown(); // temporary fix for gh-9146 - this.nettyContext.getContext().onClose() - .doOnSuccess((o) -> HttpResources.reset()).block(); + this.nettyContext.getContext().onClose().doOnSuccess((o) -> HttpResources.reset()).block(); this.nettyContext = null; } } 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 6d5af74a83d..825023c8803 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +73,12 @@ public class SslServerCustomizer implements NettyServerCustomizer { } } - 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(); } @@ -92,17 +90,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 @@ -115,23 +111,20 @@ 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 loadKeyStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), - ssl.getTrustStore(), ssl.getTrustStorePassword()); + return loadKeyStore(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 { type = (type != null) ? type : "JKS"; if (resource == null) { return null; } - KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) - : KeyStore.getInstance(type); + KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type); URL url = ResourceUtils.getURL(resource); store.load(url.openStream(), (password != null) ? password.toCharArray() : null); return store; 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 911a81d485f..7d71d35f139 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 @@ -58,12 +58,10 @@ class CompressionConnectorCustomizer implements TomcatConnectorCustomizer { Compression compression = this.compression; upgradeProtocol.setCompression("on"); upgradeProtocol.setCompressionMinSize(compression.getMinResponseSize()); - upgradeProtocol.setCompressibleMimeType( - StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes())); + upgradeProtocol.setCompressibleMimeType(StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes())); if (this.compression.getExcludedUserAgents() != null) { - upgradeProtocol - .setNoCompressionUserAgents(StringUtils.arrayToCommaDelimitedString( - this.compression.getExcludedUserAgents())); + upgradeProtocol.setNoCompressionUserAgents( + StringUtils.arrayToCommaDelimitedString(this.compression.getExcludedUserAgents())); } } @@ -71,11 +69,10 @@ class CompressionConnectorCustomizer implements TomcatConnectorCustomizer { Compression compression = this.compression; protocol.setCompression("on"); protocol.setCompressionMinSize(compression.getMinResponseSize()); - protocol.setCompressibleMimeType( - StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes())); + protocol.setCompressibleMimeType(StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes())); if (this.compression.getExcludedUserAgents() != null) { - protocol.setNoCompressionUserAgents(StringUtils.arrayToCommaDelimitedString( - this.compression.getExcludedUserAgents())); + protocol.setNoCompressionUserAgents( + StringUtils.arrayToCommaDelimitedString(this.compression.getExcludedUserAgents())); } } 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 d6f6c0ea27f..9bb861e647d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 (FileNotFoundException ex) { - throw new WebServerException("Could not load key store: " + ex.getMessage(), - ex); + throw new WebServerException("Could not load key store: " + ex.getMessage(), 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 42f190bfe4e..3ce55f7e28d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 TomcatEmbeddedContext extends StandardContext { private final boolean overrideLoadOnStart; TomcatEmbeddedContext() { - this.overrideLoadOnStart = ReflectionUtils - .findMethod(StandardContext.class, "loadOnStartup", Container[].class) + this.overrideLoadOnStart = ReflectionUtils.findMethod(StandardContext.class, "loadOnStartup", Container[].class) .getReturnType() == boolean.class; } @@ -78,8 +77,7 @@ class TomcatEmbeddedContext extends StandardContext { // version is used our overridden loadOnStart method won't have been // called and the original will have already run. boolean started = super.loadOnStartup(findChildren()); - Assert.state(started, - "Unable to start embedded tomcat context " + getName()); + Assert.state(started, "Unable to start embedded tomcat context " + getName()); } } finally { 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 0a1b1badedf..4b7c7716c13 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +98,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac @Override public WebServer getWebServer(HttpHandler httpHandler) { 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); @@ -149,8 +148,7 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac */ protected void configureContext(Context context) { this.contextLifecycleListeners.forEach(context::addLifecycleListener); - this.tomcatContextCustomizers - .forEach((customizer) -> customizer.customize(context)); + this.tomcatContextCustomizers.forEach((customizer) -> customizer.customize(context)); } protected void customizeConnector(Connector connector) { @@ -170,8 +168,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); @@ -206,10 +203,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); } @@ -228,10 +223,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)); } @@ -242,8 +235,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); } @@ -253,10 +245,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)); } @@ -307,10 +297,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); } @@ -327,10 +315,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 ee01f082572..bc11044e2da 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 @@ -158,8 +158,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto @Override public WebServer getWebServer(ServletContextInitializer... initializers) { 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); @@ -190,13 +189,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); @@ -231,22 +228,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); } @@ -278,8 +271,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) { @@ -305,8 +297,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); @@ -331,8 +322,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) { // Should be true @@ -379,8 +369,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()); @@ -395,8 +384,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(); } /** @@ -526,10 +514,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); } @@ -546,10 +532,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)); } @@ -558,10 +542,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); } @@ -575,10 +557,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)); } @@ -589,16 +569,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)); } @@ -709,8 +686,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 f30bf2c5dfd..788bbd125f6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +87,14 @@ public class TomcatWebServer implements WebServer { } private void initialize() throws WebServerException { - TomcatWebServer.logger - .info("Tomcat initialized with port(s): " + getPortsDescription(false)); + TomcatWebServer.logger.info("Tomcat initialized with port(s): " + getPortsDescription(false)); synchronized (this.monitor) { try { addInstanceIdToEngineName(); 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(); @@ -110,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 +156,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,22 +198,19 @@ public class TomcatWebServer implements WebServer { } checkThatConnectorsHaveStarted(); this.started = true; - TomcatWebServer.logger - .info("Tomcat started on port(s): " + getPortsDescription(true) - + " with context path '" + getContextPath() + "'"); + TomcatWebServer.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()); } } } @@ -245,8 +238,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(); @@ -287,8 +279,7 @@ public class TomcatWebServer implements WebServer { } catch (Exception ex) { TomcatWebServer.logger.error("Cannot start connector: ", ex); - throw new WebServerException("Unable to start embedded Tomcat connectors", - ex); + throw new WebServerException("Unable to start embedded Tomcat connectors", ex); } } @@ -343,10 +334,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 9c62693370f..c493f229c71 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; @@ -73,15 +72,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) { @@ -111,15 +107,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(); } @@ -128,24 +122,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) { @@ -161,23 +153,20 @@ 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 loadKeyStore(ssl.getTrustStoreType(), ssl.getTrustStoreProvider(), - ssl.getTrustStore(), ssl.getTrustStorePassword()); + return loadKeyStore(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 { type = (type != null) ? type : "JKS"; if (resource == null) { return null; } - KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) - : KeyStore.getInstance(type); + KeyStore store = (provider != null) ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type); URL url = ResourceUtils.getURL(resource); store.load(url.openStream(), (password != null) ? password.toCharArray() : null); return store; @@ -198,15 +187,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); } @@ -214,14 +200,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 508510ebddd..74601afc002 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; } @@ -69,8 +68,7 @@ final class UndertowCompressionConfigurer { 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))); } } @@ -90,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 f8946b52c57..1fa6327e458 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); + 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)); + 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 8e4ec726eb0..ea213b4b1f1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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; @@ -101,8 +100,7 @@ public class UndertowWebServer implements WebServer { } this.undertow.start(); this.started = true; - UndertowWebServer.logger - .info("Undertow started on port(s) " + getPortsDescription()); + UndertowWebServer.logger.info("Undertow started on port(s) " + getPortsDescription()); } catch (Exception ex) { try { @@ -111,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); @@ -177,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) { @@ -186,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 df3ff232639..23feba1f917 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.StringUtils; * @see #register(Class...) * @see #scan(String...) */ -public class AnnotationConfigReactiveWebApplicationContext - extends AbstractRefreshableConfigApplicationContext +public class AnnotationConfigReactiveWebApplicationContext extends AbstractRefreshableConfigApplicationContext implements ConfigurableReactiveWebApplicationContext, AnnotationConfigRegistry { private BeanNameGenerator beanNameGenerator; @@ -134,8 +133,7 @@ public class AnnotationConfigReactiveWebApplicationContext */ @Override public 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)); } @@ -182,25 +180,20 @@ public class AnnotationConfigReactiveWebApplicationContext */ @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) { - AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader( - beanFactory); - ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner( - beanFactory); + AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory); + ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory); applyBeanNameGenerator(beanFactory, reader, scanner); applyScopeMetadataResolver(reader, scanner); loadBeanDefinitions(reader, scanner); } - private void applyBeanNameGenerator(DefaultListableBeanFactory beanFactory, - AnnotatedBeanDefinitionReader reader, + private void applyBeanNameGenerator(DefaultListableBeanFactory beanFactory, AnnotatedBeanDefinitionReader reader, ClassPathBeanDefinitionScanner scanner) { BeanNameGenerator beanNameGenerator = getBeanNameGenerator(); if (beanNameGenerator != null) { reader.setBeanNameGenerator(beanNameGenerator); scanner.setBeanNameGenerator(beanNameGenerator); - beanFactory.registerSingleton( - AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, - beanNameGenerator); + beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator); } } @@ -213,8 +206,8 @@ public class AnnotationConfigReactiveWebApplicationContext } } - private void loadBeanDefinitions(AnnotatedBeanDefinitionReader reader, - ClassPathBeanDefinitionScanner scanner) throws LinkageError { + private void loadBeanDefinitions(AnnotatedBeanDefinitionReader reader, ClassPathBeanDefinitionScanner scanner) + throws LinkageError { if (!this.annotatedClasses.isEmpty()) { registerAnnotatedClasses(reader); } @@ -230,8 +223,7 @@ public class AnnotationConfigReactiveWebApplicationContext private void registerAnnotatedClasses(AnnotatedBeanDefinitionReader reader) { if (this.logger.isInfoEnabled()) { this.logger.info("Registering annotated classes: [" - + StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) - + "]"); + + StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]"); } reader.register(ClassUtils.toClassArray(this.annotatedClasses)); } @@ -239,23 +231,21 @@ public class AnnotationConfigReactiveWebApplicationContext private void scanBasePackages(ClassPathBeanDefinitionScanner scanner) { if (this.logger.isInfoEnabled()) { this.logger.info("Scanning base packages: [" - + StringUtils.collectionToCommaDelimitedString(this.basePackages) - + "]"); + + StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]"); } scanner.scan(StringUtils.toStringArray(this.basePackages)); } - private void registerConfigLocations(AnnotatedBeanDefinitionReader reader, - ClassPathBeanDefinitionScanner scanner, String[] configLocations) - throws LinkageError { + private void registerConfigLocations(AnnotatedBeanDefinitionReader reader, ClassPathBeanDefinitionScanner scanner, + String[] configLocations) throws LinkageError { for (String configLocation : configLocations) { try { register(reader, configLocation); } catch (ClassNotFoundException ex) { if (this.logger.isDebugEnabled()) { - this.logger.debug("Could not load class for config location [" - + configLocation + "] - trying package scan. " + ex); + this.logger.debug("Could not load class for config location [" + configLocation + + "] - trying package scan. " + ex); } int count = scanner.scan(configLocation); if (this.logger.isInfoEnabled()) { @@ -276,12 +266,10 @@ public class AnnotationConfigReactiveWebApplicationContext private void logScanResult(String configLocation, int count) { if (count == 0) { - this.logger.info("No annotated classes found for specified class/package [" - + configLocation + "]"); + this.logger.info("No annotated classes found for specified class/package [" + configLocation + "]"); } else { - this.logger.info("Found " + count + " annotated classes in package [" - + configLocation + "]"); + this.logger.info("Found " + count + " annotated classes in package [" + configLocation + "]"); } } @@ -296,8 +284,7 @@ public class AnnotationConfigReactiveWebApplicationContext * @see #getBeanNameGenerator() * @see #getScopeMetadataResolver() */ - protected AnnotatedBeanDefinitionReader getAnnotatedBeanDefinitionReader( - DefaultListableBeanFactory beanFactory) { + protected AnnotatedBeanDefinitionReader getAnnotatedBeanDefinitionReader(DefaultListableBeanFactory beanFactory) { return new AnnotatedBeanDefinitionReader(beanFactory, getEnvironment()); } @@ -312,8 +299,7 @@ public class AnnotationConfigReactiveWebApplicationContext * @see #getBeanNameGenerator() * @see #getScopeMetadataResolver() */ - protected ClassPathBeanDefinitionScanner getClassPathBeanDefinitionScanner( - DefaultListableBeanFactory beanFactory) { + protected ClassPathBeanDefinitionScanner getClassPathBeanDefinitionScanner(DefaultListableBeanFactory beanFactory) { return new ClassPathBeanDefinitionScanner(beanFactory, true, getEnvironment()); } 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 7162797b203..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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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 a89d45d7f7c..d955d183dcf 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } } @@ -100,18 +98,14 @@ public class ReactiveWebServerApplicationContext */ protected ReactiveWebServerFactory getWebServerFactory() { // 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 getBeanFactory().getBean(beanNames[0], ReactiveWebServerFactory.class); } @@ -202,10 +196,8 @@ public class ReactiveWebServerApplicationContext this.server = factory.getWebServer(this); } - 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 @@ -225,8 +217,7 @@ 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 = 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 47b99ced836..eebc8ab8bba 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.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; @@ -76,8 +75,7 @@ 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()); @@ -94,8 +92,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { if (error instanceof ResponseStatusException) { return ((ResponseStatusException) error).getStatus(); } - ResponseStatus responseStatus = AnnotatedElementUtils - .findMergedAnnotation(error.getClass(), ResponseStatus.class); + ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(error.getClass(), + ResponseStatus.class); if (responseStatus != null) { return responseStatus.code(); } @@ -109,8 +107,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { if (error instanceof ResponseStatusException) { return ((ResponseStatusException) error).getReason(); } - ResponseStatus responseStatus = AnnotatedElementUtils - .findMergedAnnotation(error.getClass(), ResponseStatus.class); + ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(error.getClass(), + ResponseStatus.class); if (responseStatus != null) { return responseStatus.reason(); } @@ -131,8 +129,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()); } @@ -150,8 +147,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 aaa5ff62e57..1f31bd27b6c 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 Ordered { +public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter implements Ordered { /** * 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 1170562fb12..c544ccccc29 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. @@ -28,9 +28,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 bf0e51df835..e6e1e4584d3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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.StringUtils; * @author Phillip Webb * @since 2.0.1 */ -public abstract class AbstractFilterRegistrationBean - extends DynamicRegistrationBean { +public abstract class AbstractFilterRegistrationBean extends DynamicRegistrationBean { /** * Filters that wrap the servlet request should be ordered less than or equal to this. @@ -70,10 +69,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); } @@ -81,10 +78,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); } @@ -104,10 +99,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); } @@ -242,21 +235,18 @@ public abstract class AbstractFilterRegistrationBean } servletNames.addAll(this.servletNames); if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) { - this.logger.info("Mapping filter: '" + registration.getName() + "' to: " - + Arrays.asList(DEFAULT_URL_MAPPINGS)); - registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, - DEFAULT_URL_MAPPINGS); + this.logger.info( + "Mapping filter: '" + registration.getName() + "' to: " + Arrays.asList(DEFAULT_URL_MAPPINGS)); + registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS); } else { if (!servletNames.isEmpty()) { - this.logger.info("Mapping filter: '" + registration.getName() - + "' to servlets: " + servletNames); + this.logger.info("Mapping filter: '" + registration.getName() + "' to servlets: " + servletNames); registration.addMappingForServletNames(dispatcherTypes, this.matchAfter, StringUtils.toStringArray(servletNames)); } if (!this.urlPatterns.isEmpty()) { - this.logger.info("Mapping filter: '" + registration.getName() - + "' to urls: " + this.urlPatterns); + this.logger.info("Mapping filter: '" + registration.getName() + "' to urls: " + this.urlPatterns); registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, StringUtils.toStringArray(this.urlPatterns)); } 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 0342990e3dc..418b94667c2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.Assert; * @see ServletContext#addFilter(String, Filter) * @see DelegatingFilterProxyRegistrationBean */ -public class FilterRegistrationBean - extends AbstractFilterRegistrationBean { +public class FilterRegistrationBean extends AbstractFilterRegistrationBean { /** * Filters that wrap the servlet request should be ordered less than or equal to this. @@ -62,8 +61,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 2e8c66c8dc6..57aca02d186 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,8 +127,7 @@ public class MultipartConfigFactory { * @return the multipart config element */ public MultipartConfigElement createMultipartConfig() { - return new MultipartConfigElement(this.location, this.maxFileSize, - this.maxRequestSize, this.fileSizeThreshold); + return new MultipartConfigElement(this.location, this.maxFileSize, this.maxRequestSize, this.fileSizeThreshold); } } 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 a64fbf20d6f..73d401c656e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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<>(); 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 ea6c71b63e0..113ce7d70c7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +58,11 @@ import org.springframework.util.MultiValueMap; * @author Phillip Webb * @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. @@ -79,55 +77,45 @@ public class ServletContextInitializerBeans this.initializers = new LinkedMultiValueMap<>(); 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); } private void addServletContextInitializerBeans(ListableBeanFactory beanFactory) { - for (Entry initializerBean : getOrderedBeansOfType( - beanFactory, ServletContextInitializer.class)) { - addServletContextInitializerBean(initializerBean.getKey(), - initializerBean.getValue(), beanFactory); + for (Entry initializerBean : getOrderedBeansOfType(beanFactory, + ServletContextInitializer.class)) { + 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 @@ -136,14 +124,12 @@ public class ServletContextInitializerBeans if (ServletContextInitializerBeans.logger.isDebugEnabled()) { String resourceDescription = getResourceDescription(beanName, beanFactory); int order = getOrder(initializer); - ServletContextInitializerBeans.logger.debug("Added existing " - + type.getSimpleName() + " initializer bean '" + beanName - + "'; order=" + order + ", resource=" + resourceDescription); + ServletContextInitializerBeans.logger.debug("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(); @@ -154,21 +140,17 @@ public class ServletContextInitializerBeans @SuppressWarnings("unchecked") private 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(); } @@ -177,24 +159,21 @@ public class ServletContextInitializerBeans addAsRegistrationBean(beanFactory, type, type, adapter); } - private void addAsRegistrationBean(ListableBeanFactory beanFactory, - Class type, Class beanType, RegistrationBeanAdapter adapter) { - List> beans = getOrderedBeansOfType(beanFactory, beanType, - this.seen); + private void addAsRegistrationBean(ListableBeanFactory beanFactory, Class type, + Class beanType, RegistrationBeanAdapter adapter) { + List> beans = getOrderedBeansOfType(beanFactory, beanType, this.seen); for (Entry bean : beans) { if (this.seen.add(bean.getValue())) { int order = getOrder(bean.getValue()); String beanName = bean.getKey(); // One that we haven't already seen - RegistrationBean registration = adapter.createRegistrationBean(beanName, - bean.getValue(), beans.size()); + RegistrationBean registration = adapter.createRegistrationBean(beanName, bean.getValue(), beans.size()); registration.setOrder(order); this.initializers.add(type, registration); if (ServletContextInitializerBeans.logger.isDebugEnabled()) { ServletContextInitializerBeans.logger.debug( - "Created " + type.getSimpleName() + " initializer for bean '" - + beanName + "'; order=" + order + ", resource=" - + getResourceDescription(beanName, beanFactory)); + "Created " + type.getSimpleName() + " initializer for bean '" + beanName + "'; order=" + + order + ", resource=" + getResourceDescription(beanName, beanFactory)); } } } @@ -209,16 +188,14 @@ 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) { - Comparator> comparator = (o1, - o2) -> AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), - o2.getValue()); + private List> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class type, + Set excludes) { + Comparator> comparator = (o1, o2) -> AnnotationAwareOrderComparator.INSTANCE + .compare(o1.getValue(), o2.getValue()); String[] names = beanFactory.getBeanNamesForType(type, true, false); Map map = new LinkedHashMap<>(); for (String name : names) { @@ -251,16 +228,14 @@ public class ServletContextInitializerBeans */ private 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; @@ -269,14 +244,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; @@ -287,12 +260,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; @@ -303,8 +274,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 cded337fcf8..71b66176b13 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. @@ -51,8 +51,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 Log logger = LogFactory.getLog(ServletRegistrationBean.class); @@ -91,8 +90,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; @@ -181,8 +179,7 @@ public class ServletRegistrationBean } @Override - protected ServletRegistration.Dynamic addRegistration(String description, - ServletContext servletContext) { + protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); logger.info("Servlet " + name + " mapped to " + this.urlMappings); 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/AnnotationConfigServletWebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/AnnotationConfigServletWebServerApplicationContext.java index 6254e92b1e3..df6e231eda0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon * @see ServletWebServerApplicationContext * @see AnnotationConfigWebApplicationContext */ -public class AnnotationConfigServletWebServerApplicationContext - extends ServletWebServerApplicationContext implements AnnotationConfigRegistry { +public class AnnotationConfigServletWebServerApplicationContext extends ServletWebServerApplicationContext + implements AnnotationConfigRegistry { private final AnnotatedBeanDefinitionReader reader; @@ -80,8 +80,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); @@ -94,8 +93,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(); @@ -143,8 +141,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); } @@ -176,8 +173,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 f78bb4fa5de..9c2b0b824ac 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 Ordered { +public class OrderedCharacterEncodingFilter extends CharacterEncodingFilter implements Ordered { 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 1aac15237ce..a30204cf9b6 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +26,12 @@ import org.springframework.web.filter.HiddenHttpMethodFilter; * @author Phillip Webb * @since 2.0.0 */ -public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter - implements Ordered { +public class OrderedHiddenHttpMethodFilter extends HiddenHttpMethodFilter implements Ordered { /** * The default order is high to ensure the filter is applied before Spring Security. */ - public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 10000; + public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 10000; private int order = DEFAULT_ORDER; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHttpPutFormContentFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHttpPutFormContentFilter.java index c12840f8ca8..764f217d1ba 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHttpPutFormContentFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/filter/OrderedHttpPutFormContentFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +26,12 @@ import org.springframework.web.filter.HttpPutFormContentFilter; * @author Joao Pedro Evangelista * @since 2.0.0 */ -public class OrderedHttpPutFormContentFilter extends HttpPutFormContentFilter - implements Ordered { +public class OrderedHttpPutFormContentFilter extends HttpPutFormContentFilter implements Ordered { /** * Higher order to ensure the filter is applied before Spring Security. */ - public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - - 9900; + public static final int DEFAULT_ORDER = FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 9900; private int order = DEFAULT_ORDER; 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 66686534524..7fc0b57fb38 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. @@ -56,8 +56,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()); @@ -130,12 +129,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 '/'"); } } } @@ -249,11 +246,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); @@ -265,8 +260,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()); } /** @@ -294,8 +289,7 @@ public abstract class AbstractServletWebServerFactory return URLDecoder.decode(url.getFile(), "UTF-8"); } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException( - "Failed to decode '" + url.getFile() + "' using UTF-8"); + throw new IllegalStateException("Failed to decode '" + url.getFile() + "' using UTF-8"); } } @@ -311,8 +305,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; @@ -323,8 +316,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()); } @@ -354,8 +346,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 f568ed3415f..afeda12b452 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -99,31 +98,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() && AnnotationUtils - .findAnnotation(getClass(), Configuration.class) != null) { + if (application.getAllSources().isEmpty() + && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) { application.addPrimarySources(Collections.singleton(getClass())); } Assert.state(!application.getAllSources().isEmpty(), @@ -131,8 +126,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); } @@ -157,10 +151,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; } @@ -193,8 +185,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/test/java/org/springframework/boot/BannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index 06c9b174abf..626fa1223fe 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +105,12 @@ public class BannerTests { application.setBanner(banner); this.context = application.run(); Banner printedBanner = (Banner) this.context.getBean("springBootBanner"); - assertThat(ReflectionTestUtils.getField(printedBanner, "banner")) - .isEqualTo(banner); - verify(banner).printBanner(any(Environment.class), - this.sourceClassCaptor.capture(), any(PrintStream.class)); + assertThat(ReflectionTestUtils.getField(printedBanner, "banner")).isEqualTo(banner); + 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 @@ -132,8 +130,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 2f9b14b892b..b76401da94b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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" }; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -70,8 +69,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(); } @@ -84,8 +82,7 @@ public class DefaultApplicationArgumentsTests { @Test public void getNoNonOptionArgs() { - ApplicationArguments arguments = new DefaultApplicationArguments( - new String[] { "--debug" }); + ApplicationArguments arguments = new DefaultApplicationArguments(new String[] { "--debug" }); assertThat(arguments.getNonOptionArgs()).isEmpty(); } 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/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 7ee677483cb..326043c674e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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.sources=org.springframework.boot.OverrideSourcesTests.MainConfiguration" }); assertThat(this.context.getBean(Service.class).bean.name).isEqualTo("bar"); 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 33f90e1e4af..7fed8cbbcf9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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("dev")).isTrue(); assertThat(this.context.getEnvironment().acceptsProfiles("a")).isTrue(); @@ -164,12 +163,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 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 c6d8138d1cd..f007c8d88df 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 SimpleMainTests { @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); } @@ -70,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 8084e1c6179..d03d91f52c6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 0ecc58bebf6..d6d9f9b6932 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -194,8 +194,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 +202,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 +235,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 +243,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 +260,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"); } @@ -321,27 +314,22 @@ public class SpringApplicationTests { @Test public void specificWebApplicationContextClassDetectWebApplicationType() { SpringApplication application = new SpringApplication(ExampleConfig.class); - application - .setApplicationContextClass(AnnotationConfigWebApplicationContext.class); - assertThat(application.getWebApplicationType()) - .isEqualTo(WebApplicationType.SERVLET); + application.setApplicationContextClass(AnnotationConfigWebApplicationContext.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 @@ -349,8 +337,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); - application.setInitializers(Arrays.asList( - (ApplicationContextInitializer) reference::set)); + application.setInitializers( + Arrays.asList((ApplicationContextInitializer) reference::set)); this.context = application.run("--foo=bar"); assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults @@ -362,8 +350,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) { @@ -406,8 +393,7 @@ 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(ApplicationEnvironmentPreparedEvent.class)); inOrder.verify(listener).onApplicationEvent(isA(ApplicationPreparedEvent.class)); inOrder.verify(listener).onApplicationEvent(isA(ContextRefreshedEvent.class)); inOrder.verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); @@ -428,18 +414,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 +430,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 +453,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 +464,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 +499,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 +507,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 +567,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 +588,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 @@ -635,8 +603,7 @@ 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); @@ -646,8 +613,7 @@ public class SpringApplicationTests { @Override public void run(String... args) throws Exception { - assertThat(SpringApplicationTests.this.output.toString()) - .contains("Started"); + assertThat(SpringApplicationTests.this.output.toString()).contains("Started"); commandLineRunner.run(args); } @@ -656,45 +622,37 @@ public class SpringApplicationTests { @Override public void run(ApplicationArguments args) throws Exception { - assertThat(SpringApplicationTests.this.output.toString()) - .contains("Started"); + 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)); this.thrown.expectCause(equalTo(failure)); try { application.run(); @@ -702,25 +660,21 @@ public class SpringApplicationTests { finally { verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationReadyEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationReadyEvent.class)); } } @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)); this.thrown.expectCause(equalTo(failure)); try { application.run(); @@ -728,8 +682,7 @@ public class SpringApplicationTests { finally { verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationReadyEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationReadyEvent.class)); } } @@ -738,20 +691,17 @@ 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)); + willThrow(failure).given(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); this.thrown.expect(equalTo(failure)); try { application.run(); } finally { verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationFailedEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); } } @@ -762,20 +712,17 @@ 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)); try { application.run(); fail("Run should have failed with a RuntimeException"); } catch (RuntimeException ex) { verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationFailedEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); assertThat(exitCodeListener.getExitCode()).isEqualTo(11); assertThat(this.output.toString()).contains("Application run failed"); } @@ -790,15 +737,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(); } @@ -811,8 +756,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(); } @@ -833,16 +777,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() { @@ -866,8 +808,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() { @@ -891,8 +832,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() { @@ -909,19 +849,17 @@ public class SpringApplicationTests { } catch (RuntimeException ex) { } - 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); @@ -931,8 +869,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); @@ -949,8 +886,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); @@ -962,8 +898,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); @@ -975,10 +911,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") @@ -1001,8 +937,7 @@ public class SpringApplicationTests { fail("Run should have failed with an ApplicationContextException"); } catch (ApplicationContextException ex) { - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, + verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, ApplicationFailedEvent.class); } } @@ -1011,8 +946,7 @@ public class SpringApplicationTests { @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); try { @@ -1020,8 +954,7 @@ public class SpringApplicationTests { fail("Run should have failed with a BeanCreationException"); } catch (BeanCreationException ex) { - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, + verifyListenerEvents(listener, ApplicationStartingEvent.class, ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class, ApplicationFailedEvent.class); } } @@ -1029,11 +962,9 @@ public class SpringApplicationTests { @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)); + application.addInitializers((applicationContext) -> applicationContext.addApplicationListener(listener)); try { application.run(); fail("Run should have failed with an ApplicationContextException"); @@ -1047,11 +978,9 @@ 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)); + application.addInitializers((applicationContext) -> applicationContext.addApplicationListener(listener)); try { application.run(); fail("Run should have failed with a BeanCreationException"); @@ -1068,14 +997,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"); @@ -1083,8 +1010,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(); @@ -1094,8 +1020,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"); @@ -1103,8 +1028,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); @@ -1114,65 +1038,51 @@ public class SpringApplicationTests { @Test public void webApplicationSwitchedOffInListener() { - TestSpringApplication application = new TestSpringApplication( - ExampleConfig.class); - application.addListeners( - (ApplicationListener) (event) -> { - Assertions.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) -> { + Assertions.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 @@ -1181,8 +1091,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(); } @@ -1194,15 +1103,14 @@ public class SpringApplicationTests { assertThat(occurrences).as("Expected single stacktrace").isEqualTo(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; } } @@ -1212,8 +1120,7 @@ public class SpringApplicationTests { }; } - private Condition runTestRunnerBean( - final String name) { + private Condition runTestRunnerBean(final String name) { return new Condition("run testrunner bean") { @Override @@ -1234,8 +1141,7 @@ public class SpringApplicationTests { public static class SpyApplicationContext extends AnnotationConfigApplicationContext { - ConfigurableApplicationContext applicationContext = spy( - new AnnotationConfigApplicationContext()); + ConfigurableApplicationContext applicationContext = spy(new AnnotationConfigApplicationContext()); @Override public void registerShutdownHook() { @@ -1274,8 +1180,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); } @@ -1385,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 @@ -1445,8 +1349,7 @@ public class SpringApplicationTests { } - static class ExitStatusException extends RuntimeException - implements ExitCodeGenerator { + static class ExitStatusException extends RuntimeException implements ExitCodeGenerator { @Override public int getExitCode() { @@ -1475,8 +1378,7 @@ public class SpringApplicationTests { } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @@ -1488,8 +1390,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(); } } @@ -1500,8 +1401,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); @@ -1514,8 +1414,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/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/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index 2238c90eac6..8ed45b0ce03 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -90,17 +89,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(); } @@ -143,8 +138,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 5e129c66050..562f4d80c32 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +66,8 @@ 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"); @@ -77,29 +76,26 @@ public class SpringApplicationBuilderTests { @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", "two=a:b", "three:c:\\logging.file", - "four:a:b"); + SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) + .contextClass(StaticApplicationContext.class) + .properties("one=c:\\logging.file", "two=a:b", "three:c:\\logging.file", "four:a:b"); this.context = application.run(); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.getProperty("one")).isEqualTo("c:\\logging.file"); @@ -110,8 +106,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); @@ -119,191 +114,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("node")).isTrue(); - assertThat(this.context.getEnvironment().getProperty("transport")) - .isEqualTo("redis"); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node")) - .isTrue(); - assertThat(this.context.getParent().getEnvironment().getProperty("transport")) - .isEqualTo("redis"); + assertThat(this.context.getEnvironment().getProperty("transport")).isEqualTo("redis"); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("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("node", "admin")) - .isTrue(); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) - .isFalse(); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("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("node", "admin")) - .isTrue(); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node", - "parent")).isTrue(); - assertThat(this.context.getParent().getEnvironment().acceptsProfiles("admin")) - .isFalse(); + assertThat(this.context.getEnvironment().acceptsProfiles("node", "admin")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("node", "parent")).isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("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("node", "admin")) - .isTrue(); + assertThat(this.context.getEnvironment().acceptsProfiles("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("admin")) - .isTrue(); + assertThat(this.context.getParent().getEnvironment().acceptsProfiles("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); @@ -321,8 +280,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 42c8822b22f..075023a810f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -55,8 +54,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(); @@ -72,8 +70,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 e8dea616ec8..879f6297ded 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +52,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(); @@ -92,8 +91,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(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); @@ -102,8 +100,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(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); @@ -115,8 +112,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(FileCopyUtils.copyToString(new FileReader(file))).isEmpty(); @@ -130,8 +126,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(FileCopyUtils.copyToString(new FileReader(file))).isNotEmpty(); } @@ -159,38 +154,30 @@ 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); this.exception.expect(IllegalStateException.class); this.exception.expectMessage("Cannot create pid file"); listener.onApplicationEvent(event); } - 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/TypeExcludeFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index 1262193ca66..657fb7813b9 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 @@ -55,10 +55,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(); @@ -68,8 +66,7 @@ public class TypeExcludeFilterTests { @Configuration @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 90a4b82193c..85e6e1c71a7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +55,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 c1 = new TestSortedConfigurations(Arrays.asList(OutputStream.class, InputStream.class)); Configurations c2 = new TestConfigurations(Arrays.asList(Short.class)); - Configurations c3 = new TestSortedConfigurations( - Arrays.asList(String.class, Integer.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 ae6df5137a6..95dba932099 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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 fac91e42f0c..6ce81fc4687 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -102,8 +102,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; @@ -144,8 +143,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"); @@ -154,8 +152,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"); @@ -189,8 +186,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"); @@ -220,8 +216,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"); @@ -230,8 +225,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"); @@ -293,8 +287,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"); @@ -312,9 +306,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"); @@ -322,9 +315,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"); @@ -390,91 +382,77 @@ 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"); } @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(); @@ -488,10 +466,8 @@ public class ConfigFileApplicationListenerTests { private String createLogForProfile(String profile) { String suffix = (profile != null) ? "-" + profile : ""; String string = ".properties)"; - return "Loaded config file '" - + new File("target/test-classes/application" + suffix + ".properties") - .getAbsoluteFile().toURI().toString() - + "' (classpath:/application" + suffix + string; + return "Loaded config file '" + new File("target/test-classes/application" + suffix + ".properties") + .getAbsoluteFile().toURI().toString() + "' (classpath:/application" + suffix + string; } @Test @@ -547,12 +523,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)"); } @@ -560,30 +533,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"); @@ -592,8 +561,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"); @@ -607,11 +575,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(); } @@ -623,11 +591,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"); } @@ -637,8 +605,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 @@ -647,20 +614,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 @@ -672,31 +637,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"); @@ -707,50 +669,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"); @@ -770,8 +727,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 @@ -779,8 +736,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"); } @@ -790,8 +746,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"); } @@ -820,12 +776,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 @@ -833,8 +787,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(); @@ -846,12 +799,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 @@ -867,13 +818,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 @@ -888,8 +837,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"); @@ -941,10 +889,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) { @@ -1002,37 +948,32 @@ public class ConfigFileApplicationListenerTests { } @Configuration - @PropertySource({ "classpath:/specificlocation.properties", - "classpath:/moreproperties.properties" }) + @PropertySource({ "classpath:/specificlocation.properties", "classpath:/moreproperties.properties" }) protected static class WithPropertySourceMultipleLocations { } @Configuration - @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<>( - Arrays.asList(new LowestPrecedenceEnvironmentPostProcessor())); + return new ArrayList<>(Arrays.asList(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 265c9d1c850..cb6b7f97cad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 411f9bb78cd..363075d358e 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); @@ -63,8 +62,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); } @@ -97,8 +95,7 @@ public class DelegatingApplicationContextInitializerTests { } @Order(Ordered.HIGHEST_PRECEDENCE) - private static class MockInitA - implements ApplicationContextInitializer { + private static class MockInitA implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -108,20 +105,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 a7b487fed2d..dbe8d42ce33 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@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 4ced23c7636..53898797485 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,8 +100,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)); new File("target/foo.log").delete(); new File(tmpDir() + "/spring.log").delete(); @@ -129,8 +128,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); @@ -140,8 +138,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-")); @@ -153,31 +150,27 @@ public class LoggingApplicationListenerTests { public void overrideConfigLocation() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml"); - 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("???") - .startsWith("LOG_FILE_IS_UNDEFINED").endsWith("BOOTBOOT"); + assertThat(output).contains("Hello world").doesNotContain("???").startsWith("LOG_FILE_IS_UNDEFINED") + .endsWith("BOOTBOOT"); } @Test public void overrideConfigDoesNotExist() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.config=doesnotexist.xml"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); this.thrown.expect(IllegalStateException.class); - 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()); } @Test public void azureDefaultLoggingConfigDoesNotCauseAFailure() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(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("???"); @@ -186,10 +179,8 @@ public class LoggingApplicationListenerTests { @Test public void tomcatNopLoggingConfigDoesNotCauseAFailure() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "LOGGING_CONFIG: -Dnop"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "LOGGING_CONFIG: -Dnop"); + 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("???"); @@ -204,32 +195,26 @@ public class LoggingApplicationListenerTests { 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() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", - "logging.file=target/foo.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + "logging.config=classpath:logback-nondefault.xml", "logging.file=target/foo.log"); + 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("target/foo.log"); } @Test public void addLogFilePropertyWithDefault() { assertThat(new File("target/foo.log").exists()).isFalse(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.file=target/foo.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.file=target/foo.log"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class); logger.info("Hello world"); assertThat(new File("target/foo.log").exists()).isTrue(); @@ -238,23 +223,19 @@ public class LoggingApplicationListenerTests { @Test public void addLogPathProperty() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.config=classpath:logback-nondefault.xml", - "logging.path=target/foo/"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + "logging.config=classpath:logback-nondefault.xml", "logging.path=target/foo/"); + 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("target/foo/spring.log"); } @Test public void parseDebugArg() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(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"); @@ -264,8 +245,7 @@ public class LoggingApplicationListenerTests { @Test public void parseTraceArg() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(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"); @@ -283,10 +263,8 @@ public class LoggingApplicationListenerTests { } private void disableDebugTraceArg(String... environment) { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - environment); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, environment); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.trace("testattrace"); assertThat(this.outputCapture.toString()).doesNotContain("testatdebug"); @@ -297,8 +275,7 @@ public class LoggingApplicationListenerTests { public void parseLevels() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=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"); @@ -309,8 +286,7 @@ public class LoggingApplicationListenerTests { public void parseLevelsCaseInsensitive() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=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"); @@ -319,10 +295,9 @@ public class LoggingApplicationListenerTests { @Test public void parseLevelsWithPlaceholder() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "foo=TRACE", "logging.level.org.springframework.boot=${foo}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(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"); @@ -333,43 +308,36 @@ public class LoggingApplicationListenerTests { public void parseLevelsFails() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); - 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") - .contains("Cannot set level: GARBAGE"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").contains("Cannot set level: GARBAGE"); } @Test public void parseLevelsNone() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=OFF"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.fatal("testatfatal"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .doesNotContain("testatfatal"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testatfatal"); } @Test public void parseLevelsMapsFalseToOff() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=false"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); this.logger.fatal("testatfatal"); - assertThat(this.outputCapture.toString()).doesNotContain("testatdebug") - .doesNotContain("testatfatal"); + assertThat(this.outputCapture.toString()).doesNotContain("testatdebug").doesNotContain("testatfatal"); } @Test public void parseArgsDisabled() { this.initializer.setParseArgs(false); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(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"); } @@ -378,10 +346,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"); } @@ -395,35 +361,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() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.exceptionConversionWord=%rEx"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.exceptionConversionWord=%rEx"); + 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(); } @@ -431,25 +388,19 @@ public class LoggingApplicationListenerTests { @Test public void shutdownHookCanBeRegistered() throws Exception { TestLoggingApplicationListener listener = new TestLoggingApplicationListener(); - System.setProperty(LoggingSystem.class.getName(), - TestShutdownHandlerLoggingSystem.class.getName()); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.register_shutdown_hook=true"); - multicastEvent(listener, - new ApplicationStartingEvent(new SpringApplication(), NO_ARGS)); + System.setProperty(LoggingSystem.class.getName(), TestShutdownHandlerLoggingSystem.class.getName()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.register_shutdown_hook=true"); + 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(); @@ -459,10 +410,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(); @@ -478,23 +427,15 @@ public class LoggingApplicationListenerTests { @Test public void systemPropertiesAreSetForLoggingConfiguration() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.exception-conversion-word=conversion", "logging.file=target/log", - "logging.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("target/log"); - assertThat(System.getProperty(LoggingSystemProperties.LOG_LEVEL_PATTERN)) - .isEqualTo("level"); - assertThat(System.getProperty(LoggingSystemProperties.LOG_PATH)) - .isEqualTo("path"); + "logging.exception-conversion-word=conversion", "logging.file=target/log", "logging.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("target/log"); + assertThat(System.getProperty(LoggingSystemProperties.LOG_LEVEL_PATTERN)).isEqualTo("level"); + assertThat(System.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("path"); assertThat(System.getProperty(LoggingSystemProperties.PID_KEY)).isNotNull(); } @@ -503,8 +444,7 @@ public class LoggingApplicationListenerTests { // gh-7719 TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.pattern.console=console ${doesnotexist}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) .isEqualTo("console ${doesnotexist}"); } @@ -513,29 +453,23 @@ public class LoggingApplicationListenerTests { public void environmentPropertiesResolvePlaceholders() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.pattern.console=console ${pid}"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + 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() { - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, - "logging.file=target/${PID}.log"); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.file=target/${PID}.log"); + this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) .isEqualTo("target/" + 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(); @@ -546,14 +480,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"); } @@ -594,13 +525,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) { } @@ -625,8 +554,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/ConfigurationPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java index 9923a03e560..18bcaa7da2e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -151,16 +150,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"); } @@ -174,8 +171,7 @@ public class ConfigurationPropertiesTests { @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); } @@ -189,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"); } @@ -230,15 +225,13 @@ public class ConfigurationPropertiesTests { @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"); } @@ -252,39 +245,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 @@ -296,20 +282,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"); } @@ -318,14 +302,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"); } @@ -340,8 +322,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"); } @@ -355,10 +336,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"); } @@ -369,8 +348,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(); } @@ -381,8 +359,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(); } @@ -393,8 +370,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 @@ -428,17 +404,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"); } @@ -453,44 +427,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"); @@ -523,62 +490,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)); @@ -587,8 +544,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"); @@ -596,8 +552,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)); @@ -607,8 +562,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"); @@ -617,16 +571,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 @@ -637,13 +588,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 @@ -658,14 +607,12 @@ public class ConfigurationPropertiesTests { public void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { this.thrown.expect(BeanCreationException.class); this.thrown.expectCause(instanceOf(BindException.class)); - prepareConverterContext(NonQualifiedConverterConfiguration.class, - PersonProperties.class); + prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.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"); @@ -675,8 +622,7 @@ public class ConfigurationPropertiesTests { public void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { this.thrown.expect(BeanCreationException.class); this.thrown.expectCause(instanceOf(BindException.class)); - prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, - PersonProperties.class); + prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, PersonProperties.class); } @Test @@ -699,8 +645,7 @@ public class ConfigurationPropertiesTests { } catch (Exception ex) { assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); } } @@ -720,8 +665,7 @@ public class ConfigurationPropertiesTests { } catch (Exception ex) { assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); } } @@ -735,16 +679,15 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenFailsShouldIncludeAnnotationDetails() { removeSystemProperties(); - this.thrown.expectMessage("Could not bind properties to " - + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " - + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); + this.thrown.expectMessage( + "Could not bind properties to " + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " + + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz"); } @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"); @@ -755,8 +698,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); } @@ -775,16 +717,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); @@ -792,16 +732,13 @@ public class ConfigurationPropertiesTests { assertThat(x.get(1).getB()).isEqualTo(1); } - 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; } @@ -811,8 +748,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"); } @@ -924,8 +860,7 @@ public class ConfigurationPropertiesTests { } @Configuration - @EnableConfigurationProperties({ PrefixProperties.class, - AnotherPrefixProperties.class }) + @EnableConfigurationProperties({ PrefixProperties.class, AnotherPrefixProperties.class }) static class MultiplePrefixPropertiesDeclaredAsAnnotationValueConfiguration { } @@ -1358,8 +1293,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; @@ -1425,8 +1359,7 @@ public class ConfigurationPropertiesTests { @ConfigurationProperties("test") @Validated - static class ValidatedImplementationProperties - implements InterfaceForValidatedImplementation { + static class ValidatedImplementationProperties implements InterfaceForValidatedImplementation { @NotNull private String foo; @@ -1763,8 +1696,7 @@ public class ConfigurationPropertiesTests { @Nullable @Override - public Object convert(@Nullable Object source, TypeDescriptor sourceType, - TypeDescriptor targetType) { + public Object convert(@Nullable 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 eb2f727ffa5..52210152f8f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 PropertyMapperTests { @Test public void asIntShouldAdaptSupplier() { - Integer result = this.map.from(() -> "123").asInt(Long::valueOf) - .toInstance(Integer::new); + Integer result = this.map.from(() -> "123").asInt(Long::valueOf).toInstance(Integer::new); assertThat(result).isEqualTo(123); } @@ -132,8 +131,7 @@ public class PropertyMapperTests { @Test public void whenEqualToWhenValueIsEqualShouldMatch() { - String result = this.map.from(() -> "123").whenEqualTo("123") - .toInstance(String::new); + String result = this.map.from(() -> "123").whenEqualTo("123").toInstance(String::new); assertThat(result).isEqualTo("123"); } @@ -144,8 +142,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); } @@ -157,8 +154,7 @@ public class PropertyMapperTests { @Test public void whenWhenValueMatchesShouldMap() { - String result = this.map.from(() -> "123").when("123"::equals) - .toInstance(String::new); + String result = this.map.from(() -> "123").when("123"::equals).toInstance(String::new); assertThat(result).isEqualTo("123"); } @@ -170,8 +166,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::new); + Long result = this.map.from(source).when("123"::equals).as(Integer::valueOf).when((v) -> v == 123) + .as(Integer::longValue).toInstance(Long::new); 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 6f5acd71727..08a743c6e88 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 static org.mockito.Mockito.withSettings; */ 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); @@ -76,14 +75,13 @@ public class ArrayBinderTests { @Test public void bindToCollectionShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1", "line1")); - BindHandler handler = mock(BindHandler.class, - withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + BindHandler handler = mock(BindHandler.class, withSettings().defaultAnswer(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 @@ -152,8 +150,8 @@ public class ArrayBinderTests { fail("No exception thrown"); } catch (BindException 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]"); @@ -196,8 +194,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,15 +208,14 @@ public class ArrayBinderTests { @Test public void bindToArrayShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo[0]", "1", "line1")); - BindHandler handler = mock(BindHandler.class, - withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + BindHandler handler = mock(BindHandler.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); 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 @@ -285,8 +281,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 @@ -295,8 +291,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 fb61c635014..e5627a8e7c6 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. @@ -75,94 +75,78 @@ public class BindConverterTests { @Test public void createWhenPropertyEditorInitializerIsNotNullShouldUseToInitialize() { - new BindConverter(ApplicationConversionService.getSharedInstance(), - this.propertyEditorInitializer); + new BindConverter(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 = new BindConverter( - ApplicationConversionService.getSharedInstance(), null); - assertThat(bindConverter.canConvert("test", - ResolvableType.forClass(SampleType.class))).isFalse(); + BindConverter bindConverter = new BindConverter(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); @@ -171,10 +155,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"); } @@ -182,15 +164,13 @@ 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 = new BindConverter( - ApplicationConversionService.getSharedInstance(), null); + BindConverter bindConverter = new BindConverter(ApplicationConversionService.getSharedInstance(), null); this.thrown.expect(ConverterNotFoundException.class); bindConverter.convert("test", ResolvableType.forClass(SampleType.class)); } @@ -199,25 +179,21 @@ public class BindConverterTests { public void convertWhenConvertingToFileShouldExcludeFileEditor() { // For back compatibility we want true file conversion and not an accidental // classpath resource reference. See gh-12163 - BindConverter bindConverter = new BindConverter(new GenericConversionService(), - null); + BindConverter bindConverter = new BindConverter(new GenericConversionService(), null); File result = bindConverter.convert(".", ResolvableType.forClass(File.class)); assertThat(result.getPath()).isEqualTo("."); } @Test public void fallsBackToApplicationConversionService() { - BindConverter bindConverter = new BindConverter(new GenericConversionService(), - null); - Duration result = bindConverter.convert("10s", - ResolvableType.forClass(Duration.class)); + BindConverter bindConverter = new BindConverter(new GenericConversionService(), null); + Duration result = bindConverter.convert("10s", ResolvableType.forClass(Duration.class)); assertThat(result.getSeconds()).isEqualTo(10); } private BindConverter getPropertyEditorOnlyBindConverter( Consumer propertyEditorInitializer) { - return new BindConverter(new ThrowingConversionService(), - propertyEditorInitializer); + return new BindConverter(new ThrowingConversionService(), propertyEditorInitializer); } private BindConverter getBindConverter(Converter converter) { @@ -304,8 +280,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 2ab07bd1baf..26e1f8eb7a7 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-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -195,8 +195,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 0a69515094a..59a2f4afac7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 BindableTests { @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 @@ -78,28 +77,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() { this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - "ExistingValue must be an instance of " + String.class.getName()); + this.thrown.expectMessage("ExistingValue must be an instance of " + String.class.getName()); Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123); } @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); } @@ -107,26 +103,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 @@ -137,47 +129,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 8c82fb72d02..a872a8336d2 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. @@ -91,8 +91,7 @@ public class BinderTests { public void bindWhenNameIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Name must not be null"); - this.binder.bind((ConfigurationPropertyName) null, Bindable.of(String.class), - BindHandler.DEFAULT); + this.binder.bind((ConfigurationPropertyName) null, Bindable.of(String.class), BindHandler.DEFAULT); } @Test @@ -144,8 +143,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); } @@ -154,32 +152,28 @@ 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"); } @Test public void bindToValueShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo", "1", "line1")); - BindHandler handler = mock(BindHandler.class, - withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + BindHandler handler = mock(BindHandler.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); 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 @@ -191,8 +185,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"); @@ -211,37 +204,30 @@ public class BinderTests { @Test public void bindToJavaBeanShouldTriggerOnSuccess() { - this.sources - .add(new MockConfigurationPropertySource("foo.value", "bar", "line1")); - BindHandler handler = mock(BindHandler.class, - withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + this.sources.add(new MockConfigurationPropertySource("foo.value", "bar", "line1")); + BindHandler handler = mock(BindHandler.class, withSettings().defaultAnswer(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.thrown.expectCause(instanceOf(ConversionFailedException.class)); - 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")); this.binder.bind("foo", Bindable.of(LocalDate.class)); } @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"); } @@ -257,8 +243,7 @@ public class BinderTests { @Override public void assertion(BindException ex) throws AssertionError { - 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(); } @@ -276,10 +261,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 4c524d11782..533513636fa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +46,9 @@ import static org.assertj.core.api.Assertions.fail; */ 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); @@ -93,8 +91,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); @@ -124,8 +122,8 @@ public class CollectionBinderTests { fail("No exception thrown"); } catch (BindException 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]"); @@ -146,8 +144,8 @@ public class CollectionBinderTests { fail("No exception thrown"); } catch (BindException 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[4].value"); @@ -190,8 +188,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); } @@ -201,20 +198,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 @@ -234,10 +228,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); @@ -297,8 +289,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"); } @@ -307,9 +298,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); } @@ -318,8 +307,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"); } @@ -352,8 +340,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"); } @@ -363,8 +350,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"); } @@ -376,8 +362,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"); @@ -390,8 +375,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(); @@ -404,8 +388,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 @@ -414,8 +398,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 @@ -423,8 +407,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); } @@ -443,8 +426,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"); } 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 03afae494fb..c9ceec544a8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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"); @@ -85,8 +84,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"); @@ -103,8 +102,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); @@ -129,8 +127,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); } @@ -143,9 +140,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); @@ -157,10 +152,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 @@ -169,10 +162,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 @@ -182,8 +173,7 @@ public class JavaBeanBinderTests { source.put("foo.list[2]", "bar-baz"); this.sources.add(source); this.thrown.expect(BindException.class); - this.thrown.expectCause( - Matchers.instanceOf(UnboundConfigurationPropertiesException.class)); + this.thrown.expectCause(Matchers.instanceOf(UnboundConfigurationPropertiesException.class)); this.binder.bind("foo", Bindable.of(ExampleListBean.class)); } @@ -193,10 +183,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 @@ -205,10 +193,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 @@ -218,8 +204,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 @@ -228,10 +213,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 @@ -240,10 +224,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 @@ -252,10 +235,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 @@ -266,8 +248,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 @@ -276,8 +257,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"); } @@ -289,8 +269,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"); @@ -315,8 +294,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,7 @@ public class JavaBeanBinderTests { source.put("foo.nested.foo", "bar"); this.sources.add(source); this.thrown.expect(BindException.class); - this.binder.bind("foo", - Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class)); + this.binder.bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class)); } @Test @@ -348,8 +326,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(); } @@ -368,11 +345,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"); } @@ -383,8 +358,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); } @@ -405,8 +379,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"); @@ -418,18 +391,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); } @@ -438,8 +408,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); } @@ -460,8 +429,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"); } @@ -471,8 +440,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); } @@ -481,8 +450,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"); } @@ -492,8 +461,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); } 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 a3f3f612b2f..7ec428309d5 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. @@ -63,20 +63,18 @@ import static org.mockito.Mockito.withSettings; */ 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); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -131,8 +129,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"); @@ -151,8 +149,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"); @@ -160,10 +158,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); @@ -180,8 +176,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"); @@ -197,10 +192,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"); } @@ -240,8 +233,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); @@ -257,8 +249,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); @@ -269,19 +260,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(); } @@ -320,8 +308,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); @@ -332,13 +320,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); } @@ -353,55 +339,47 @@ public class MapBinderTests { @Test public void bindToMapShouldTriggerOnSuccess() { this.sources.add(new MockConfigurationPropertySource("foo.bar", "1", "line1")); - BindHandler handler = mock(BindHandler.class, - withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + BindHandler handler = mock(BindHandler.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); 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")); - BindHandler handler = mock(BindHandler.class, - withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); + this.sources.add(new MockConfigurationPropertySource("foo.bar", "a,b,c", "line1")); + BindHandler handler = mock(BindHandler.class, withSettings().defaultAnswer(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"); @@ -409,8 +387,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"); @@ -439,8 +416,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"); @@ -454,26 +430,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"); @@ -486,8 +458,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"); @@ -500,8 +471,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"); @@ -577,8 +547,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")); } @@ -589,8 +558,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)); } @@ -622,13 +590,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.entrySet()).containsExactly(entry("a", "b"), entry("c", "d"), - entry("e", "f")); + assertThat(result.entrySet()).containsExactly(entry("a", "b"), entry("c", "d"), entry("e", "f")); } @Test @@ -636,16 +600,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) { @@ -697,8 +658,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) -> "")); } } @@ -741,8 +701,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 a22d7acd7d8..f00f79d3893 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. @@ -76,8 +76,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"); @@ -93,8 +92,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 0427b4b2f8d..c1f454792e9 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,7 @@ public class IgnoreErrorsBindHandlerTests { @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 1eca25ba808..c3de430f9d7 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. @@ -64,8 +64,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 @@ -74,8 +73,7 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { source.put("example.foo", "1"); this.sources.add(source); this.thrown.expectCause(instanceOf(IllegalStateException.class)); - this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler()); + this.binder.bind("example", Bindable.of(Example.class), new IgnoreTopLevelConverterNotFoundBindHandler()); } @Test @@ -85,8 +83,7 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { this.sources.add(source); this.thrown.expect(BindException.class); this.thrown.expectCause(instanceOf(ConverterNotFoundException.class)); - this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler()); + this.binder.bind("example", Bindable.of(Example.class), new IgnoreTopLevelConverterNotFoundBindHandler()); } public static class Example { 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 42a71d3890a..2e13c58aba3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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"); } @@ -76,13 +74,11 @@ public class NoUnboundElementsBindHandlerTests { this.sources.add(source); this.binder = new Binder(this.sources); try { - this.binder.bind("example", Bindable.of(Example.class), - new NoUnboundElementsBindHandler()); + this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()); fail("did not throw"); } catch (BindException ex) { - assertThat(ex.getCause().getMessage()) - .contains("The elements [example.baz] were left unbound"); + assertThat(ex.getCause().getMessage()).contains("The elements [example.baz] were left unbound"); } } @@ -93,8 +89,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"); } @@ -105,10 +101,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"); } 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/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 b08bd463a48..86998471f17 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -91,16 +90,14 @@ public class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", 4)); this.thrown.expect(BindException.class); this.thrown.expectCause(instanceOf(BindValidationException.class)); - this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), - this.handler); + this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), this.handler); } @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"); } @@ -112,21 +109,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"); } @@ -135,22 +129,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 @@ -161,8 +150,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); } 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 a0e3684040d..db2bb0ef1d1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.assertj.core.api.Assertions.assertThat; */ public class ValidationErrorsTests { - private static final ConfigurationPropertyName NAME = ConfigurationPropertyName - .of("foo"); + private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("foo"); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -73,8 +72,7 @@ public class ValidationErrorsTests { @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); } @@ -82,8 +80,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); } @@ -91,8 +88,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); } @@ -100,8 +96,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()).containsExactlyElementsOf(allErrors); } @@ -116,8 +111,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/source/AbstractPropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AbstractPropertyMapperTests.java index 6a4a92f7e4d..dd2c6c355ee 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 abstract class AbstractPropertyMapperTests { } protected final Iterator namesFromString(String name, Object value) { - 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 ebb282fd32f..0656724d226 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. @@ -60,12 +60,10 @@ public class AliasedConfigurationPropertySourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.UNKNOWN); + 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 @@ -73,14 +71,12 @@ public class AliasedConfigurationPropertySourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.PRESENT); + 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 @@ -88,14 +84,11 @@ public class AliasedConfigurationPropertySourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.ABSENT); + 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 @@ -103,14 +96,11 @@ public class AliasedConfigurationPropertySourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.ABSENT); + 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 @@ -124,8 +114,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 9edd2bc92d0..b4e2288bb91 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ConfigurationPropertyNameAliasesTests { @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 @@ -55,8 +53,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 @@ -64,18 +61,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 @@ -84,8 +79,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 @@ -117,8 +111,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 8f7bdf3ca7e..c047ca98ab2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -243,8 +243,7 @@ public class ConfigurationPropertyNameTests { @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); } @@ -280,8 +279,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"); } @@ -316,16 +315,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 @@ -363,12 +359,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 @@ -378,12 +371,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) { @@ -399,10 +389,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 @@ -413,8 +401,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]"); } @@ -475,8 +462,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(); } @@ -508,8 +494,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(); } @@ -517,8 +502,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(); } @@ -533,15 +517,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 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"); } @@ -586,8 +568,7 @@ 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); } 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 50f23478eb6..33550732f94 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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()).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 36902a60653..81f56761416 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,16 +53,14 @@ public class ConfigurationPropertyStateTests { @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 075e4837adb..2c8c6713bc6 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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.mockito.Mockito.mock; */ public class ConfigurationPropertyTests { - private static final ConfigurationPropertyName NAME = ConfigurationPropertyName - .of("foo"); + private static final ConfigurationPropertyName NAME = ConfigurationPropertyName.of("foo"); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -75,17 +74,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 c640afc6be1..a2d180a0748 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 DefaultPropertyMapperTests extends AbstractPropertyMapperTests { assertThat(namesFromString("my.host-name")).containsExactly("my.host-name"); assertThat(namesFromString("my.hostName")).containsExactly("my.hostname"); assertThat(namesFromString("my.HOST_NAME")).containsExactly("my.hostname"); - assertThat(namesFromString("s[!@#$%^&*()=+]e-rVeR")) - .containsExactly("s[!@#$%^&*()=+].e-rver"); + assertThat(namesFromString("s[!@#$%^&*()=+]e-rVeR")).containsExactly("s[!@#$%^&*()=+].e-rver"); assertThat(namesFromString("host[FOO].name")).containsExactly("host[FOO].name"); } @@ -55,14 +54,10 @@ public class DefaultPropertyMapperTests extends AbstractPropertyMapperTests { assertThat(namesFromConfiguration("server.port")).containsExactly("server.port"); assertThat(namesFromConfiguration("host[0]")).containsExactly("host[0]"); assertThat(namesFromConfiguration("host[0][1]")).containsExactly("host[0][1]"); - assertThat(namesFromConfiguration("host[0].name")) - .containsExactly("host[0].name"); - assertThat(namesFromConfiguration("host.f00.name")) - .containsExactly("host.f00.name"); - assertThat(namesFromConfiguration("my.host-name")) - .containsExactly("my.host-name"); - assertThat(namesFromConfiguration("host[FOO].name")) - .containsExactly("host[FOO].name"); + assertThat(namesFromConfiguration("host[0].name")).containsExactly("host[0].name"); + assertThat(namesFromConfiguration("host.f00.name")).containsExactly("host.f00.name"); + assertThat(namesFromConfiguration("my.host-name")).containsExactly("my.host-name"); + assertThat(namesFromConfiguration("host[FOO].name")).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 4770217d71a..4ff0fd2346e 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 FilteredConfigurationPropertiesSourceTests { public void createWhenFilterIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Filter must not be null"); - new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), - null); + new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null); } @Test @@ -62,8 +61,7 @@ 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(); } @@ -72,11 +70,9 @@ public class FilteredConfigurationPropertiesSourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.UNKNOWN); + 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 @@ -84,11 +80,9 @@ public class FilteredConfigurationPropertiesSourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.ABSENT); + 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 @@ -96,11 +90,9 @@ public class FilteredConfigurationPropertiesSourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = mock(ConfigurationPropertySource.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); - given(source.containsDescendantOf(name)) - .willReturn(ConfigurationPropertyState.PRESENT); + 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() { @@ -113,8 +105,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 58c26dd2444..4b05f15d188 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,20 +26,17 @@ 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()).extracting(ConfigurationPropertyName::toString) - .containsExactly("a", "b", "c"); + assertThat(filtered.iterator()).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 bfcac0b10ad..c13018ebd80 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 MapConfigurationPropertySourceTests { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); - assertThat(source.iterator()).containsExactly( - ConfigurationPropertyName.of("foo.bar"), + assertThat(source.iterator()).containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.baz")); } @@ -103,15 +102,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 5c66959e989..3eec395540c 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. @@ -66,8 +66,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"); } @@ -79,8 +78,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\""); } @@ -89,15 +87,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 @@ -105,8 +100,8 @@ 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); } @@ -120,8 +115,7 @@ public class SpringConfigurationPropertySourceTests { @Test public void fromWhenNonEnumerableShouldReturnNonIterable() { - PropertySource propertySource = new PropertySource("test", - new Object()) { + PropertySource propertySource = new PropertySource("test", new Object()) { @Override public Object getProperty(String name) { @@ -162,8 +156,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 93b364bb521..19bb51e7a1f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,27 +53,21 @@ public class SpringConfigurationPropertySourcesTests { @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(); } @@ -83,56 +77,43 @@ 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 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) { @@ -142,25 +123,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()).hasSize(5); } @Test public void shouldTrackChanges() { MutablePropertySources sources = new MutablePropertySources(); - SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources( - sources); + SpringConfigurationPropertySources configurationSources = new SpringConfigurationPropertySources(sources); assertThat(configurationSources.iterator()).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()).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()).hasSize(2); } @@ -168,20 +144,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 ef7a9e4bd89..bcd0d42028a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 SpringIterableConfigurationPropertySourceTests { public void createWhenMapperIsNullShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("Mapper must not be null"); - new SpringIterableConfigurationPropertySource( - mock(EnumerablePropertySource.class), null); + new SpringIterableConfigurationPropertySource(mock(EnumerablePropertySource.class), null); } @Test @@ -66,16 +65,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()).extracting(Object::toString) - .containsExactly("my.key1", "my.key2a", "my.key2b", "my.key4"); + assertThat(adapter.iterator()).extracting(Object::toString).containsExactly("my.key1", "my.key2a", "my.key2b", + "my.key4"); } @Test @@ -84,8 +82,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"); @@ -100,8 +97,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"); @@ -115,8 +111,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"); @@ -137,8 +132,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 @@ -165,8 +159,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); @@ -175,8 +169,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; 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 5efe6cd9df3..7d98c85a226 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,8 @@ public class SystemEnvironmentPropertyMapperTests extends AbstractPropertyMapper assertThat(namesFromConfiguration("host[0]")).containsExactly("HOST_0"); assertThat(namesFromConfiguration("host[0][1]")).containsExactly("HOST_0_1"); assertThat(namesFromConfiguration("host[0].name")).containsExactly("HOST_0_NAME"); - assertThat(namesFromConfiguration("host.f00.name")) - .containsExactly("HOST_F00_NAME"); - assertThat(namesFromConfiguration("foo.the-bar")).containsExactly("FOO_THEBAR", - "FOO_THE_BAR"); + assertThat(namesFromConfiguration("host.f00.name")).containsExactly("HOST_F00_NAME"); + assertThat(namesFromConfiguration("foo.the-bar")).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 ad73651fad6..91827ab1cb4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,21 +45,14 @@ public class DurationStyleTests { @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 @@ -67,50 +60,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 @@ -138,12 +120,9 @@ 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 @@ -190,40 +169,26 @@ 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 @@ -240,10 +205,8 @@ 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 @@ -273,8 +236,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 @@ -286,8 +248,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 4a5fa48ff2c..da7275c572c 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. @@ -50,8 +50,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); @@ -61,8 +60,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"); } @@ -77,8 +75,7 @@ public class InetAddressFormatterTests { 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/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/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/StringToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java index fe384bed660..c96c63571ba 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. @@ -45,8 +45,7 @@ public class StringToDurationConverterTests { private final ConversionService conversionService; - public StringToDurationConverterTests(String name, - ConversionService conversionService) { + public StringToDurationConverterTests(String name, ConversionService conversionService) { this.conversionService = conversionService; } @@ -127,12 +126,9 @@ 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 @@ -158,8 +154,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 a31e7742d24..fc0b74dc9a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,13 +43,11 @@ public class FailureAnalyzersIntegrationTests { @Test public void analysisIsPerformed() { try { - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE).run(); + new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run(); fail("Application started successfully"); } catch (Exception ex) { - assertThat(this.outputCapture.toString()) - .contains("APPLICATION FAILED TO START"); + 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 7113c2675b2..b844718549e 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/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index 77a6a411ec2..8e62aebf0a6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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/InvalidConfigurationPropertyNameFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java index 4ccdada8a20..3fba0dbb1ae 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 756675790e3..4e707af6ad8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 NoSuchMethodFailureAnalyzerTests { assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) .contains("the method javax.servlet.ServletContext.addServlet" - + "(Ljava/lang/String;Ljavax/servlet/Servlet;)" - + "Ljavax/servlet/ServletRegistration$Dynamic;") + + "(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 2d99b99ff7d..e422b7c34b8 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 34981fe014c..cbbad37530a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 ValidationExceptionFailureAnalyzerTests { fail("Expected failure did not occur"); } catch (Exception ex) { - FailureAnalysis analysis = new ValidationExceptionFailureAnalyzer() - .analyze(ex); + FailureAnalysis analysis = new ValidationExceptionFailureAnalyzer().analyze(ex); assertThat(analysis).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 32732e4267c..6747cf15d6f 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. @@ -42,10 +42,8 @@ public class NoSnakeYamlPropertySourceLoaderTests { @Test public void load() throws Exception { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Attempted to load resource but snakeyaml was not found on the classpath"); - ByteArrayResource resource = new ByteArrayResource( - "foo:\n bar: spam".getBytes()); + this.thrown.expectMessage("Attempted to load resource but snakeyaml was not found on the classpath"); + ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); this.loader.load("resource", resource); } 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 80c6b3c394c..41e33ba75e1 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. @@ -57,8 +57,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); } @@ -95,8 +94,8 @@ public class OriginTrackedPropertiesLoaderTests { // gh-12716 this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Malformed \\uxxxx encoding"); - new OriginTrackedPropertiesLoader(new ClassPathResource( - "test-properties-malformed-unicode.properties", getClass())).load(); + new OriginTrackedPropertiesLoader( + new ClassPathResource("test-properties-malformed-unicode.properties", getClass())).load(); } @Test 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 6e117e0d12a..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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 f9a3897efa5..1fd22f59bdc 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. @@ -42,8 +42,7 @@ public class SpringApplicationJsonEnvironmentPostProcessorTests { @Test public void error() { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, - "spring.application.json=foo:bar"); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); this.processor.postProcessEnvironment(this.environment, null); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); } @@ -58,8 +57,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(); } @@ -116,8 +114,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 @@ -126,12 +123,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 271243bc1ba..cf8f9f7a8fd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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/jackson/JsonComponentModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java index 035cb54e1c6..5ed84fd187a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -91,8 +91,7 @@ public class JsonComponentModuleTests { 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); } @@ -110,8 +109,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 d1f7d6ee548..56fcf898298 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -135,8 +134,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); } @@ -144,8 +142,7 @@ 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); } @@ -187,15 +184,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/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 a1ccd76d21e..7596ce79233 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,57 +38,48 @@ 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); } private DataSource wrapInProxy(DataSource 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 1bdc34aff25..3154c46b66b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import static org.assertj.core.api.Assertions.assertThat; 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.TERADATA)); + .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.ORACLE, DatabaseDriver.DB2, + DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, DatabaseDriver.TERADATA)); private final String className; @@ -60,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; } @@ -84,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 ead515fdf12..12af25f6b8c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +36,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(); } @@ -69,78 +67,49 @@ 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("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("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("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")) .isEqualTo(DatabaseDriver.POSTGRESQL); - assertThat( - DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) - .isEqualTo(DatabaseDriver.JTDS); - 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:sqlserver://127.0.0.1:1433")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebirdsql://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: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 e111895f40c..460499ade64 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. @@ -46,8 +46,7 @@ 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 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 03f6d954009..e602e601f7b 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. @@ -93,8 +93,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); } @@ -102,8 +101,8 @@ 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); } 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 f0caa547e51..16248dc5731 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java index 2b4dc4d9209..b58b7ddc87f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/DataSourceXAResourceRecoveryHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +70,9 @@ public class DataSourceXAResourceRecoveryHelperTests { } @Test - public void shouldCreateConnectionWithCredentialsAndGetXAResource() - throws SQLException { - given(this.xaDataSource.getXAConnection(anyString(), anyString())) - .willReturn(this.xaConnection); - this.recoveryHelper = new DataSourceXAResourceRecoveryHelper(this.xaDataSource, - "username", "password"); + public void shouldCreateConnectionWithCredentialsAndGetXAResource() throws SQLException { + given(this.xaDataSource.getXAConnection(anyString(), anyString())).willReturn(this.xaConnection); + this.recoveryHelper = new DataSourceXAResourceRecoveryHelper(this.xaDataSource, "username", "password"); XAResource[] xaResources = this.recoveryHelper.getXAResources(); assertThat(xaResources.length).isEqualTo(1); assertThat(xaResources[0]).isSameAs(this.recoveryHelper); @@ -85,8 +82,7 @@ public class DataSourceXAResourceRecoveryHelperTests { @Test public void shouldFailToCreateConnectionAndNotGetXAResource() throws SQLException { - given(this.xaDataSource.getXAConnection()) - .willThrow(new SQLException("Test exception")); + given(this.xaDataSource.getXAConnection()).willThrow(new SQLException("Test exception")); XAResource[] xaResources = this.recoveryHelper.getXAResources(); assertThat(xaResources.length).isEqualTo(0); verify(this.xaDataSource, times(1)).getXAConnection(); @@ -101,8 +97,7 @@ public class DataSourceXAResourceRecoveryHelperTests { } @Test - public void shouldDelegateRecoverCallAndCloseConnection() - throws XAException, SQLException { + public void shouldDelegateRecoverCallAndCloseConnection() throws XAException, SQLException { this.recoveryHelper.getXAResources(); this.recoveryHelper.recover(XAResource.TMENDRSCAN); verify(this.xaResource, times(1)).recover(XAResource.TMENDRSCAN); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java index 356c71ae9e7..0bf7c31f43d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 +46,10 @@ public class NarayanaBeanFactoryPostProcessorTests { this.context = new AnnotationConfigApplicationContext(beanFactory); this.context.register(Config.class); this.context.refresh(); - verify(beanFactory).registerDependentBean("narayanaTransactionManager", - "dataSource"); - verify(beanFactory).registerDependentBean("narayanaTransactionManager", - "connectionFactory"); - verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", - "dataSource"); - verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", - "connectionFactory"); + verify(beanFactory).registerDependentBean("narayanaTransactionManager", "dataSource"); + verify(beanFactory).registerDependentBean("narayanaTransactionManager", "connectionFactory"); + verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", "dataSource"); + verify(beanFactory).registerDependentBean("narayanaRecoveryManagerBean", "connectionFactory"); this.context.close(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java index ade97d65376..6efdda2efed 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaConfigurationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,56 +44,49 @@ public class NarayanaConfigurationBeanTests { @After @SuppressWarnings("unchecked") public void cleanup() { - ((Map) ReflectionTestUtils.getField(BeanPopulator.class, - "beanInstances")).clear(); + ((Map) ReflectionTestUtils.getField(BeanPopulator.class, "beanInstances")).clear(); } @Test public void shouldSetDefaultProperties() throws Exception { NarayanaProperties narayanaProperties = new NarayanaProperties(); - NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean( - narayanaProperties); + NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean(narayanaProperties); narayanaConfigurationBean.afterPropertiesSet(); - assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class) - .getNodeIdentifier()).isEqualTo("1"); - assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class) + assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class).getNodeIdentifier()).isEqualTo("1"); + assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getObjectStoreDir()) + .endsWith("ObjectStore"); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") .getObjectStoreDir()).endsWith("ObjectStore"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") - .getObjectStoreDir()).endsWith("ObjectStore"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore") - .getObjectStoreDir()).endsWith("ObjectStore"); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .isCommitOnePhase()).isTrue(); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .getDefaultTimeout()).isEqualTo(60); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getPeriodicRecoveryPeriod()).isEqualTo(120); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryBackoffPeriod()).isEqualTo(10); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore").getObjectStoreDir()) + .endsWith("ObjectStore"); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).isCommitOnePhase()).isTrue(); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).getDefaultTimeout()) + .isEqualTo(60); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getPeriodicRecoveryPeriod()) + .isEqualTo(120); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryBackoffPeriod()) + .isEqualTo(10); List xaResourceOrphanFilters = Arrays.asList( "com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter"); - assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class) - .getXaResourceOrphanFilterClassNames()) - .isEqualTo(xaResourceOrphanFilters); + assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class).getXaResourceOrphanFilterClassNames()) + .isEqualTo(xaResourceOrphanFilters); List recoveryModules = Arrays.asList( "com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule"); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryModuleClassNames()).isEqualTo(recoveryModules); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryModuleClassNames()) + .isEqualTo(recoveryModules); - List expiryScanners = Arrays.asList( - "com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner"); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getExpiryScannerClassNames()).isEqualTo(expiryScanners); + List expiryScanners = Arrays + .asList("com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner"); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getExpiryScannerClassNames()) + .isEqualTo(expiryScanners); - assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class) - .getXaResourceRecoveryClassNames()).isEmpty(); + assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class).getXaResourceRecoveryClassNames()) + .isEmpty(); } @Test @@ -105,44 +98,33 @@ public class NarayanaConfigurationBeanTests { narayanaProperties.setPeriodicRecoveryPeriod(Duration.ofSeconds(2)); narayanaProperties.setRecoveryBackoffPeriod(Duration.ofSeconds(3)); narayanaProperties.setOnePhaseCommit(false); - narayanaProperties.setXaResourceOrphanFilters( - Arrays.asList("test-filter-1", "test-filter-2")); - narayanaProperties - .setRecoveryModules(Arrays.asList("test-module-1", "test-module-2")); - narayanaProperties - .setExpiryScanners(Arrays.asList("test-scanner-1", "test-scanner-2")); + narayanaProperties.setXaResourceOrphanFilters(Arrays.asList("test-filter-1", "test-filter-2")); + narayanaProperties.setRecoveryModules(Arrays.asList("test-module-1", "test-module-2")); + narayanaProperties.setExpiryScanners(Arrays.asList("test-scanner-1", "test-scanner-2")); - NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean( - narayanaProperties); + NarayanaConfigurationBean narayanaConfigurationBean = new NarayanaConfigurationBean(narayanaProperties); narayanaConfigurationBean.afterPropertiesSet(); - assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class) - .getNodeIdentifier()).isEqualTo("test-id"); - assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class) + assertThat(BeanPopulator.getDefaultInstance(CoreEnvironmentBean.class).getNodeIdentifier()) + .isEqualTo("test-id"); + assertThat(BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getObjectStoreDir()) + .isEqualTo("test-dir"); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") .getObjectStoreDir()).isEqualTo("test-dir"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "communicationStore") - .getObjectStoreDir()).isEqualTo("test-dir"); - assertThat(BeanPopulator - .getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore") - .getObjectStoreDir()).isEqualTo("test-dir"); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .isCommitOnePhase()).isFalse(); - assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class) - .getDefaultTimeout()).isEqualTo(1); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getPeriodicRecoveryPeriod()).isEqualTo(2); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryBackoffPeriod()).isEqualTo(3); - assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class) - .getXaResourceOrphanFilterClassNames()) - .isEqualTo(Arrays.asList("test-filter-1", "test-filter-2")); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getRecoveryModuleClassNames()) - .isEqualTo(Arrays.asList("test-module-1", "test-module-2")); - assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class) - .getExpiryScannerClassNames()) - .isEqualTo(Arrays.asList("test-scanner-1", "test-scanner-2")); + assertThat(BeanPopulator.getNamedInstance(ObjectStoreEnvironmentBean.class, "stateStore").getObjectStoreDir()) + .isEqualTo("test-dir"); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).isCommitOnePhase()).isFalse(); + assertThat(BeanPopulator.getDefaultInstance(CoordinatorEnvironmentBean.class).getDefaultTimeout()).isEqualTo(1); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getPeriodicRecoveryPeriod()) + .isEqualTo(2); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryBackoffPeriod()) + .isEqualTo(3); + assertThat(BeanPopulator.getDefaultInstance(JTAEnvironmentBean.class).getXaResourceOrphanFilterClassNames()) + .isEqualTo(Arrays.asList("test-filter-1", "test-filter-2")); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getRecoveryModuleClassNames()) + .isEqualTo(Arrays.asList("test-module-1", "test-module-2")); + assertThat(BeanPopulator.getDefaultInstance(RecoveryEnvironmentBean.class).getExpiryScannerClassNames()) + .isEqualTo(Arrays.asList("test-scanner-1", "test-scanner-2")); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java index 38c8881875d..3092e33d0a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaDataSourceBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +64,14 @@ public class NarayanaDataSourceBeanTests { @Test public void shouldUnwrapDataSource() throws SQLException { - assertThat(this.dataSourceBean.unwrap(DataSource.class)) - .isInstanceOf(DataSource.class); - assertThat(this.dataSourceBean.unwrap(DataSource.class)) - .isSameAs(this.dataSourceBean); + assertThat(this.dataSourceBean.unwrap(DataSource.class)).isInstanceOf(DataSource.class); + assertThat(this.dataSourceBean.unwrap(DataSource.class)).isSameAs(this.dataSourceBean); } @Test public void shouldUnwrapXaDataSource() throws SQLException { - assertThat(this.dataSourceBean.unwrap(XADataSource.class)) - .isInstanceOf(XADataSource.class); - assertThat(this.dataSourceBean.unwrap(XADataSource.class)) - .isSameAs(this.dataSource); + assertThat(this.dataSourceBean.unwrap(XADataSource.class)).isInstanceOf(XADataSource.class); + assertThat(this.dataSourceBean.unwrap(XADataSource.class)).isSameAs(this.dataSource); } @Test @@ -105,8 +101,7 @@ public class NarayanaDataSourceBeanTests { Connection mockConnection = mock(Connection.class); XAConnection mockXaConnection = mock(XAConnection.class); given(mockXaConnection.getConnection()).willReturn(mockConnection); - given(this.dataSource.getXAConnection(username, password)) - .willReturn(mockXaConnection); + given(this.dataSource.getXAConnection(username, password)).willReturn(mockXaConnection); Properties properties = new Properties(); properties.put(TransactionalDriver.XADataSource, this.dataSource); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java index 3adde4768aa..1d818e85de5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXAConnectionFactoryWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 NarayanaXAConnectionFactoryWrapperTests { private TransactionManager transactionManager = mock(TransactionManager.class); - private NarayanaRecoveryManagerBean recoveryManager = mock( - NarayanaRecoveryManagerBean.class); + private NarayanaRecoveryManagerBean recoveryManager = mock(NarayanaRecoveryManagerBean.class); private NarayanaProperties properties = mock(NarayanaProperties.class); - private NarayanaXAConnectionFactoryWrapper wrapper = new NarayanaXAConnectionFactoryWrapper( - this.transactionManager, this.recoveryManager, this.properties); + private NarayanaXAConnectionFactoryWrapper wrapper = new NarayanaXAConnectionFactoryWrapper(this.transactionManager, + this.recoveryManager, this.properties); @Test public void wrap() { - ConnectionFactory wrapped = this.wrapper - .wrapConnectionFactory(this.connectionFactory); + ConnectionFactory wrapped = this.wrapper.wrapConnectionFactory(this.connectionFactory); assertThat(wrapped).isInstanceOf(ConnectionFactoryProxy.class); - verify(this.recoveryManager, times(1)) - .registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); verify(this.properties, times(1)).getRecoveryJmsUser(); verify(this.properties, times(1)).getRecoveryJmsPass(); } @@ -65,11 +62,9 @@ public class NarayanaXAConnectionFactoryWrapperTests { public void wrapWithCredentials() { given(this.properties.getRecoveryJmsUser()).willReturn("userName"); given(this.properties.getRecoveryJmsPass()).willReturn("password"); - ConnectionFactory wrapped = this.wrapper - .wrapConnectionFactory(this.connectionFactory); + ConnectionFactory wrapped = this.wrapper.wrapConnectionFactory(this.connectionFactory); assertThat(wrapped).isInstanceOf(ConnectionFactoryProxy.class); - verify(this.recoveryManager, times(1)) - .registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper(any(JmsXAResourceRecoveryHelper.class)); verify(this.properties, times(2)).getRecoveryJmsUser(); verify(this.properties, times(1)).getRecoveryJmsPass(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java index 4ef25f647b1..f54bd51bba8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jta/narayana/NarayanaXADataSourceWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,19 @@ public class NarayanaXADataSourceWrapperTests { private XADataSource dataSource = mock(XADataSource.class); - private NarayanaRecoveryManagerBean recoveryManager = mock( - NarayanaRecoveryManagerBean.class); + private NarayanaRecoveryManagerBean recoveryManager = mock(NarayanaRecoveryManagerBean.class); private NarayanaProperties properties = mock(NarayanaProperties.class); - private NarayanaXADataSourceWrapper wrapper = new NarayanaXADataSourceWrapper( - this.recoveryManager, this.properties); + private NarayanaXADataSourceWrapper wrapper = new NarayanaXADataSourceWrapper(this.recoveryManager, + this.properties); @Test public void wrap() { DataSource wrapped = this.wrapper.wrapDataSource(this.dataSource); assertThat(wrapped).isInstanceOf(NarayanaDataSourceBean.class); - verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper( - any(DataSourceXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)) + .registerXAResourceRecoveryHelper(any(DataSourceXAResourceRecoveryHelper.class)); verify(this.properties, times(1)).getRecoveryDbUser(); verify(this.properties, times(1)).getRecoveryDbPass(); } @@ -61,8 +60,8 @@ public class NarayanaXADataSourceWrapperTests { given(this.properties.getRecoveryDbPass()).willReturn("password"); DataSource wrapped = this.wrapper.wrapDataSource(this.dataSource); assertThat(wrapped).isInstanceOf(NarayanaDataSourceBean.class); - verify(this.recoveryManager, times(1)).registerXAResourceRecoveryHelper( - any(DataSourceXAResourceRecoveryHelper.class)); + verify(this.recoveryManager, times(1)) + .registerXAResourceRecoveryHelper(any(DataSourceXAResourceRecoveryHelper.class)); verify(this.properties, times(2)).getRecoveryDbUser(); verify(this.properties, times(1)).getRecoveryDbPass(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java index a4cf6e4cb4b..c198db5e6b8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/CommonsLoggingLiquibaseLoggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -142,8 +142,7 @@ public class CommonsLoggingLiquibaseLoggerTests { verify(this.delegate, never()).error("severe"); } - private class MockCommonsLoggingLiquibaseLogger - extends CommonsLoggingLiquibaseLogger { + private class MockCommonsLoggingLiquibaseLogger extends CommonsLoggingLiquibaseLogger { @Override protected Log createLogger(String name) { 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 4072695634f..13e27a8b21d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,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/LogFileTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index 71099df802d..199f10d5654 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); } @@ -63,10 +62,8 @@ public class LogFileTests { Properties properties = new Properties(); logFile.applyTo(properties); assertThat(logFile.toString()).isEqualTo("logpath/spring.log"); - assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo("logpath/spring.log"); - assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)) - .isEqualTo("logpath"); + assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)).isEqualTo("logpath/spring.log"); + assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("logpath"); } @Test @@ -76,18 +73,15 @@ 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(String file, String path) { Map properties = new LinkedHashMap<>(); properties.put("logging.file", file); properties.put("logging.path", path); - 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/java/JavaLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index 25cbfc336b4..f6f24d1c569 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,11 +49,9 @@ import static org.assertj.core.api.Assertions.assertThat; */ 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(); @@ -119,8 +117,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(); @@ -130,8 +128,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"); @@ -140,15 +137,13 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test(expected = IllegalStateException.class) public void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", - null); + 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 @@ -158,8 +153,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 @@ -171,8 +165,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 @@ -180,11 +173,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 @@ -192,10 +183,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 2f10d8c99c2..8c036837220 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); @@ -134,8 +133,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void getSupportedLevels() { - assertThat(this.loggingSystem.getSupportedLogLevels()) - .isEqualTo(EnumSet.allOf(LogLevel.class)); + assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo(EnumSet.allOf(LogLevel.class)); } @Test @@ -145,8 +143,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 @@ -158,8 +155,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 @@ -167,11 +163,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 @@ -179,10 +173,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 @@ -199,8 +192,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"); @@ -208,32 +200,27 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { @Test public void configLocationsWithNoExtraDependencies() { - assertThat(this.loggingSystem.getStandardConfigLocations()) - .contains("log4j2.xml"); + assertThat(this.loggingSystem.getStandardConfigLocations()).contains("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 @@ -249,8 +236,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { Matcher expectedOutput = containsString("[junit-"); this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected")); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } @@ -268,14 +254,11 @@ 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"))); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } finally { @@ -310,8 +293,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 86b88b038cf..6dbacec6d7e 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 @@ -84,8 +84,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 Log logger; @@ -125,8 +124,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void withFile() throws Exception { 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"); @@ -134,10 +132,8 @@ 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(getRollingPolicy().getMaxHistory()) - .isEqualTo(CoreConstants.UNBOUND_HISTORY); + assertThat(ReflectionTestUtils.getField(getRollingPolicy(), "maxFileSize").toString()).isEqualTo("10 MB"); + assertThat(getRollingPolicy().getMaxHistory()).isEqualTo(CoreConstants.UNBOUND_HISTORY); } @Test @@ -151,8 +147,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(); @@ -169,8 +164,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"); @@ -180,15 +175,13 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test(expected = IllegalStateException.class) public void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - this.loggingSystem.initialize(this.initializationContext, - "classpath:logback-nonexistent.xml", null); + 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 @@ -198,8 +191,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 @@ -211,8 +203,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 @@ -220,11 +211,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 @@ -232,23 +221,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 @@ -256,8 +242,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); } @@ -265,8 +250,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"); @@ -277,8 +261,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"); @@ -296,15 +279,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() { @@ -322,8 +305,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(); @@ -334,8 +316,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(); @@ -346,8 +327,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testFilePatternProperty() throws Exception { 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); @@ -361,39 +341,33 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { public void testMaxFileSizeProperty() throws Exception { 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, null, 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 testMaxFileSizePropertyWithXmlConfiguration() throws Exception { 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() 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, null, logFile); @@ -406,12 +380,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); @@ -420,13 +392,11 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { @Test public void exceptionsIncludeClassPackaging() throws Exception { 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")); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } @@ -436,16 +406,12 @@ 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"))); - String fileContents = FileCopyUtils - .copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); + this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); + String fileContents = FileCopyUtils.copyToString(new FileReader(new File(tmpDir() + "/spring.log"))); assertThat(fileContents).is(Matched.by(expectedOutput)); } finally { @@ -459,16 +425,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(); @@ -486,10 +449,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(); @@ -516,8 +477,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } private String getLineWithText(File file, String outputSearch) throws Exception { - return getLineWithText(FileCopyUtils.copyToString(new FileReader(file)), - outputSearch); + return getLineWithText(FileCopyUtils.copyToString(new FileReader(file)), outputSearch); } private String getLineWithText(String output, String outputSearch) { 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 158b081dbff..c1166494b27 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ -130,16 +129,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"); @@ -169,8 +166,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 78990f6b005..d9eca20c07b 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. @@ -44,8 +44,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); @@ -55,24 +54,21 @@ 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); verify(this.environment).acceptsProfiles("dev"); } @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); verify(this.environment).acceptsProfiles("dev", "qa"); } @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); @@ -82,8 +78,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 5386576f4fb..6ee21083d99 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 970d00c9e47..87e97e8cc8c 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. @@ -53,8 +53,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 59c566bac73..33b638db69e 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,18 +62,15 @@ public class SpringPhysicalNamingStrategyTests { @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(this.serviceRegistry) - .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/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java index bf8f077f5ef..fd59cd32536 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. @@ -58,38 +58,32 @@ public class ApplicationContextServerWebExchangeMatcherTests { @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); + Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(exchange); this.thrown.expect(NoSuchBeanDefinitionException.class); supplier.get(); } @Test public void matchesWhenContextIsNull() { - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/path").build()); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").build()); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("No ApplicationContext found on ServerWebExchange."); new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) @@ -98,11 +92,9 @@ public class ApplicationContextServerWebExchangeMatcherTests { 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 +104,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 +143,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 c63683c40f3..57c90038bb2 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. @@ -62,15 +62,14 @@ 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); + Supplier supplier = new TestApplicationContextRequestMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(context); this.thrown.expect(NoSuchBeanDefinitionException.class); supplier.get(); } @@ -79,8 +78,7 @@ public class ApplicationContextRequestMatcherTests { 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; } @@ -102,8 +100,7 @@ public class ApplicationContextRequestMatcherTests { } - static class TestApplicationContextRequestMatcher - extends ApplicationContextRequestMatcher { + static class TestApplicationContextRequestMatcher extends ApplicationContextRequestMatcher { private Supplier providedContext; @@ -111,14 +108,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/util/LambdaSafeTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java index c14094f821b..3f8d582a2ae 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. @@ -66,8 +66,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); } @@ -76,8 +75,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); } @@ -86,8 +84,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); } @@ -96,26 +93,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)); @@ -126,8 +119,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); @@ -139,8 +131,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); @@ -152,8 +143,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(); @@ -165,8 +155,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(); @@ -178,8 +167,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); @@ -193,8 +181,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(); } @@ -207,8 +194,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(); } @@ -217,9 +203,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); } @@ -229,8 +213,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); } @@ -240,8 +223,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); } @@ -251,8 +233,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); } @@ -260,23 +241,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)); } @@ -286,8 +262,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); } @@ -298,8 +273,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); } @@ -310,8 +285,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); } @@ -322,8 +297,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); } @@ -333,8 +308,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(); } @@ -347,8 +322,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(); } @@ -362,8 +337,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(); } @@ -385,8 +359,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); } @@ -396,8 +369,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); } @@ -406,13 +379,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/web/client/RestTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index 6bb75ee8dd0..87728b3f4db 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,15 +96,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 @@ -119,8 +117,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); @@ -143,15 +141,13 @@ public class RestTemplateBuilderTests { @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); } @@ -175,27 +171,21 @@ 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 @@ -220,8 +210,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); } @@ -242,12 +231,9 @@ public class RestTemplateBuilderTests { @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 @@ -259,18 +245,14 @@ public class RestTemplateBuilderTests { @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 @@ -297,8 +279,7 @@ public class RestTemplateBuilderTests { @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); } @@ -349,8 +330,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); } @@ -358,8 +339,8 @@ 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); } @@ -382,8 +363,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(); verify(customizer1).customize(template); verify(customizer2).customize(template); } @@ -404,97 +384,80 @@ 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 connectTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, - "requestConfig")).getConnectTimeout()).isEqualTo(1234); + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setConnectTimeout(1234).build() + .getRequestFactory(); + assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getConnectTimeout()) + .isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnHttpComponentsRequestFactory() { ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(HttpComponentsClientHttpRequestFactory.class) - .setReadTimeout(1234).build().getRequestFactory(); - assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, - "requestConfig")).getSocketTimeout()).isEqualTo(1234); + .requestFactory(HttpComponentsClientHttpRequestFactory.class).setReadTimeout(1234).build() + .getRequestFactory(); + assertThat(((RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig")).getSocketTimeout()) + .isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) .setConnectTimeout(1234).build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")) - .isEqualTo(1234); + assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")).isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnSimpleRequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(SimpleClientHttpRequestFactory.class).setReadTimeout(1234) - .build().getRequestFactory(); - assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")) - .isEqualTo(1234); + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(SimpleClientHttpRequestFactory.class) + .setReadTimeout(1234).build().getRequestFactory(); + assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")).isEqualTo(1234); } @Test public void connectTimeoutCanBeConfiguredOnOkHttp3RequestFactory() { - ClientHttpRequestFactory requestFactory = this.builder - .requestFactory(OkHttp3ClientHttpRequestFactory.class) + ClientHttpRequestFactory requestFactory = this.builder.requestFactory(OkHttp3ClientHttpRequestFactory.class) .setConnectTimeout(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(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 connectTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) - .setConnectTimeout(1234).build(); - assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")) - .isEqualTo(1234); + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)).setConnectTimeout(1234) + .build(); + assertThat(ReflectionTestUtils.getField(requestFactory, "connectTimeout")).isEqualTo(1234); } @Test public void readTimeoutCanBeConfiguredOnAWrappedRequestFactory() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); - this.builder - .requestFactory( - () -> new BufferingClientHttpRequestFactory(requestFactory)) - .setReadTimeout(1234).build(); - assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")) - .isEqualTo(1234); + this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)).setReadTimeout(1234) + .build(); + assertThat(ReflectionTestUtils.getField(requestFactory, "readTimeout")).isEqualTo(1234); } @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 f864ca0175e..4084f1a6a72 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 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 df5c7a29fba..db9a33f9e37 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +89,10 @@ public class WebServerPortFileWriterTest { listener.onApplicationEvent(mockEvent("management", 9090)); assertThat(FileCopyUtils.copyToString(new FileReader(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()); - FileReader reader = new FileReader( - new File(file.getParentFile(), managementFile)); + managementFile = managementFile.substring(0, + managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); + managementFile = managementFile + "-management." + StringUtils.getFilenameExtension(file.getName()); + FileReader reader = new FileReader(new File(file.getParentFile(), managementFile)); assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("9090"); assertThat(collectFileNames(file.getParentFile())).contains(managementFile); } @@ -106,12 +104,10 @@ 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()); - FileReader reader = new FileReader( - new File(file.getParentFile(), managementFile)); + managementFile = managementFile.substring(0, + managementFile.length() - StringUtils.getFilenameExtension(managementFile).length() - 1); + managementFile = managementFile + "-MANAGEMENT." + StringUtils.getFilenameExtension(file.getName()); + FileReader reader = new FileReader(new File(file.getParentFile(), managementFile)); assertThat(FileCopyUtils.copyToString(reader)).isEqualTo("9090"); assertThat(collectFileNames(file.getParentFile())).contains(managementFile); } @@ -119,8 +115,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 f88f0556c07..3f51e754763 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. @@ -39,8 +39,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() { @@ -85,10 +84,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()); } } 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 7528aa5bf9a..955e567d5a8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,8 +63,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() { @@ -128,14 +127,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 @@ -163,12 +159,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 @@ -178,12 +172,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) { @@ -199,8 +190,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); @@ -240,8 +230,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 @@ -250,8 +239,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 @@ -273,10 +261,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 @@ -291,10 +277,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 @@ -327,16 +311,14 @@ public class JettyServletWebServerFactoryTests jettyWebServer.start(); } finally { - QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer.getServer() - .getThreadPool(); + QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer.getServer().getThreadPool(); assertThat(threadPool.isRunning()).isFalse(); } } @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; @@ -348,22 +330,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 113d5792771..2faeb176393 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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); } @@ -58,12 +57,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 @@ -72,10 +69,8 @@ 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(); } private Server createCustomizedServer() { @@ -90,8 +85,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 ba45a8bdf36..7ec26887b3e 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() { 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 1250fa9231f..206979414be 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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(); } @@ -86,8 +85,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"); } @@ -102,11 +100,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 @@ -120,49 +116,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); @@ -171,8 +159,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"); @@ -180,8 +167,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(); @@ -189,8 +175,7 @@ public class SslConnectorCustomizerTests { assertThat(this.output.toString()).doesNotContain("Password verification failed"); } - 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 77a8710551c..b02a8d740f5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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() { @@ -78,8 +77,7 @@ public class TomcatReactiveWebServerFactoryTests @Test public void defaultTomcatListeners() { TomcatReactiveWebServerFactory factory = getFactory(); - assertThat(factory.getContextLifecycleListeners()).hasSize(1).first() - .isInstanceOf(AprLifecycleListener.class); + assertThat(factory.getContextLifecycleListeners()).hasSize(1).first().isInstanceOf(AprLifecycleListener.class); } @Test 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 9eea6d28215..84148ba2ab4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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(); @@ -108,8 +107,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()); } @@ -122,19 +120,16 @@ 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(); } @Test public void defaultTomcatListeners() { TomcatServletWebServerFactory factory = getFactory(); - assertThat(factory.getContextLifecycleListeners()).hasSize(1).first() - .isInstanceOf(AprLifecycleListener.class); + assertThat(factory.getContextLifecycleListeners()).hasSize(1).first().isInstanceOf(AprLifecycleListener.class); } @Test @@ -197,10 +192,8 @@ public class TomcatServletWebServerFactoryTests Arrays.setAll(listeners, (i) -> stoppedConnector()); factory.addAdditionalTomcatConnectors(listeners); this.webServer = factory.getWebServer(); - Map connectors = ((TomcatWebServer) this.webServer) - .getServiceConnectors(); - assertThat(connectors.values().iterator().next().length) - .isEqualTo(listeners.length + 1); + Map connectors = ((TomcatWebServer) this.webServer).getServiceConnectors(); + assertThat(connectors.values().iterator().next().length).isEqualTo(listeners.length + 1); } private Connector stoppedConnector() { @@ -284,8 +277,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"); } @@ -293,14 +285,12 @@ 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"); } @Test - public void primaryConnectorPortClashThrowsIllegalStateException() - throws IOException { + public void primaryConnectorPortClashThrowsIllegalStateException() throws IOException { doWithBlockedPort((port) -> { TomcatServletWebServerFactory factory = getFactory(); factory.setPort(port); @@ -316,12 +306,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 @@ -337,8 +325,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 @@ -369,8 +356,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) { @@ -415,8 +401,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"); } @@ -431,8 +416,7 @@ public class TomcatServletWebServerFactoryTests Tomcat tomcat = ((TomcatWebServer) this.webServer).getTomcat(); Context context = (Context) tomcat.getHost().findChildren()[0]; JarScanFilter jarScanFilter = context.getJarScanner().getJarScanFilter(); - Set tldSkipSet = (Set) ReflectionTestUtils.getField(jarScanFilter, - "tldSkipSet"); + Set tldSkipSet = (Set) ReflectionTestUtils.getField(jarScanFilter, "tldSkipSet"); assertThat(tldSkipSet).contains("foo.jar", "bar.jar"); } @@ -455,15 +439,14 @@ public class TomcatServletWebServerFactoryTests ((StandardContext) context).setFailCtxIfServletStartFails(true); } }); - 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.thrown.expect(WebServerException.class); this.webServer.start(); } @Test - public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() - throws IOException, URISyntaxException { + public void nonExistentUploadDirectoryIsCreatedUponMultipartUpload() throws IOException, URISyntaxException { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0); AtomicReference servletContextReference = new AtomicReference<>(); factory.addInitializers(new ServletContextInitializer() { @@ -474,8 +457,7 @@ public class TomcatServletWebServerFactoryTests Dynamic servlet = servletContext.addServlet("upload", new HttpServlet() { @Override - protected void doPost(HttpServletRequest req, - HttpServletResponse resp) + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getParts(); } @@ -488,18 +470,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); } @@ -518,16 +498,13 @@ public class TomcatServletWebServerFactoryTests @SuppressWarnings("unchecked") @Override protected Map getActualMimeMappings() { - Context context = (Context) ((TomcatWebServer) this.webServer).getTomcat() - .getHost().findChildren()[0]; - return (Map) ReflectionTestUtils.getField(context, - "mimeMappings"); + Context context = (Context) ((TomcatWebServer) this.webServer).getTomcat().getHost().findChildren()[0]; + return (Map) ReflectionTestUtils.getField(context, "mimeMappings"); } @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; @@ -545,8 +522,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 3d39def6b24..87a501e272f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,12 +41,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); } @@ -56,8 +54,7 @@ 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); try { ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); fail(); @@ -75,8 +72,7 @@ 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); try { ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null); fail(); 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 54d5e4443e6..aed920fdf19 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. @@ -46,8 +46,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(); @@ -89,14 +88,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 d7267905e0c..732b840cef5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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() { @@ -74,8 +73,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"); @@ -132,8 +130,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); @@ -151,8 +148,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("/"); } @@ -166,19 +162,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"); } @@ -191,8 +184,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); @@ -202,22 +194,20 @@ 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 { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); + this.thrown.expect(anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }); } @Test public void sslRestrictedProtocolsECDHETLS1Failure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); + this.thrown.expect(anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }); } @@ -236,8 +226,7 @@ public class UndertowServletWebServerFactoryTests @Test public void sslRestrictedProtocolsRSATLS11Failure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); + this.thrown.expect(anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" }); } @@ -255,11 +244,10 @@ public class UndertowServletWebServerFactoryTests } private ServletContainer getServletContainerFromNewFactory() { - UndertowServletWebServer container = (UndertowServletWebServer) getFactory() - .getWebServer(); + UndertowServletWebServer container = (UndertowServletWebServer) getFactory().getWebServer(); try { - return ((DeploymentManager) ReflectionTestUtils.getField(container, - "manager")).getDeployment().getServletContainer(); + return ((DeploymentManager) ReflectionTestUtils.getField(container, "manager")).getDeployment() + .getServletContainer(); } finally { container.stop(); @@ -268,8 +256,8 @@ public class UndertowServletWebServerFactoryTests @Override protected Map getActualMimeMappings() { - return ((DeploymentManager) ReflectionTestUtils.getField(this.webServer, - "manager")).getDeployment().getMimeExtensionMappings(); + return ((DeploymentManager) ReflectionTestUtils.getField(this.webServer, "manager")).getDeployment() + .getMimeExtensionMappings(); } @Override @@ -283,15 +271,14 @@ public class UndertowServletWebServerFactoryTests @Override protected Charset getCharset(Locale locale) { - DeploymentInfo info = ((DeploymentManager) ReflectionTestUtils - .getField(this.webServer, "manager")).getDeployment().getDeploymentInfo(); + DeploymentInfo info = ((DeploymentManager) ReflectionTestUtils.getField(this.webServer, "manager")) + .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); Object undertow = ReflectionTestUtils.getField(this.webServer, "undertow"); 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 86a598b827b..503339ef92c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 786f4c06f56..c67d22b1b6d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,23 +51,20 @@ import static org.assertj.core.api.Assertions.assertThat; */ 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); @Rule public ExpectedException thrown = ExpectedException.none(); private DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes(); - private List> readers = ServerCodecConfigurer.create() - .getReaders(); + private List> readers = ServerCodecConfigurer.create().getReaders(); @Test public void missingExceptionAttribute() { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Missing exception attribute in ServerWebExchange"); - MockServerWebExchange exchange = MockServerWebExchange - .from(MockServerHttpRequest.get("/test").build()); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); ServerRequest request = ServerRequest.create(exchange, this.readers); this.errorAttributes.getErrorAttributes(request, false); } @@ -75,8 +72,8 @@ public class DefaultErrorAttributesTests { @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); } @@ -84,10 +81,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); } @@ -95,10 +91,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()); } @@ -106,10 +101,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!"); } @@ -117,10 +111,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); } @@ -129,8 +122,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"); @@ -142,44 +134,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); } @@ -187,8 +172,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(); } @@ -196,16 +181,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"); } @@ -213,13 +197,12 @@ public class DefaultErrorAttributesTests { 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" @@ -227,8 +210,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 b634dc58f7d..8ad07a7a008 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 @@ -102,8 +102,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"); @@ -129,8 +128,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() @@ -139,14 +137,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { } protected ReactorClientHttpConnector buildTrustAllSslConnector() { - return new ReactorClientHttpConnector((options) -> options.sslSupport( - (sslContextBuilder) -> sslContextBuilder.sslProvider(SslProvider.JDK) - .trustManager(InsecureTrustManagerFactory.INSTANCE))); + return new ReactorClientHttpConnector((options) -> options.sslSupport((sslContextBuilder) -> sslContextBuilder + .sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE))); } @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"); @@ -165,11 +161,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()); @@ -178,12 +172,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { X509KeyManager x509KeyManager = (X509KeyManager) keyManager; PrivateKey privateKey = x509KeyManager.getPrivateKey("spring-boot"); if (privateKey != null) { - X509Certificate[] certificateChain = x509KeyManager - .getCertificateChain("spring-boot"); - return new ReactorClientHttpConnector((options) -> options - .sslSupport((sslContextBuilder) -> sslContextBuilder - .sslProvider(SslProvider.JDK) - .trustManager(InsecureTrustManagerFactory.INSTANCE) + X509Certificate[] certificateChain = x509KeyManager.getCertificateChain("spring-boot"); + return new ReactorClientHttpConnector( + (options) -> options.sslSupport((sslContextBuilder) -> sslContextBuilder + .sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE) .keyManager(privateKey, certificateChain))); } } @@ -191,14 +183,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() @@ -207,8 +197,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"); @@ -227,20 +216,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() { @@ -248,28 +234,25 @@ public abstract class AbstractReactiveWebServerFactoryTests { }); } - protected WebClient.Builder getWebClient( - Consumer clientOptions) { + protected WebClient.Builder getWebClient(Consumer clientOptions) { InetSocketAddress address = new InetSocketAddress(this.webServer.getPort()); String baseUrl = "http://" + address.getHostString() + ":" + address.getPort(); - return WebClient.builder() - .clientConnector(new ReactorClientHttpConnector(clientOptions)) - .baseUrl(baseUrl); + return WebClient.builder().clientConnector(new ReactorClientHttpConnector(clientOptions)).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); } @@ -279,8 +262,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { compression.setEnabled(true); compression.setMinResponseSize(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); } @@ -289,8 +272,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); } @@ -300,9 +283,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); } @@ -316,13 +298,11 @@ 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(); - return getWebClient((options) -> options.compression(true) - .afterChannelInit((channel) -> channel.pipeline().addBefore( - NettyPipeline.HttpDecompressor, "CompressionTest", - new CompressionDetectionHandler()))).build(); + return getWebClient((options) -> options.compression(true).afterChannelInit((channel) -> channel.pipeline() + .addBefore(NettyPipeline.HttpDecompressor, "CompressionTest", new CompressionDetectionHandler()))) + .build(); } protected void assertResponseIsCompressed(ResponseEntity response) { @@ -346,15 +326,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"); } 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 ce3d85fdf8e..025d27c4183 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. @@ -60,8 +60,8 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { @Test public void setBeanFactoryWhenNotListableShouldThrowException() { this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("WebServerCustomizerBeanPostProcessor can only " - + "be used with a ListableBeanFactory"); + this.thrown + .expectMessage("WebServerCustomizerBeanPostProcessor can only " + "be used with a ListableBeanFactory"); this.processor.setBeanFactory(mock(BeanFactory.class)); } @@ -159,8 +159,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) { @@ -195,18 +195,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 187ad34e3b8..73d0d144bed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 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 @@ -71,8 +70,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 @@ -86,8 +84,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); @@ -97,10 +94,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 @@ -123,8 +119,7 @@ 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 @@ -145,13 +140,11 @@ public abstract class AbstractFilterRegistrationBeanTests { @Test public void setServletRegistrationBeanReplacesValue() throws Exception { - AbstractFilterRegistrationBean bean = createFilterRegistrationBean( - mockServletRegistration("a")); - bean.setServletRegistrationBeans(new LinkedHashSet>( - Arrays.asList(mockServletRegistration("b")))); + AbstractFilterRegistrationBean bean = createFilterRegistrationBean(mockServletRegistration("a")); + bean.setServletRegistrationBeans( + new LinkedHashSet>(Arrays.asList(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 @@ -200,15 +193,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 00f4c490a3f..28c8bdd327f 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. @@ -42,8 +42,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<>(); @@ -66,8 +65,7 @@ public class DelegatingFilterProxyRegistrationBeanTests @Test public void nameDefaultsToTargetBeanName() { - assertThat(new DelegatingFilterProxyRegistrationBean("myFilter") - .getOrDeduceName(null)).isEqualTo("myFilter"); + assertThat(new DelegatingFilterProxyRegistrationBean("myFilter").getOrDeduceName(null)).isEqualTo("myFilter"); } @Test @@ -75,22 +73,18 @@ 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(); } @@ -98,15 +92,14 @@ public class DelegatingFilterProxyRegistrationBeanTests public void createServletRegistrationBeanMustNotBeNull() { this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("ServletRegistrationBeans must not be null"); - new DelegatingFilterProxyRegistrationBean("mockFilter", - (ServletRegistrationBean[]) null); + new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) 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; } @@ -123,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/FilterRegistrationIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationIntegrationTests.java index a4cd3cf6069..4a4082eccdb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 FilterRegistrationIntegrationTests { } private void load(Class configuration) { - this.context = new AnnotationConfigServletWebServerApplicationContext( - ContainerConfiguration.class, configuration); + this.context = new AnnotationConfigServletWebServerApplicationContext(ContainerConfiguration.class, + configuration); } @Configuration 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 a18656dc920..2deb7aae0c2 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 - @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 32c0b4c9736..fca5e8c2025 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,20 +54,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 @@ -75,8 +72,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 @@ -84,27 +80,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() { this.thrown.expect(AnnotationConfigurationException.class); - this.thrown.expectMessage(allOf(containsString("'value'"), - containsString("'basePackages'"), containsString("com.example.foo"), - containsString("com.example.bar"))); + this.thrown.expectMessage(allOf(containsString("'value'"), containsString("'basePackages'"), + containsString("com.example.foo"), containsString("com.example.bar"))); this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class); } @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 @@ -112,30 +104,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 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 a0d6171f8f2..a0c18bfee25 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 @@ -106,8 +106,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 b42df0cca10..fe9a6bc34a3 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. @@ -67,8 +67,7 @@ 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 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 f5a2e5b1636..7e53fc4f73d 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. @@ -67,16 +67,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); @@ -85,10 +82,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); @@ -159,8 +154,7 @@ public class ServletRegistrationBeanTests { @Test public void setMappingMustNotBeNull() { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("UrlMappings must not be null"); bean.setUrlMappings(null); @@ -175,8 +169,7 @@ public class ServletRegistrationBeanTests { @Test public void addMappingMustNotBeNull() { - ServletRegistrationBean bean = new ServletRegistrationBean<>( - this.servlet); + ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); this.thrown.expect(IllegalArgumentException.class); this.thrown.expectMessage("UrlMappings must not be null"); bean.addUrlMappings((String[]) null); @@ -184,8 +177,7 @@ public class ServletRegistrationBeanTests { @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"); @@ -193,8 +185,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); @@ -203,8 +194,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 07069ae7b51..e244fef1ef9 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 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()); @@ -69,20 +68,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(); @@ -91,8 +87,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); } @@ -100,63 +95,52 @@ 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 { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The urlPatterns and value attributes are mutually exclusive."); + this.thrown.expectMessage("The urlPatterns and value attributes are mutually exclusive."); getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class); } 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()); } @@ -171,14 +155,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 { } @@ -216,8 +198,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 9dda2215cdc..a5d866345c4 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,19 +53,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); } @@ -73,68 +69,53 @@ 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 { this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The urlPatterns and value attributes are mutually exclusive."); + this.thrown.expectMessage("The urlPatterns and value attributes are mutually exclusive."); getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class); } 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()); } @@ -149,8 +130,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 23c9587546a..d88db135bd5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,24 +52,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(); } @@ -102,8 +100,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(); } @@ -115,8 +112,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 @@ -124,18 +120,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); } @@ -162,8 +155,7 @@ public class AnnotationConfigServletWebServerApplicationContextTests { @Configuration @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 3e9f211800b..eb17f8ceb86 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. @@ -118,18 +118,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,8 +135,7 @@ public class ServletWebServerApplicationContextTests { // also be problematic in a classic WAR deployment. addWebServerFactoryBean(); this.context.refresh(); - Field shutdownHookField = AbstractApplicationContext.class - .getDeclaredField("shutdownHook"); + Field shutdownHookField = AbstractApplicationContext.class.getDeclaredField("shutdownHook"); shutdownHookField.setAccessible(true); Object shutdownHook = shutdownHookField.get(this.context); assertThat(shutdownHook).isNull(); @@ -149,11 +144,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); @@ -199,8 +192,7 @@ public class ServletWebServerApplicationContextTests { public void missingServletWebServerFactory() { this.thrown.expect(ApplicationContextException.class); this.thrown.expectMessage( - "Unable to start ServletWebServerApplicationContext due to missing " - + "ServletWebServerFactory bean"); + "Unable to start ServletWebServerApplicationContext due to missing " + "ServletWebServerFactory bean"); this.context.refresh(); } @@ -210,9 +202,8 @@ public class ServletWebServerApplicationContextTests { this.context.registerBeanDefinition("webServerFactory2", new RootBeanDefinition(MockServletWebServerFactory.class)); this.thrown.expect(ApplicationContextException.class); - this.thrown.expectMessage( - "Unable to start ServletWebServerApplicationContext due to " - + "multiple ServletWebServerFactory beans"); + this.thrown.expectMessage("Unable to start ServletWebServerApplicationContext due to " + + "multiple ServletWebServerFactory beans"); this.context.refresh(); } @@ -236,8 +227,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); @@ -248,11 +238,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)); @@ -262,24 +250,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(); @@ -287,19 +270,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)); @@ -312,10 +292,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 @@ -327,10 +307,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); @@ -342,8 +320,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); @@ -354,10 +331,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); @@ -365,14 +340,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(); @@ -387,10 +360,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(); @@ -404,8 +375,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(); @@ -413,34 +383,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 this.thrown.expect(BeanCreationException.class); this.thrown.expectMessage("Create FilterBean Failure"); 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()); } @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); @@ -449,8 +413,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); } @@ -464,10 +427,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 @@ -475,18 +436,14 @@ 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(new BeanFactoryPostProcessor() { @Override - public void postProcessBeanFactory( - ConfigurableListableBeanFactory beanFactory) throws BeansException { - WithAutowiredServletRequest bean = beanFactory - .getBean(WithAutowiredServletRequest.class); + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + WithAutowiredServletRequest bean = beanFactory.getBean(WithAutowiredServletRequest.class); assertThat(bean.getRequest()).isNotNull(); } @@ -500,8 +457,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() { @@ -530,8 +487,7 @@ public class ServletWebServerApplicationContextTests { return object; } - public static class MockListener - implements ApplicationListener { + public static class MockListener implements ApplicationListener { private ServletWebServerInitializedEvent event; @@ -550,8 +506,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 6cb44c8dd4a..676cfdb88a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,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 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 70cfd659b88..1ba97baa164 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 @@ -210,8 +210,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.stop(); this.thrown.expect(IOException.class); String response = getResponse(getLocalUrl(port, "/hello")); - throw new RuntimeException( - "Unexpected response on port " + port + " : " + response); + throw new RuntimeException("Unexpected response on port " + port + " : " + response); } @Test @@ -244,8 +243,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); @@ -258,8 +257,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); } @@ -278,8 +276,7 @@ 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 @@ -299,8 +296,7 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void contextRootPathMustNotBeSlash() { this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - "Root ContextPath must be specified using an empty string"); + this.thrown.expectMessage("Root ContextPath must be specified using an empty string"); getFactory().setContextPath("/"); } @@ -330,8 +326,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(); @@ -340,8 +335,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(); } @@ -349,8 +343,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"); @@ -360,13 +353,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 @@ -385,16 +375,12 @@ 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); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); this.thrown.expect(SSLException.class); getResponse(getLocalUrl("https", "/hello"), requestFactory); } @@ -403,18 +389,13 @@ public abstract class AbstractServletWebServerFactoryTests { 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 @@ -426,12 +407,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"); @@ -441,16 +420,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(); } @@ -459,16 +435,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"); } @@ -479,142 +452,102 @@ 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(), - new PrivateKeyStrategy() { + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "secret".toCharArray(), new PrivateKeyStrategy() { - @Override - public String chooseAlias( - Map aliases, - Socket socket) { - return "spring-boot"; - } + @Override + public String chooseAlias(Map aliases, Socket socket) { + return "spring-boot"; + } - }) - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + }).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()); + 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(), - new PrivateKeyStrategy() { + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "password".toCharArray(), new PrivateKeyStrategy() { - @Override - public String chooseAlias( - Map aliases, - Socket socket) { - return "spring-boot"; - } - }) - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + @Override + public String chooseAlias(Map aliases, Socket socket) { + return "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(expected = IOException.class) - 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); getResponse(getLocalUrl("https", "/test.txt"), 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")); 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 @@ -632,28 +565,19 @@ 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()); + 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(), - new PrivateKeyStrategy() { + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "password".toCharArray(), new PrivateKeyStrategy() { - @Override - public String chooseAlias( - Map aliases, - Socket socket) { - return "spring-boot"; - } - }) - .build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); - assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) - .isEqualTo("test"); + @Override + public String chooseAlias(Map aliases, Socket socket) { + return "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(); } @@ -680,20 +604,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) { @@ -721,26 +642,19 @@ 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/test.jks", null, - protocols, ciphers)); - this.webServer = factory.getWebServer( - new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); + factory.setSsl(getSsl(null, "password", "src/test/resources/test.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()); + new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( - httpClient); + HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) - .contains("scheme=https"); + assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)).contains("scheme=https"); } private String getStoreType(String keyStore) { @@ -749,8 +663,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 @@ -780,8 +693,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); } @@ -822,8 +734,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"); @@ -872,8 +783,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 @@ -882,15 +792,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(); } @@ -900,11 +808,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()); } @@ -945,14 +852,12 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void portClashOfPrimaryConnectorResultsInPortInUseException() - throws IOException { + public void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { try { AbstractServletWebServerFactory factory = getFactory(); factory.setPort(port); - AbstractServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); + AbstractServletWebServerFactoryTests.this.webServer = factory.getWebServer(); AbstractServletWebServerFactoryTests.this.webServer.start(); fail(); } @@ -963,14 +868,12 @@ public abstract class AbstractServletWebServerFactoryTests { } @Test - public void portClashOfSecondaryConnectorResultsInPortInUseException() - throws IOException { + public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { try { AbstractServletWebServerFactory factory = getFactory(); addConnector(port, factory); - AbstractServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); + AbstractServletWebServerFactoryTests.this.webServer = factory.getWebServer(); AbstractServletWebServerFactoryTests.this.webServer.start(); fail(); } @@ -1009,33 +912,31 @@ 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() { + } - })); + })); this.thrown.expect(WebServerException.class); factory.getWebServer().start(); } @@ -1044,8 +945,7 @@ public abstract class AbstractServletWebServerFactoryTests { 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"); @@ -1057,61 +957,48 @@ 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)); } - 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); @@ -1125,19 +1012,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; @@ -1151,10 +1036,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()); } @@ -1170,8 +1053,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); } @@ -1182,17 +1064,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); } } @@ -1202,18 +1081,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, @@ -1229,10 +1106,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"); @@ -1240,8 +1115,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"); @@ -1249,37 +1123,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) + ":" + 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) + ":" + value); + } - }, "/session"); + }, "/session"); bean.setName("session"); return bean; } @@ -1303,8 +1172,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()) { @@ -1320,8 +1188,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); @@ -1362,8 +1229,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; @@ -1372,8 +1238,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 418ce4e58ff..08850642365 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 3bc879ff2a8..60b06d0fd73 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,31 +68,27 @@ 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() { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("No SpringApplication sources have been defined"); - new MockSpringBootServletInitializer() - .createRootApplicationContext(this.servletContext); + new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext); } @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 @@ -105,8 +101,7 @@ public class SpringBootServletInitializerTests { @Test @SuppressWarnings("rawtypes") public void mainClassHasSensibleDefault() { - new WithConfigurationAnnotation() - .createRootApplicationContext(this.servletContext); + new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext); Class mainApplicationClass = (Class) new DirectFieldAccessor(this.application) .getPropertyValue("mainApplicationClass"); assertThat(mainApplicationClass).isEqualTo(WithConfigurationAnnotation.class); @@ -114,14 +109,12 @@ public class SpringBootServletInitializerTests { @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(); } @@ -132,8 +125,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); } } @@ -141,26 +133,21 @@ public class SpringBootServletInitializerTests { @Test public void servletContextPropertySourceIsAvailablePriorToRefresh() { ServletContext servletContext = mock(ServletContext.class); - given(servletContext.getInitParameterNames()).willReturn( - Collections.enumeration(Arrays.asList("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(Arrays.asList("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()); } } @@ -180,8 +167,7 @@ public class SpringBootServletInitializerTests { } - private class CustomSpringBootServletInitializer - extends MockSpringBootServletInitializer { + private class CustomSpringBootServletInitializer extends MockSpringBootServletInitializer { private final CustomSpringApplicationBuilder applicationBuilder = new CustomSpringApplicationBuilder(); @@ -191,8 +177,7 @@ public class SpringBootServletInitializerTests { } @Override - protected SpringApplicationBuilder configure( - SpringApplicationBuilder application) { + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Config.class); } @@ -206,16 +191,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 - public static class WithErrorPageFilterNotRegistered - extends SpringBootServletInitializer { + public static class WithErrorPageFilterNotRegistered extends SpringBootServletInitializer { public WithErrorPageFilterNotRegistered() { setRegisterErrorPageFilter(false); @@ -257,8 +240,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 546ff90607d..9651b8caed1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ 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-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/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 6467d50d07b..3da0353cb74 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. @@ -67,8 +67,7 @@ public class DevToolsIntegrationTests { public void launchApplication() throws Exception { this.serverPortFile.delete(); System.out.println("Launching " + this.javaLauncher.getClass()); - this.launchedApplication = this.applicationLauncher - .launchApplication(this.javaLauncher); + this.launchedApplication = this.applicationLauncher.launchApplication(this.javaLauncher); } @After @@ -80,25 +79,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()) @@ -109,16 +103,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"); } @@ -126,57 +117,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); @@ -187,18 +164,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); @@ -210,12 +184,9 @@ public class DevToolsIntegrationTests { System.out.println("Getting server port " + this.serverPortFile.length()); if (System.currentTimeMillis() > end) { throw new IllegalStateException(String.format( - "server.port file was not written within 30 seconds. " - + "Application output:%n%s%s", - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardOut())), - FileCopyUtils.copyToString(new FileReader( - this.launchedApplication.getStandardError())))); + "server.port file was not written within 30 seconds. " + "Application output:%n%s%s", + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardOut())), + FileCopyUtils.copyToString(new FileReader(this.launchedApplication.getStandardError())))); } Thread.sleep(100); } @@ -229,8 +200,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}") @@ -259,14 +229,12 @@ public class DevToolsIntegrationTests { } public void build() throws Exception { - Builder builder = new ByteBuddy().subclass(Object.class) - .name(this.name).annotateType(AnnotationDescription.Builder - .ofType(RestController.class).build()); + Builder 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/ExplodedRemoteApplicationLauncher.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java index 56920f8a924..c05ccdfc227 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-devtools-tests/src/test/java/org/springframework/boot/devtools/tests/ExplodedRemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ExplodedRemoteApplicationLauncher extends RemoteApplicationLauncher File appDirectory = new File("target/app"); FileSystemUtils.deleteRecursively(appDirectory); appDirectory.mkdirs(); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/app/com")); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/app/com")); List entries = new ArrayList<>(); entries.add("target/app"); for (File jar : new File("target/dependencies").listFiles()) { 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 5175e332d8a..55e2c2d0256 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,14 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher @Override protected String createApplicationClassPath() throws Exception { File appDirectory = new File("target/app"); - if (appDirectory.isDirectory() - && !FileSystemUtils.deleteRecursively(appDirectory.toPath())) { - throw new IllegalStateException( - "Failed to delete '" + appDirectory.getAbsolutePath() + "'"); + if (appDirectory.isDirectory() && !FileSystemUtils.deleteRecursively(appDirectory.toPath())) { + throw new IllegalStateException("Failed to delete '" + appDirectory.getAbsolutePath() + "'"); } appDirectory.mkdirs(); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); - JarOutputStream output = new JarOutputStream( - new FileOutputStream(new File(appDirectory, "app.jar")), manifest); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/app/com")); + JarOutputStream output = new JarOutputStream(new FileOutputStream(new File(appDirectory, "app.jar")), manifest); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/app/com")); addToJar(output, new File("target/app/"), new File("target/app/")); output.close(); List entries = new ArrayList<>(); @@ -61,20 +57,18 @@ public class JarFileRemoteApplicationLauncher extends RemoteApplicationLauncher for (File jar : new File("target/dependencies").listFiles()) { entries.add(jar.getAbsolutePath()); } - 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 be6b9b7b856..fcc151b6df6 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. @@ -40,20 +40,19 @@ class JvmLauncher implements TestRule { @Override public Statement apply(Statement base, Description description) { - this.outputDirectory = new File("target/output/" - + description.getMethodName().replaceAll("[^A-Za-z]+", "")); + this.outputDirectory = new File("target/output/" + description.getMethodName().replaceAll("[^A-Za-z]+", "")); this.outputDirectory.mkdirs(); return base; } LaunchedJvm launch(String name, String classpath, String... args) throws IOException { - List command = new ArrayList<>(Arrays - .asList(System.getProperty("java.home") + "/bin/java", "-cp", classpath)); + List 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 remoteProcessRestarter; - LaunchedApplication(File classesDirectory, File standardOut, File standardError, - Process localProcess, Process remoteProcess, - BiFunction remoteProcessRestarter) { + LaunchedApplication(File classesDirectory, File standardOut, File standardError, Process localProcess, + Process remoteProcess, BiFunction 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 dfbcf7e91a7..1008556aeff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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 @@ import org.springframework.util.StringUtils; public class LocalApplicationLauncher implements ApplicationLauncher { @Override - public LaunchedApplication launchApplication(JvmLauncher jvmLauncher) - throws Exception { + public LaunchedApplication launchApplication(JvmLauncher jvmLauncher) throws Exception { LaunchedJvm jvm = jvmLauncher.launch("local", createApplicationClassPath(), "com.example.DevToolsTestApplication", "--server.port=0"); - return new LaunchedApplication(new File("target/app"), jvm.getStandardOut(), - jvm.getStandardError(), jvm.getProcess(), null, null); + return new LaunchedApplication(new File("target/app"), jvm.getStandardOut(), jvm.getStandardError(), + jvm.getProcess(), null, null); } protected String createApplicationClassPath() throws Exception { File appDirectory = new File("target/app"); FileSystemUtils.deleteRecursively(appDirectory); appDirectory.mkdirs(); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/app/com")); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/app/com")); List entries = new ArrayList<>(); entries.add("target/app"); for (File jar : new File("target/dependencies").listFiles()) { 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 3f9cebe05f9..27edc1ed55d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author 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,29 +37,22 @@ import org.springframework.util.StringUtils; abstract class RemoteApplicationLauncher implements ApplicationLauncher { @Override - public LaunchedApplication launchApplication(JvmLauncher javaLauncher) - throws Exception { - LaunchedJvm applicationJvm = javaLauncher.launch("app", - createApplicationClassPath(), "com.example.DevToolsTestApplication", - "--server.port=0", "--spring.devtools.remote.secret=secret"); + public LaunchedApplication launchApplication(JvmLauncher javaLauncher) throws Exception { + LaunchedJvm applicationJvm = javaLauncher.launch("app", createApplicationClassPath(), + "com.example.DevToolsTestApplication", "--server.port=0", "--spring.devtools.remote.secret=secret"); int port = awaitServerPort(applicationJvm.getStandardOut()); - BiFunction remoteRestarter = getRemoteRestarter( - javaLauncher); - return new LaunchedApplication(new File("target/remote"), - applicationJvm.getStandardOut(), applicationJvm.getStandardError(), - applicationJvm.getProcess(), remoteRestarter.apply(port, null), + BiFunction remoteRestarter = getRemoteRestarter(javaLauncher); + return new LaunchedApplication(new File("target/remote"), applicationJvm.getStandardOut(), + applicationJvm.getStandardError(), applicationJvm.getProcess(), remoteRestarter.apply(port, null), remoteRestarter); } - private BiFunction getRemoteRestarter( - JvmLauncher javaLauncher) { + private BiFunction 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(); @@ -72,14 +65,12 @@ abstract class RemoteApplicationLauncher implements ApplicationLauncher { protected abstract String createApplicationClassPath() throws Exception; - private String createRemoteSpringApplicationClassPath(File classesDirectory) - throws Exception { + private String createRemoteSpringApplicationClassPath(File classesDirectory) throws Exception { if (classesDirectory == null) { File remoteDirectory = new File("target/remote"); FileSystemUtils.deleteRecursively(remoteDirectory); remoteDirectory.mkdirs(); - FileSystemUtils.copyRecursively(new File("target/test-classes/com"), - new File("target/remote/com")); + FileSystemUtils.copyRecursively(new File("target/test-classes/com"), new File("target/remote/com")); } List entries = new ArrayList<>(); entries.add("target/remote"); @@ -95,8 +86,7 @@ abstract class RemoteApplicationLauncher implements ApplicationLauncher { 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); @@ -110,16 +100,13 @@ abstract class RemoteApplicationLauncher implements ApplicationLauncher { 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 d42491c8a2b..5cb235471cd 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 @@ -219,12 +209,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 @@ -275,10 +262,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) { @@ -304,17 +289,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 items = new ArrayList<>(); @@ -331,8 +313,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(); } @@ -344,8 +325,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; } @@ -364,38 +345,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; } @@ -426,15 +399,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 { + private static final class CopyToContainerCmdExec extends AbstrSyncDockerCmdExec { - private CopyToContainerCmdExec(WebTarget baseResource, - DockerClientConfig dockerClientConfig) { + private CopyToContainerCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) { super(baseResource, dockerClientConfig); } @@ -442,12 +412,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; } @@ -484,8 +452,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 7558f0c99e5..288b680d407 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("target/server.port")).run(args); } @Bean public ServletRegistrationBean resourceServletRegistration() { - ServletRegistrationBean registration = new ServletRegistrationBean( - new HttpServlet() { + ServletRegistrationBean registration = new ServletRegistrationBean(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 a2082ed63f8..62b0214e52d 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. @@ -70,16 +70,14 @@ abstract class AbstractApplicationLauncher extends ExternalResource { private Process startApplication() throws Exception { File workingDirectory = getWorkingDirectory(); - File serverPortFile = (workingDirectory != null) - ? new File(workingDirectory, "target/server.port") + File serverPortFile = (workingDirectory != null) ? new File(workingDirectory, "target/server.port") : new File("target/server.port"); serverPortFile.delete(); File archive = this.applicationBuilder.buildApplication(); List arguments = new ArrayList<>(); arguments.add(System.getProperty("java.home") + "/bin/java"); arguments.addAll(getArguments(archive)); - ProcessBuilder processBuilder = new ProcessBuilder( - StringUtils.toStringArray(arguments)); + ProcessBuilder processBuilder = new ProcessBuilder(StringUtils.toStringArray(arguments)); if (workingDirectory != null) { processBuilder.directory(workingDirectory); } @@ -94,16 +92,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 5ab0edc91a6..bcddc7f47f5 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. @@ -65,15 +65,12 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { private static List createParameters(String packaging, String container, List> applicationLaunchers) { List parameters = new ArrayList<>(); - ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, - packaging, container); + ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, packaging, container); for (Class launcherClass : applicationLaunchers) { try { - AbstractApplicationLauncher launcher = launcherClass - .getDeclaredConstructor(ApplicationBuilder.class) + AbstractApplicationLauncher launcher = launcherClass.getDeclaredConstructor(ApplicationBuilder.class) .newInstance(applicationBuilder); - 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) { @@ -83,8 +80,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() { @@ -103,14 +99,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 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 dcc9182cfda..87eb4478ff3 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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,9 +61,7 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { for (File dependency : dependencies.listFiles()) { classpath.add(dependency.getAbsolutePath()); } - return Arrays.asList("-cp", - StringUtils.collectionToDelimitedString(classpath, - File.pathSeparator), + return Arrays.asList("-cp", StringUtils.collectionToDelimitedString(classpath, File.pathSeparator), "com.example.ResourceHandlingApplication"); } catch (IOException ex) { @@ -107,13 +105,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 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 entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void metaInfResourceFromDependencyIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity 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 entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedMetaInfResourceIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedJarIsNotAvailableViaHttp() { - ResponseEntity entity = this.rest - .getForEntity("/BOOT-INF/lib/resources-1.0.jar", String.class); + ResponseEntity 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 entity = this.rest.getForEntity( - "/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", - String.class); + ResponseEntity 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 entity = this.rest.getForEntity( - "/org/springframework/boot/loader/Launcher.class", String.class); + ResponseEntity 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 entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void metaInfResourceFromDependencyIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void webappResourcesAreAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", - String.class); + ResponseEntity 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 entity = this.rest - .getForEntity("/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/nested-meta-inf-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedMetaInfResourceIsAvailableViaServletContext() { - ResponseEntity entity = this.rest.getForEntity( - "/servletContext?/nested-meta-inf-resource.txt", String.class); + ResponseEntity entity = this.rest.getForEntity("/servletContext?/nested-meta-inf-resource.txt", + String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void nestedJarIsNotAvailableViaHttp() { - ResponseEntity entity = this.rest - .getForEntity("/WEB-INF/lib/resources-1.0.jar", String.class); + ResponseEntity 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 entity = this.rest.getForEntity( - "/WEB-INF/classes/com/example/ResourceHandlingApplication.class", - String.class); + ResponseEntity 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 entity = this.rest.getForEntity("/webapp-resource.txt", - String.class); + ResponseEntity entity = this.rest.getForEntity("/webapp-resource.txt", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void loaderClassesAreNotAvailableViaHttp() { - ResponseEntity entity = this.rest.getForEntity( - "/org/springframework/boot/loader/Launcher.class", String.class); + ResponseEntity 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 674a2da187b..b8f8288128e 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-2017 the original author or authors. + * Copyright 2012-2019 the original author 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 ExplodedApplicationLauncher extends AbstractApplicationLauncher { @Override protected List getArguments(File archive) { - 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 ec46a064ab6..c70ccd5a77e 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. @@ -73,9 +73,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { classpath.add(dependency.getAbsolutePath()); } classpath.add(resourcesProject.getAbsolutePath()); - return Arrays.asList("-cp", - StringUtils.collectionToDelimitedString(classpath, - File.pathSeparator), + return Arrays.asList("-cp", StringUtils.collectionToDelimitedString(classpath, File.pathSeparator), "com.example.ResourceHandlingApplication"); } catch (IOException ex) { @@ -107,8 +105,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { } private File explodedResourcesProject(File dependencies) throws IOException { - File resourcesProject = new File(this.exploded, - "resources-project/target/classes"); + File resourcesProject = new File(this.exploded, "resources-project/target/classes"); File resourcesJar = new File(dependencies, "resources-1.0.jar"); explodeArchive(resourcesJar, resourcesProject); resourcesJar.delete(); @@ -128,13 +125,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 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/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) {