Merge branch '1.5.x' into 2.0.x

pull/17198/head
Andy Wilkinson 6 years ago
commit c6c139d980

@ -24,7 +24,7 @@
</property>
</activation>
<properties>
<spring-javaformat.version>0.0.9</spring-javaformat.version>
<spring-javaformat.version>0.0.11</spring-javaformat.version>
<nohttp-checkstyle.version>0.0.1.RELEASE</nohttp-checkstyle.version>
</properties>
<build>

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<? extends Annotation> annotationType;
protected OnEndpointElementCondition(String prefix,
Class<? extends Annotation> annotationType) {
protected OnEndpointElementCondition(String prefix, Class<? extends Annotation> 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));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<RabbitHealthIndicator, RabbitTemplate> {
public class RabbitHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<RabbitHealthIndicator, RabbitTemplate> {
private final Map<String, RabbitTemplate> rabbitTemplates;
public RabbitHealthIndicatorAutoConfiguration(
Map<String, RabbitTemplate> rabbitTemplates) {
public RabbitHealthIndicatorAutoConfiguration(Map<String, RabbitTemplate> rabbitTemplates) {
this.rabbitTemplates = rabbitTemplates;
}

@ -44,8 +44,7 @@ public class AuditAutoConfiguration {
private final AuditEventRepository auditEventRepository;
public AuditAutoConfiguration(
ObjectProvider<AuditEventRepository> auditEventRepository) {
public AuditAutoConfiguration(ObjectProvider<AuditEventRepository> 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();

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<CassandraHealthIndicator, CassandraOperations> {
@AutoConfigureAfter({ CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class })
public class CassandraHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<CassandraHealthIndicator, CassandraOperations> {
private final Map<String, CassandraOperations> cassandraOperations;
public CassandraHealthIndicatorAutoConfiguration(
Map<String, CassandraOperations> cassandraOperations) {
public CassandraHealthIndicatorAutoConfiguration(Map<String, CassandraOperations> cassandraOperations) {
this.cassandraOperations = cassandraOperations;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<OperationInvokerAdvisor> invokerAdvisors,
ParameterValueMapper parameterValueMapper, EndpointMediaTypes endpointMediaTypes,
PathMapper endpointPathMapper, Collection<OperationInvokerAdvisor> invokerAdvisors,
Collection<EndpointFilter<ExposableWebEndpoint>> 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);
}
}

@ -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 {
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<String, Object> 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> T getRequired(Map<String, Object> map, String key, Class<T> 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,

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<SecurityResponse> SUCCESS = Mono
.just(SecurityResponse.success());
private static final Mono<SecurityResponse> 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");
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ExposableWebEndpoint> endpoints,
EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration,
CloudFoundrySecurityInterceptor securityInterceptor,
Collection<ExposableWebEndpoint> 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<ResponseEntity<Object>> 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<String, Link> 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<String, Link> links = this.linksResolver.resolveLinks(request.getURI().toString());
return new ResponseEntity<>(Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)),
HttpStatus.OK);
});
}
private Map<String, Link> getAccessibleLinks(AccessLevel accessLevel,
Map<String, Link> links) {
private Map<String, Link> getAccessibleLinks(AccessLevel accessLevel, Map<String, Link> 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<ResponseEntity<Object>> handle(ServerWebExchange exchange,
Map<String, String> body) {
return this.securityInterceptor
.preHandle(exchange, this.endpointId.toLowerCaseString())
.flatMap((securityResponse) -> flatMapResponse(exchange, body,
securityResponse));
public Mono<ResponseEntity<Object>> handle(ServerWebExchange exchange, Map<String, String> body) {
return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString())
.flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse));
}
private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange,
Map<String, String> body, SecurityResponse securityResponse) {
private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange, Map<String, String> body,
SecurityResponse securityResponse) {
if (!securityResponse.getStatus().equals(HttpStatus.OK)) {
return Mono.just(new ResponseEntity<>(securityResponse.getStatus()));
}

@ -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<ExposableWebEndpoint> webEndpoints = endpointDiscoverer.getEndpoints();
List<ExposableEndpoint<?>> 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);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<String> 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<AccessLevel> 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<? extends Map<String, String>> 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<String, String> extractTokenKeys(Map<String, Object> response) {
@ -141,11 +134,9 @@ class ReactiveCloudFoundrySecurityService {
* @return the UAA url Mono
*/
public Mono<String> 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<Void> 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<Void> 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<Void> 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<String, String> 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<Void> 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<Void> 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<Void> 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();
}

@ -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<ExposableWebEndpoint> webEndpoints = discoverer.getEndpoints();
List<ExposableEndpoint<?>> 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<WebSecurity> {
public static class IgnoredPathsWebSecurityConfigurer implements WebSecurityConfigurer<WebSecurity> {
@Override
public void init(WebSecurity builder) throws Exception {
builder.ignoring().requestMatchers(
new AntPathRequestMatcher("/cloudfoundryapplication/**"));
builder.ignoring().requestMatchers(new AntPathRequestMatcher("/cloudfoundryapplication/**"));
}
@Override

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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");
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<String, String> 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) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ExposableWebEndpoint> endpoints,
EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration,
CloudFoundrySecurityInterceptor securityInterceptor,
Collection<ExposableWebEndpoint> 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<String, Map<String, Link>> links(HttpServletRequest request,
HttpServletResponse response) {
SecurityResponse securityResponse = this.securityInterceptor.preHandle(request,
null);
protected Map<String, Map<String, Link>> 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<String, Link> links = this.linksResolver
.resolveLinks(request.getRequestURL().toString());
AccessLevel accessLevel = (AccessLevel) request.getAttribute(AccessLevel.REQUEST_ATTRIBUTE);
Map<String, Link> links = this.linksResolver.resolveLinks(request.getRequestURL().toString());
Map<String, Link> 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<String, String> 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<Object>(securityResponse.getMessage(),
securityResponse.getStatus());
return new ResponseEntity<Object>(securityResponse.getMessage(), securityResponse.getStatus());
}
return this.delegate.handle(request, body);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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");
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<String, ContextConditionEvaluation> 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<String, ContextConditionEvaluation> contexts;
private ApplicationConditionEvaluation(
Map<String, ContextConditionEvaluation> contexts) {
private ApplicationConditionEvaluation(Map<String, ContextConditionEvaluation> 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<MessageAndCondition> target = (conditionAndOutcome.getOutcome()
.isMatch() ? this.matched : this.notMatched);
List<MessageAndCondition> target = (conditionAndOutcome.getOutcome().isMatch() ? this.matched
: this.notMatched);
target.add(new MessageAndCondition(conditionAndOutcome));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ElasticsearchHealthIndicator, Client> {
static class ElasticsearchClientHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<ElasticsearchHealthIndicator, Client> {
private final Map<String, Client> 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<ElasticsearchJestHealthIndicator, JestClient> {
static class ElasticsearchJestHealthIndicatorConfiguration
extends CompositeHealthIndicatorConfiguration<ElasticsearchJestHealthIndicator, JestClient> {
private final Map<String, JestClient> clients;
@ -107,8 +106,7 @@ public class ElasticsearchHealthIndicatorAutoConfiguration {
}
@Override
protected ElasticsearchJestHealthIndicator createHealthIndicator(
JestClient client) {
protected ElasticsearchJestHealthIndicator createHealthIndicator(JestClient client) {
return new ElasticsearchJestHealthIndicator(client);
}

@ -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 {
/**

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<EndpointId, Long>
@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> duration = Binder.get(this.environment).bind(name, DURATION);
return duration.map(Duration::toMillis).orElse(null);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<E extends ExposableEndpoint<?>>
implements EndpointFilter<E> {
public class ExposeExcludePropertyEndpointFilter<E extends ExposableEndpoint<?>> implements EndpointFilter<E> {
private final Class<E> endpointType;
@ -53,8 +52,8 @@ public class ExposeExcludePropertyEndpointFilter<E extends ExposableEndpoint<?>>
private final Set<String> exposeDefaults;
public ExposeExcludePropertyEndpointFilter(Class<E> endpointType,
Environment environment, String prefix, String... exposeDefaults) {
public ExposeExcludePropertyEndpointFilter(Class<E> 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<E extends ExposableEndpoint<?>>
this.exposeDefaults = asSet(Arrays.asList(exposeDefaults));
}
public ExposeExcludePropertyEndpointFilter(Class<E> endpointType,
Collection<String> include, Collection<String> exclude,
String... exposeDefaults) {
public ExposeExcludePropertyEndpointFilter(Class<E> endpointType, Collection<String> include,
Collection<String> 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<E extends ExposableEndpoint<?>>
}
private Set<String> 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<String> cleanup(List<String> values) {
@ -85,8 +82,7 @@ public class ExposeExcludePropertyEndpointFilter<E extends ExposableEndpoint<?>>
}
private String cleanup(String value) {
return "*".equals(value) ? "*"
: EndpointId.fromPropertyValue(value).toLowerCaseString();
return "*".equals(value) ? "*" : EndpointId.fromPropertyValue(value).toLowerCaseString();
}
private Set<String> asSet(Collection<String> items) {
@ -107,8 +103,7 @@ public class ExposeExcludePropertyEndpointFilter<E extends ExposableEndpoint<?>>
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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<Environment, Optional<Boolean>> 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<Boolean> 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<String, Object> attributes = metadata
.getAnnotationAttributes(ConditionalOnEnabledEndpoint.class.getName());
Map<String, Object> 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"));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<Collection<OperationInvokerAdvisor>> invokerAdvisors,
ObjectProvider<Collection<EndpointFilter<ExposableJmxEndpoint>>> 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> objectMapper,
public JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, ObjectProvider<ObjectMapper> 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<ExposableJmxEndpoint> 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(), "*");
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<String, String> 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);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ExposableServletEndpoint> 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());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<String> MEDIA_TYPES = Arrays
.asList(ActuatorMediaType.V2_JSON, "application/json");
private static final List<String> 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<Collection<OperationInvokerAdvisor>> invokerAdvisors,
ObjectProvider<Collection<EndpointFilter<ExposableWebEndpoint>>> 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<Collection<EndpointFilter<ExposableControllerEndpoint>>> 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<EndpointsSupplier<?>> endpointSuppliers,
public PathMappedEndpoints pathMappedEndpoints(Collection<EndpointsSupplier<?>> endpointSuppliers,
WebEndpointProperties webEndpointProperties) {
return new PathMappedEndpoints(webEndpointProperties.getBasePath(),
endpointSuppliers);
return new PathMappedEndpoints(webEndpointProperties.getBasePath(), endpointSuppliers);
}
@Bean
public ExposeExcludePropertyEndpointFilter<ExposableWebEndpoint> 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<ExposableControllerEndpoint> 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<Collection<EndpointFilter<ExposableServletEndpoint>>> filters) {
return new ServletEndpointDiscoverer(applicationContext,
webEndpointPathMapper,
return new ServletEndpointDiscoverer(applicationContext, webEndpointPathMapper,
filters.getIfAvailable(Collections::emptyList));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
allEndpoints.addAll(webEndpointsSupplier.getEndpoints());
@ -71,10 +69,8 @@ class JerseyWebEndpointManagementContextConfiguration {
EndpointMapping endpointMapping = new EndpointMapping(basePath);
Collection<ExposableWebEndpoint> 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))));
};
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ExposableWebEndpoint> endpoints = webEndpointsSupplier.getEndpoints();
List<ExposableEndpoint<?>> 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());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier
.getEndpoints();
Collection<ExposableWebEndpoint> 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());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<H extends HealthIndi
if (beans.size() == 1) {
return createHealthIndicator(beans.values().iterator().next());
}
CompositeHealthIndicator composite = new CompositeHealthIndicator(
this.healthAggregator);
beans.forEach((name, source) -> 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<H> indicatorClass = (Class<H>) generics[0];
Class<S> sourceClass = (Class<S>) generics[1];
@ -60,8 +57,8 @@ public abstract class CompositeHealthIndicatorConfiguration<H extends HealthIndi
return indicatorClass.getConstructor(sourceClass).newInstance(source);
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create indicator " + indicatorClass
+ " for source " + sourceClass, ex);
throw new IllegalStateException(
"Unable to create indicator " + indicatorClass + " for source " + sourceClass, ex);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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 abstract class CompositeReactiveHealthIndicatorConfiguration<H extends Re
if (beans.size() == 1) {
return createHealthIndicator(beans.values().iterator().next());
}
CompositeReactiveHealthIndicator composite = new CompositeReactiveHealthIndicator(
this.healthAggregator);
beans.forEach((name, source) -> 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<H> indicatorClass = (Class<H>) generics[0];
Class<S> sourceClass = (Class<S>) generics[1];
@ -59,8 +56,8 @@ public abstract class CompositeReactiveHealthIndicatorConfiguration<H extends Re
return indicatorClass.getConstructor(sourceClass).newInstance(source);
}
catch (Exception ex) {
throw new IllegalStateException("Unable to create indicator " + indicatorClass
+ " for source " + sourceClass, ex);
throw new IllegalStateException(
"Unable to create indicator " + indicatorClass + " for source " + sourceClass, ex);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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.context.annotation.Import;
* @since 2.0.0
*/
@Configuration
@EnableConfigurationProperties({ HealthEndpointProperties.class,
HealthIndicatorProperties.class })
@EnableConfigurationProperties({ HealthEndpointProperties.class, HealthIndicatorProperties.class })
@AutoConfigureAfter(HealthIndicatorAutoConfiguration.class)
@Import({ HealthEndpointConfiguration.class,
HealthEndpointWebExtensionConfiguration.class })
@Import({ HealthEndpointConfiguration.class, HealthEndpointWebExtensionConfiguration.class })
public class HealthEndpointAutoConfiguration {
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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 HealthEndpointWebExtensionConfiguration {
@Bean
@ConditionalOnMissingBean
public HealthStatusHttpMapper createHealthStatusHttpMapper(
HealthIndicatorProperties healthIndicatorProperties) {
public HealthStatusHttpMapper createHealthStatusHttpMapper(HealthIndicatorProperties healthIndicatorProperties) {
HealthStatusHttpMapper statusHttpMapper = new HealthStatusHttpMapper();
if (healthIndicatorProperties.getHttpMapping() != null) {
statusHttpMapper.addStatusMapping(healthIndicatorProperties.getHttpMapping());
@ -62,11 +61,10 @@ class HealthEndpointWebExtensionConfiguration {
@Bean
@ConditionalOnMissingBean
public HealthWebEndpointResponseMapper healthWebEndpointResponseMapper(
HealthStatusHttpMapper statusHttpMapper,
public HealthWebEndpointResponseMapper healthWebEndpointResponseMapper(HealthStatusHttpMapper statusHttpMapper,
HealthEndpointProperties properties) {
return new HealthWebEndpointResponseMapper(statusHttpMapper,
properties.getShowDetails(), properties.getRoles());
return new HealthWebEndpointResponseMapper(statusHttpMapper, properties.getShowDetails(),
properties.getRoles());
}
@Configuration
@ -78,12 +76,10 @@ class HealthEndpointWebExtensionConfiguration {
ReactiveWebHealthConfiguration(ObjectProvider<HealthAggregator> healthAggregator,
ObjectProvider<Map<String, ReactiveHealthIndicator>> reactiveHealthIndicators,
ObjectProvider<Map<String, HealthIndicator>> 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<String, HealthIndicator> 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<List<InfoContributor>> infoContributors) {
public InfoEndpoint infoEndpoint(ObjectProvider<List<InfoContributor>> infoContributors) {
return new InfoEndpoint(infoContributors.getIfAvailable(Collections::emptyList));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<DataSourceHealthIndicator, DataSource>
implements InitializingBean {
CompositeHealthIndicatorConfiguration<DataSourceHealthIndicator, DataSource> implements InitializingBean {
private final Map<String, DataSource> dataSources;
@ -71,15 +70,13 @@ public class DataSourceHealthIndicatorAutoConfiguration extends
private DataSourcePoolMetadataProvider poolMetadataProvider;
public DataSourceHealthIndicatorAutoConfiguration(
ObjectProvider<Map<String, DataSource>> dataSources,
public DataSourceHealthIndicatorAutoConfiguration(ObjectProvider<Map<String, DataSource>> dataSources,
ObjectProvider<Collection<DataSourcePoolMetadataProvider>> metadataProviders) {
this.dataSources = filterDataSources(dataSources.getIfAvailable());
this.metadataProviders = metadataProviders.getIfAvailable();
}
private Map<String, DataSource> filterDataSources(
Map<String, DataSource> candidates) {
private Map<String, DataSource> filterDataSources(Map<String, DataSource> 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<JmsHealthIndicator, ConnectionFactory> {
public class JmsHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<JmsHealthIndicator, ConnectionFactory> {
private final Map<String, ConnectionFactory> connectionFactories;
public JmsHealthIndicatorAutoConfiguration(
ObjectProvider<Map<String, ConnectionFactory>> connectionFactories) {
public JmsHealthIndicatorAutoConfiguration(ObjectProvider<Map<String, ConnectionFactory>> connectionFactories) {
this.connectionFactories = connectionFactories.getIfAvailable();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<EndpointServlet> {
@Override
public EndpointServlet get() {
return new EndpointServlet(AgentServlet.class)
.withInitParameters(this.initParameters);
return new EndpointServlet(AgentServlet.class).withInitParameters(this.initParameters);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<LdapHealthIndicator, LdapOperations> {
public class LdapHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<LdapHealthIndicator, LdapOperations> {
private final Map<String, LdapOperations> ldapOperations;
public LdapHealthIndicatorAutoConfiguration(
Map<String, LdapOperations> ldapOperations) {
public LdapHealthIndicatorAutoConfiguration(Map<String, LdapOperations> ldapOperations) {
this.ldapOperations = ldapOperations;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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"));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author 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<MailHealthIndicator, JavaMailSenderImpl> {
public class MailHealthIndicatorAutoConfiguration
extends CompositeHealthIndicatorConfiguration<MailHealthIndicator, JavaMailSenderImpl> {
private final Map<String, JavaMailSenderImpl> mailSenders;
public MailHealthIndicatorAutoConfiguration(
ObjectProvider<Map<String, JavaMailSenderImpl>> mailSenders) {
public MailHealthIndicatorAutoConfiguration(ObjectProvider<Map<String, JavaMailSenderImpl>> mailSenders) {
this.mailSenders = mailSenders.getIfAvailable();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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 {

@ -42,8 +42,7 @@ class CompositeMeterRegistryConfiguration {
@Bean
@Primary
public CompositeMeterRegistry compositeMeterRegistry(Clock clock,
List<MeterRegistry> registries) {
public CompositeMeterRegistry compositeMeterRegistry(Clock clock, List<MeterRegistry> registries) {
return new CompositeMeterRegistry(clock, registries);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<MeterBinder> binders,
Collection<MeterFilter> filters,
Collection<MeterRegistryCustomizer<?>> customizers,
boolean addToGlobalRegistry) {
MeterRegistryConfigurer(Collection<MeterBinder> binders, Collection<MeterFilter> filters,
Collection<MeterRegistryCustomizer<?>> 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) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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());

@ -71,13 +71,11 @@ public class MetricsAutoConfiguration {
}
@Bean
public static MeterRegistryPostProcessor meterRegistryPostProcessor(
ObjectProvider<List<MeterBinder>> meterBinders,
public static MeterRegistryPostProcessor meterRegistryPostProcessor(ObjectProvider<List<MeterBinder>> meterBinders,
ObjectProvider<List<MeterFilter>> meterFilters,
ObjectProvider<List<MeterRegistryCustomizer<?>>> meterRegistryCustomizers,
ObjectProvider<MetricsProperties> 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()));
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<MissingRequiredConfigurationException> {
@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(".")) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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 {
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<String, CacheManager> cacheManagers;
CacheMetricsRegistrarConfiguration(MeterRegistry registry,
Collection<CacheMeterBinderProvider<?>> binderProviders,
CacheMetricsRegistrarConfiguration(MeterRegistry registry, Collection<CacheMeterBinderProvider<?>> binderProviders,
Map<String, CacheManager> 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;
}

@ -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 {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<AtlasProperties>
implements AtlasConfig {
class AtlasPropertiesConfigAdapter extends PropertiesConfigAdapter<AtlasProperties> implements AtlasConfig {
AtlasPropertiesConfigAdapter(AtlasProperties properties) {
super(properties);
@ -87,8 +86,7 @@ class AtlasPropertiesConfigAdapter extends PropertiesConfigAdapter<AtlasProperti
@Override
public Duration configRefreshFrequency() {
return get(AtlasProperties::getConfigRefreshFrequency,
AtlasConfig.super::configRefreshFrequency);
return get(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency);
}
@Override

@ -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(DatadogMeterRegistry.class)
@ConditionalOnProperty(prefix = "management.metrics.export.datadog", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "management.metrics.export.datadog", name = "enabled", havingValue = "true",
matchIfMissing = true)
@EnableConfigurationProperties(DatadogProperties.class)
public class DatadogMetricsExportAutoConfiguration {
@ -59,8 +58,7 @@ public class DatadogMetricsExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public DatadogMeterRegistry datadogMeterRegistry(DatadogConfig datadogConfig,
Clock clock) {
public DatadogMeterRegistry datadogMeterRegistry(DatadogConfig datadogConfig, Clock clock) {
return new DatadogMeterRegistry(datadogConfig, clock);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties.
* @author Jon Schneider
* @author Phillip Webb
*/
class DatadogPropertiesConfigAdapter extends
StepRegistryPropertiesConfigAdapter<DatadogProperties> implements DatadogConfig {
class DatadogPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<DatadogProperties>
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

@ -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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<GangliaProperties>
implements GangliaConfig {
class GangliaPropertiesConfigAdapter extends PropertiesConfigAdapter<GangliaProperties> implements GangliaConfig {
GangliaPropertiesConfigAdapter(GangliaProperties properties) {
super(properties);
@ -59,20 +58,17 @@ class GangliaPropertiesConfigAdapter extends PropertiesConfigAdapter<GangliaProp
@Override
public TimeUnit durationUnits() {
return get(GangliaProperties::getDurationUnits,
GangliaConfig.super::durationUnits);
return get(GangliaProperties::getDurationUnits, GangliaConfig.super::durationUnits);
}
@Override
public String protocolVersion() {
return get(GangliaProperties::getProtocolVersion,
GangliaConfig.super::protocolVersion);
return get(GangliaProperties::getProtocolVersion, GangliaConfig.super::protocolVersion);
}
@Override
public GMetric.UDPAddressingMode addressingMode() {
return get(GangliaProperties::getAddressingMode,
GangliaConfig.super::addressingMode);
return get(GangliaProperties::getAddressingMode, GangliaConfig.super::addressingMode);
}
@Override

@ -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(GraphiteMeterRegistry.class)
@ConditionalOnProperty(prefix = "management.metrics.export.graphite", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "management.metrics.export.graphite", name = "enabled", havingValue = "true",
matchIfMissing = true)
@EnableConfigurationProperties(GraphiteProperties.class)
public class GraphiteMetricsExportAutoConfiguration {
@ -59,8 +58,7 @@ public class GraphiteMetricsExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig graphiteConfig,
Clock clock) {
public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig graphiteConfig, Clock clock) {
return new GraphiteMeterRegistry(graphiteConfig, clock);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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 GraphitePropertiesConfigAdapter extends PropertiesConfigAdapter<GraphiteProperties>
implements GraphiteConfig {
class GraphitePropertiesConfigAdapter extends PropertiesConfigAdapter<GraphiteProperties> implements GraphiteConfig {
GraphitePropertiesConfigAdapter(GraphiteProperties properties) {
super(properties);
@ -59,8 +58,7 @@ class GraphitePropertiesConfigAdapter extends PropertiesConfigAdapter<GraphitePr
@Override
public TimeUnit durationUnits() {
return get(GraphiteProperties::getDurationUnits,
GraphiteConfig.super::durationUnits);
return get(GraphiteProperties::getDurationUnits, GraphiteConfig.super::durationUnits);
}
@Override
@ -80,8 +78,7 @@ class GraphitePropertiesConfigAdapter extends PropertiesConfigAdapter<GraphitePr
@Override
public String[] tagsAsPrefix() {
return get(GraphiteProperties::getTagsAsPrefix,
GraphiteConfig.super::tagsAsPrefix);
return get(GraphiteProperties::getTagsAsPrefix, GraphiteConfig.super::tagsAsPrefix);
}
}

@ -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(InfluxMeterRegistry.class)
@ConditionalOnProperty(prefix = "management.metrics.export.influx", name = "enabled",
havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(prefix = "management.metrics.export.influx", name = "enabled", havingValue = "true",
matchIfMissing = true)
@EnableConfigurationProperties(InfluxProperties.class)
public class InfluxMetricsExportAutoConfiguration {
@ -59,8 +58,7 @@ public class InfluxMetricsExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public InfluxMeterRegistry influxMeterRegistry(InfluxConfig influxConfig,
Clock clock) {
public InfluxMeterRegistry influxMeterRegistry(InfluxConfig influxConfig, Clock clock) {
return new InfluxMeterRegistry(influxConfig, clock);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,8 +27,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.properties.
* @author Jon Schneider
* @author Phillip Webb
*/
class InfluxPropertiesConfigAdapter extends
StepRegistryPropertiesConfigAdapter<InfluxProperties> implements InfluxConfig {
class InfluxPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<InfluxProperties>
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

@ -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 {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<JmxProperties>
implements JmxConfig {
class JmxPropertiesConfigAdapter extends PropertiesConfigAdapter<JmxProperties> implements JmxConfig {
JmxPropertiesConfigAdapter(JmxProperties properties) {
super(properties);

@ -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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<NewRelicProperties>
public class NewRelicPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<NewRelicProperties>
implements NewRelicConfig {
public NewRelicPropertiesConfigAdapter(NewRelicProperties properties) {

@ -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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<PrometheusProperties> implements PrometheusConfig {
class PrometheusPropertiesConfigAdapter extends PropertiesConfigAdapter<PrometheusProperties>
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

@ -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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<SignalFxProperties>
public class SignalFxPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<SignalFxProperties>
implements SignalFxConfig {
public SignalFxPropertiesConfigAdapter(SignalFxProperties properties) {

@ -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

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<SimpleProperties> implements SimpleConfig {
public class SimplePropertiesConfigAdapter extends PropertiesConfigAdapter<SimpleProperties> implements SimpleConfig {
public SimplePropertiesConfigAdapter(SimpleProperties properties) {
super(properties);

@ -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);
}

@ -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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<StatsdProperties> implements StatsdConfig {
public class StatsdPropertiesConfigAdapter extends PropertiesConfigAdapter<StatsdProperties> 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);
}
}

@ -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);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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<WavefrontProperties>
public class WavefrontPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<WavefrontProperties>
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) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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() {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author 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);
}
}

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

Loading…
Cancel
Save