Merge branch '2.0.x'

This commit is contained in:
Phillip Webb
2018-05-03 23:54:42 -07:00
138 changed files with 312 additions and 284 deletions

View File

@@ -16,6 +16,7 @@
package org.springframework.boot.actuate.audit;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.List;
@@ -43,8 +44,13 @@ public class AuditEventsEndpoint {
@ReadOperation
public AuditEventsDescriptor events(@Nullable String principal,
@Nullable OffsetDateTime after, @Nullable String type) {
return new AuditEventsDescriptor(this.auditEventRepository.find(principal,
after == null ? null : after.toInstant(), type));
List<AuditEvent> events = this.auditEventRepository.find(principal,
getInstant(after), type);
return new AuditEventsDescriptor(events);
}
private Instant getInstant(OffsetDateTime offsetDateTime) {
return (offsetDateTime != null ? offsetDateTime.toInstant() : null);
}
/**

View File

@@ -119,7 +119,7 @@ public class BeansEndpoint {
}
ConfigurableApplicationContext parent = getConfigurableParent(context);
return new ContextBeans(describeBeans(context.getBeanFactory()),
parent == null ? null : parent.getId());
parent != null ? parent.getId() : null);
}
private static Map<String, BeanDescriptor> describeBeans(
@@ -168,8 +168,8 @@ public class BeansEndpoint {
private BeanDescriptor(String[] aliases, String scope, Class<?> type,
String resource, String[] dependencies) {
this.aliases = aliases;
this.scope = StringUtils.hasText(scope) ? scope
: BeanDefinition.SCOPE_SINGLETON;
this.scope = (StringUtils.hasText(scope) ? scope
: BeanDefinition.SCOPE_SINGLETON);
this.type = type;
this.resource = resource;
this.dependencies = dependencies;

View File

@@ -118,7 +118,7 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext
prefix, sanitize(prefix, safeSerialize(mapper, bean, prefix))));
});
return new ContextConfigurationProperties(beanDescriptors,
context.getParent() == null ? null : context.getParent().getId());
context.getParent() != null ? context.getParent().getId() : null);
}
private ConfigurationBeanFactoryMetadata getBeanFactoryMetadata(

View File

@@ -55,7 +55,7 @@ public class ElasticsearchHealthIndicator extends AbstractHealthIndicator {
public ElasticsearchHealthIndicator(Client client, long responseTimeout,
List<String> indices) {
this(client, responseTimeout,
(indices == null ? null : StringUtils.toStringArray(indices)));
(indices != null ? StringUtils.toStringArray(indices) : null));
}
/**

View File

@@ -224,7 +224,7 @@ public abstract class EndpointDiscoverer<E extends ExposableEndpoint<O>, O exten
}
private <T> T getLast(List<T> list) {
return CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1);
return (CollectionUtils.isEmpty(list) ? null : list.get(list.size() - 1));
}
private void assertNoDuplicateOperations(EndpointBean endpointBean,

View File

@@ -39,7 +39,7 @@ public class JacksonJmxOperationResponseMapper implements JmxOperationResponseMa
private final JavaType mapType;
public JacksonJmxOperationResponseMapper(ObjectMapper objectMapper) {
this.objectMapper = (objectMapper == null ? new ObjectMapper() : objectMapper);
this.objectMapper = (objectMapper != null ? objectMapper : new ObjectMapper());
this.listType = this.objectMapper.getTypeFactory()
.constructParametricType(List.class, Object.class);
this.mapType = this.objectMapper.getTypeFactory()

View File

@@ -46,7 +46,7 @@ public class PathMappedEndpoints implements Iterable<PathMappedEndpoint> {
*/
public PathMappedEndpoints(String basePath, EndpointsSupplier<?> supplier) {
Assert.notNull(supplier, "Supplier must not be null");
this.basePath = (basePath == null ? "" : basePath);
this.basePath = (basePath != null ? basePath : "");
this.endpoints = getEndpoints(Collections.singleton(supplier));
}
@@ -58,7 +58,7 @@ public class PathMappedEndpoints implements Iterable<PathMappedEndpoint> {
public PathMappedEndpoints(String basePath,
Collection<EndpointsSupplier<?>> suppliers) {
Assert.notNull(suppliers, "Suppliers must not be null");
this.basePath = (basePath == null ? "" : basePath);
this.basePath = (basePath != null ? basePath : "");
this.endpoints = getEndpoints(suppliers);
}
@@ -91,7 +91,7 @@ public class PathMappedEndpoints implements Iterable<PathMappedEndpoint> {
*/
public String getRootPath(String endpointId) {
PathMappedEndpoint endpoint = getEndpoint(endpointId);
return (endpoint == null ? null : endpoint.getRootPath());
return (endpoint != null ? endpoint.getRootPath() : null);
}
/**
@@ -144,7 +144,7 @@ public class PathMappedEndpoints implements Iterable<PathMappedEndpoint> {
}
private String getPath(PathMappedEndpoint endpoint) {
return (endpoint == null ? null : this.basePath + "/" + endpoint.getRootPath());
return (endpoint != null ? this.basePath + "/" + endpoint.getRootPath() : null);
}
private <T> List<T> asList(Stream<T> stream) {

View File

@@ -46,7 +46,7 @@ public class ServletEndpointRegistrar implements ServletContextInitializer {
public ServletEndpointRegistrar(String basePath,
Collection<ExposableServletEndpoint> servletEndpoints) {
Assert.notNull(servletEndpoints, "ServletEndpoints must not be null");
this.basePath = (basePath == null ? "" : basePath);
this.basePath = (basePath != null ? basePath : "");
this.servletEndpoints = servletEndpoints;
}

View File

@@ -179,7 +179,7 @@ public class JerseyEndpointResourceFactory {
Map<String, Object> result = new HashMap<>();
multivaluedMap.forEach((name, values) -> {
if (!CollectionUtils.isEmpty(values)) {
result.put(name, values.size() == 1 ? values.get(0) : values);
result.put(name, values.size() != 1 ? values : values.get(0));
}
});
return result;

View File

@@ -309,7 +309,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping
arguments.putAll(body);
}
exchange.getRequest().getQueryParams().forEach((name, values) -> arguments
.put(name, values.size() == 1 ? values.get(0) : values));
.put(name, values.size() != 1 ? values : values.get(0)));
return arguments;
}
@@ -323,8 +323,8 @@ public abstract class AbstractWebFluxEndpointHandlerMapping
.onErrorMap(InvalidEndpointRequestException.class,
(ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST,
ex.getReason()))
.defaultIfEmpty(new ResponseEntity<>(httpMethod == HttpMethod.GET
? HttpStatus.NOT_FOUND : HttpStatus.NO_CONTENT));
.defaultIfEmpty(new ResponseEntity<>(httpMethod != HttpMethod.GET
? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND));
}
private ResponseEntity<Object> toResponseEntity(Object response) {

View File

@@ -257,7 +257,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping
arguments.putAll(body);
}
request.getParameterMap().forEach((name, values) -> arguments.put(name,
values.length == 1 ? values[0] : Arrays.asList(values)));
values.length != 1 ? Arrays.asList(values) : values[0]));
return arguments;
}
@@ -269,8 +269,8 @@ public abstract class AbstractWebMvcEndpointHandlerMapping
private Object handleResult(Object result, HttpMethod httpMethod) {
if (result == null) {
return new ResponseEntity<>(httpMethod == HttpMethod.GET
? HttpStatus.NOT_FOUND : HttpStatus.NO_CONTENT);
return new ResponseEntity<>(httpMethod != HttpMethod.GET
? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND);
}
if (!(result instanceof WebEndpointResponse)) {
return result;

View File

@@ -34,6 +34,7 @@ import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.context.properties.bind.PlaceholdersResolver;
import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginLookup;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
@@ -152,11 +153,16 @@ public class EnvironmentEndpoint {
private PropertyValueDescriptor describeValueOf(String name, PropertySource<?> source,
PlaceholdersResolver resolver) {
Object resolved = resolver.resolvePlaceholders(source.getProperty(name));
String origin = (source instanceof OriginLookup)
? ((OriginLookup<Object>) source).getOrigin(name).toString() : null;
String origin = ((source instanceof OriginLookup)
? getOrigin((OriginLookup<Object>) source, name) : null);
return new PropertyValueDescriptor(sanitize(name, resolved), origin);
}
private String getOrigin(OriginLookup<Object> lookup, String name) {
Origin origin = lookup.getOrigin(name);
return (origin != null ? origin.toString() : null);
}
private PlaceholdersResolver getResolver() {
return new PropertySourcesPlaceholdersSanitizingResolver(getPropertySources(),
this.sanitizer);

View File

@@ -59,7 +59,7 @@ public class FlywayEndpoint {
.put(name, new FlywayDescriptor(flyway.info().all())));
ApplicationContext parent = target.getParent();
contextFlywayBeans.put(target.getId(), new ContextFlywayBeans(flywayBeans,
parent == null ? null : parent.getId()));
parent != null ? parent.getId() : null));
target = parent;
}
return new ApplicationFlywayBeans(contextFlywayBeans);
@@ -170,7 +170,7 @@ public class FlywayEndpoint {
}
private String nullSafeToString(Object obj) {
return (obj == null ? null : obj.toString());
return (obj != null ? obj.toString() : null);
}
public MigrationType getType() {

View File

@@ -57,8 +57,8 @@ public class CompositeReactiveHealthIndicator implements ReactiveHealthIndicator
Assert.notNull(indicators, "Indicators must not be null");
this.indicators = new LinkedHashMap<>(indicators);
this.healthAggregator = healthAggregator;
this.timeoutCompose = (mono) -> this.timeout != null ? mono.timeout(
Duration.ofMillis(this.timeout), Mono.just(this.timeoutHealth)) : mono;
this.timeoutCompose = (mono) -> (this.timeout != null ? mono.timeout(
Duration.ofMillis(this.timeout), Mono.just(this.timeoutHealth)) : mono);
}
/**

View File

@@ -86,7 +86,7 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator
super("DataSource health check failed");
this.dataSource = dataSource;
this.query = query;
this.jdbcTemplate = (dataSource == null ? null : new JdbcTemplate(dataSource));
this.jdbcTemplate = (dataSource != null ? new JdbcTemplate(dataSource) : null);
}
@Override

View File

@@ -69,7 +69,7 @@ public class LiquibaseEndpoint {
createReport(liquibase, service, factory)));
ApplicationContext parent = target.getParent();
contextBeans.put(target.getId(), new ContextLiquibaseBeans(liquibaseBeans,
parent == null ? null : parent.getId()));
parent != null ? parent.getId() : null));
target = parent;
}
return new ApplicationLiquibaseBeans(contextBeans);
@@ -204,8 +204,8 @@ public class LiquibaseEndpoint {
this.execType = ranChangeSet.getExecType();
this.id = ranChangeSet.getId();
this.labels = ranChangeSet.getLabels().getLabels();
this.checksum = ranChangeSet.getLastCheckSum() == null ? null
: ranChangeSet.getLastCheckSum().toString();
this.checksum = (ranChangeSet.getLastCheckSum() != null
? ranChangeSet.getLastCheckSum().toString() : null);
this.orderExecuted = ranChangeSet.getOrderExecuted();
this.tag = ranChangeSet.getTag();
}

View File

@@ -73,7 +73,7 @@ public class LoggersEndpoint {
Assert.notNull(name, "Name must not be null");
LoggerConfiguration configuration = this.loggingSystem
.getLoggerConfiguration(name);
return (configuration == null ? null : new LoggerLevels(configuration));
return (configuration != null ? new LoggerLevels(configuration) : null);
}
@WriteOperation

View File

@@ -78,7 +78,7 @@ public class HeapDumpWebEndpoint {
if (this.lock.tryLock(this.timeout, TimeUnit.MILLISECONDS)) {
try {
return new WebEndpointResponse<>(
dumpHeap(live == null ? true : live));
dumpHeap(live != null ? live : true));
}
finally {
this.lock.unlock();

View File

@@ -96,10 +96,15 @@ public class MetricsEndpoint {
}
private List<Tag> parseTags(List<String> tags) {
return tags == null ? Collections.emptyList() : tags.stream().map((t) -> {
String[] tagParts = t.split(":", 2);
return Tag.of(tagParts[0], tagParts[1]);
}).collect(Collectors.toList());
if (tags == null) {
return Collections.emptyList();
}
return tags.stream().map(this::parseTag).collect(Collectors.toList());
}
private Tag parseTag(String tag) {
String[] parts = tag.split(":", 2);
return Tag.of(parts[0], parts[1]);
}
private void collectMeters(List<Meter> meters, MeterRegistry registry, String name,
@@ -125,7 +130,7 @@ public class MetricsEndpoint {
}
private BiFunction<Double, Double, Double> mergeFunction(Statistic statistic) {
return Statistic.MAX.equals(statistic) ? Double::max : Double::sum;
return (Statistic.MAX.equals(statistic) ? Double::max : Double::sum);
}
private Map<String, Set<String>> getAvailableTags(List<Meter> meters) {

View File

@@ -50,10 +50,10 @@ public class PrometheusScrapeEndpoint {
TextFormat.write004(writer, this.collectorRegistry.metricFamilySamples());
return writer.toString();
}
catch (IOException e) {
catch (IOException ex) {
// This actually never happens since StringWriter::write() doesn't throw any
// IOException
throw new RuntimeException("Writing metrics failed", e);
throw new RuntimeException("Writing metrics failed", ex);
}
}

View File

@@ -36,9 +36,9 @@ public class DefaultRestTemplateExchangeTagsProvider
@Override
public Iterable<Tag> getTags(String urlTemplate, HttpRequest request,
ClientHttpResponse response) {
Tag uriTag = StringUtils.hasText(urlTemplate)
Tag uriTag = (StringUtils.hasText(urlTemplate)
? RestTemplateExchangeTags.uri(urlTemplate)
: RestTemplateExchangeTags.uri(request);
: RestTemplateExchangeTags.uri(request));
return Arrays.asList(RestTemplateExchangeTags.method(request), uriTag,
RestTemplateExchangeTags.status(response),
RestTemplateExchangeTags.clientName(request));

View File

@@ -64,7 +64,7 @@ public final class RestTemplateExchangeTags {
* @return the uri tag
*/
public static Tag uri(String uriTemplate) {
String uri = StringUtils.hasText(uriTemplate) ? uriTemplate : "none";
String uri = (StringUtils.hasText(uriTemplate) ? uriTemplate : "none");
return Tag.of("uri", ensureLeadingSlash(stripUri(uri)));
}

View File

@@ -58,7 +58,7 @@ public final class WebMvcTags {
* @return the method tag whose value is a capitalized method (e.g. GET).
*/
public static Tag method(HttpServletRequest request) {
return (request == null ? METHOD_UNKNOWN : Tag.of("method", request.getMethod()));
return (request != null ? Tag.of("method", request.getMethod()) : METHOD_UNKNOWN);
}
/**
@@ -67,8 +67,9 @@ public final class WebMvcTags {
* @return the status tag derived from the status of the response
*/
public static Tag status(HttpServletResponse response) {
return (response == null ? STATUS_UNKNOWN :
Tag.of("status", Integer.toString(response.getStatus())));
return (response != null
? Tag.of("status", Integer.toString(response.getStatus()))
: STATUS_UNKNOWN);
}
/**

View File

@@ -86,7 +86,7 @@ public class HttpExchangeTracer {
}
private <T> T getIfIncluded(Include include, Supplier<T> valueSupplier) {
return this.includes.contains(include) ? valueSupplier.get() : null;
return (this.includes.contains(include) ? valueSupplier.get() : null);
}
private <T> void setIfIncluded(Include include, Supplier<T> supplier,

View File

@@ -59,8 +59,8 @@ public class MappingsEndpoint {
this.descriptionProviders
.forEach((provider) -> mappings.put(provider.getMappingName(),
provider.describeMappings(applicationContext)));
return new ContextMappings(mappings, applicationContext.getParent() == null ? null
: applicationContext.getId());
return new ContextMappings(mappings, applicationContext.getParent() != null
? applicationContext.getId() : null);
}
/**

View File

@@ -64,7 +64,7 @@ final class DispatcherServletHandlerMappings {
initializeDispatcherServletIfPossible();
handlerMappings = this.dispatcherServlet.getHandlerMappings();
}
return handlerMappings == null ? Collections.emptyList() : handlerMappings;
return (handlerMappings != null ? handlerMappings : Collections.emptyList());
}
private void initializeDispatcherServletIfPossible() {

View File

@@ -73,11 +73,11 @@ public class HttpTraceWebFilter implements WebFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<?> principal = this.includes.contains(Include.PRINCIPAL)
Mono<?> principal = (this.includes.contains(Include.PRINCIPAL)
? exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE)
: Mono.just(NONE);
Mono<?> session = this.includes.contains(Include.SESSION_ID)
? exchange.getSession() : Mono.just(NONE);
: Mono.just(NONE));
Mono<?> session = (this.includes.contains(Include.SESSION_ID)
? exchange.getSession() : Mono.just(NONE));
return Mono.zip(principal, session)
.flatMap((tuple) -> filter(exchange, chain,
asType(tuple.getT1(), Principal.class),
@@ -97,17 +97,17 @@ public class HttpTraceWebFilter implements WebFilter, Ordered {
exchange);
HttpTrace trace = this.tracer.receivedRequest(request);
return chain.filter(exchange).doAfterSuccessOrError((aVoid, ex) -> {
this.tracer.sendingResponse(trace,
new TraceableServerHttpResponse(ex == null ? exchange.getResponse()
: new CustomStatusResponseDecorator(ex,
exchange.getResponse())),
() -> principal, () -> getStartedSessionId(session));
TraceableServerHttpResponse response = new TraceableServerHttpResponse(
(ex != null ? new CustomStatusResponseDecorator(ex,
exchange.getResponse()) : exchange.getResponse()));
this.tracer.sendingResponse(trace, response, () -> principal,
() -> getStartedSessionId(session));
this.repository.add(trace);
});
}
private String getStartedSessionId(WebSession session) {
return (session != null && session.isStarted()) ? session.getId() : null;
return (session != null && session.isStarted() ? session.getId() : null);
}
private static final class CustomStatusResponseDecorator
@@ -117,9 +117,9 @@ public class HttpTraceWebFilter implements WebFilter, Ordered {
private CustomStatusResponseDecorator(Throwable ex, ServerHttpResponse delegate) {
super(delegate);
this.status = ex instanceof ResponseStatusException
this.status = (ex instanceof ResponseStatusException
? ((ResponseStatusException) ex).getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
: HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override

View File

@@ -45,8 +45,8 @@ class ServerWebExchangeTraceableRequest implements TraceableRequest {
this.method = request.getMethodValue();
this.headers = request.getHeaders();
this.uri = request.getURI();
this.remoteAddress = request.getRemoteAddress() == null ? null
: request.getRemoteAddress().getAddress().toString();
this.remoteAddress = (request.getRemoteAddress() != null
? request.getRemoteAddress().getAddress().toString() : null);
}
@Override

View File

@@ -38,8 +38,8 @@ class TraceableServerHttpResponse implements TraceableResponse {
@Override
public int getStatus() {
return this.response.getStatusCode() == null ? 200
: this.response.getStatusCode().value();
return (this.response.getStatusCode() != null
? this.response.getStatusCode().value() : 200);
}
@Override

View File

@@ -86,8 +86,9 @@ public class HttpTraceFilter extends OncePerRequestFilter implements Ordered {
}
finally {
TraceableHttpServletResponse traceableResponse = new TraceableHttpServletResponse(
status == response.getStatus() ? response
: new CustomStatusResponseWrapper(response, status));
status != response.getStatus()
? new CustomStatusResponseWrapper(response, status)
: response);
this.tracer.sendingResponse(trace, traceableResponse,
request::getUserPrincipal, () -> getSessionId(request));
this.repository.add(trace);
@@ -96,7 +97,7 @@ public class HttpTraceFilter extends OncePerRequestFilter implements Ordered {
private String getSessionId(HttpServletRequest request) {
HttpSession session = request.getSession(false);
return session == null ? null : session.getId();
return (session != null ? session.getId() : null);
}
private static final class CustomStatusResponseWrapper

View File

@@ -255,7 +255,7 @@ public class ConfigurationPropertiesReportEndpointTests {
}
public boolean isMixedBoolean() {
return (this.mixedBoolean == null ? false : this.mixedBoolean);
return (this.mixedBoolean != null ? this.mixedBoolean : false);
}
public void setMixedBoolean(Boolean mixedBoolean) {

View File

@@ -57,7 +57,7 @@ public class ReflectiveOperationInvokerTests {
ReflectionUtils.findMethod(Example.class, "reverse", String.class),
OperationType.READ);
this.parameterValueMapper = (parameter,
value) -> (value == null ? null : value.toString());
value) -> (value != null ? value.toString() : null);
}
@Test

View File

@@ -190,8 +190,9 @@ public class JmxEndpointExporterTests {
@Override
public ObjectName getObjectName(ExposableJmxEndpoint endpoint)
throws MalformedObjectNameException {
return (endpoint == null ? null
: new ObjectName("boot:type=Endpoint,name=" + endpoint.getId()));
return (endpoint != null
? new ObjectName("boot:type=Endpoint,name=" + endpoint.getId())
: null);
}
}

View File

@@ -68,8 +68,8 @@ public class TestJmxOperation implements JmxOperation {
@Override
public Object invoke(InvocationContext context) {
return (this.invoke == null ? "result"
: this.invoke.apply(context.getArguments()));
return (this.invoke != null ? this.invoke.apply(context.getArguments())
: "result");
}
@Override

View File

@@ -835,7 +835,7 @@ public abstract class AbstractWebEndpointIntegrationTests<T extends Configurable
@ReadOperation
public String read(@Nullable Principal principal) {
return principal == null ? "None" : principal.getName();
return (principal != null ? principal.getName() : "None");
}
}
@@ -856,7 +856,7 @@ public abstract class AbstractWebEndpointIntegrationTests<T extends Configurable
@ReadOperation
public String read(SecurityContext securityContext) {
Principal principal = securityContext.getPrincipal();
return principal == null ? "None" : principal.getName();
return (principal != null ? principal.getName() : "None");
}
}

View File

@@ -250,8 +250,8 @@ public class WebMvcMetricsFilterTests {
result.set(this.mvc.perform(get("/api/c1/completableFuture/{id}", 1))
.andExpect(request().asyncStarted()).andReturn());
}
catch (Exception e) {
fail("Failed to execute async request", e);
catch (Exception ex) {
fail("Failed to execute async request", ex);
}
});
backgroundRequest.start();

View File

@@ -326,8 +326,8 @@ public class HttpExchangeTracerTests {
private String mixedCase(String input) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
output.append(i % 2 == 0 ? Character.toLowerCase(input.charAt(i))
: Character.toUpperCase(input.charAt(i)));
output.append(i % 2 != 0 ? Character.toUpperCase(input.charAt(i))
: Character.toLowerCase(input.charAt(i)));
}
return output.toString();
}