Commit 54c0cf51 authored by Andy Wilkinson's avatar Andy Wilkinson

Polish

parent 3904f49c
...@@ -36,4 +36,3 @@ class CloudFoundryEndpointFilter implements EndpointFilter<WebOperation> { ...@@ -36,4 +36,3 @@ class CloudFoundryEndpointFilter implements EndpointFilter<WebOperation> {
} }
} }
...@@ -27,8 +27,8 @@ import org.springframework.boot.actuate.health.HealthEndpoint; ...@@ -27,8 +27,8 @@ import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.health.ReactiveHealthEndpointWebExtension; import org.springframework.boot.actuate.health.ReactiveHealthEndpointWebExtension;
/** /**
* Reactive {@link EndpointExtension} for the {@link HealthEndpoint} that always * Reactive {@link EndpointExtension} for the {@link HealthEndpoint} that always exposes
* exposes full health details. * full health details.
* *
* @author Madhura Bhave * @author Madhura Bhave
* @since 2.0.0 * @since 2.0.0
......
...@@ -75,8 +75,7 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { ...@@ -75,8 +75,7 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint @ConditionalOnEnabledEndpoint
@ConditionalOnBean({ HealthEndpoint.class, @ConditionalOnBean({ HealthEndpoint.class, ReactiveHealthEndpointWebExtension.class })
ReactiveHealthEndpointWebExtension.class })
public CloudFoundryReactiveHealthEndpointWebExtension cloudFoundryReactiveHealthEndpointWebExtension( public CloudFoundryReactiveHealthEndpointWebExtension cloudFoundryReactiveHealthEndpointWebExtension(
ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension) { ReactiveHealthEndpointWebExtension reactiveHealthEndpointWebExtension) {
return new CloudFoundryReactiveHealthEndpointWebExtension( return new CloudFoundryReactiveHealthEndpointWebExtension(
......
...@@ -60,7 +60,8 @@ import org.springframework.web.servlet.DispatcherServlet; ...@@ -60,7 +60,8 @@ import org.springframework.web.servlet.DispatcherServlet;
*/ */
@Configuration @Configuration
@ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true) @ConditionalOnProperty(prefix = "management.cloudfoundry", name = "enabled", matchIfMissing = true)
@AutoConfigureAfter({ ServletManagementContextAutoConfiguration.class, HealthEndpointAutoConfiguration.class }) @AutoConfigureAfter({ ServletManagementContextAutoConfiguration.class,
HealthEndpointAutoConfiguration.class })
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass(DispatcherServlet.class) @ConditionalOnClass(DispatcherServlet.class)
@ConditionalOnBean(DispatcherServlet.class) @ConditionalOnBean(DispatcherServlet.class)
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -56,7 +56,8 @@ public class WebFluxEndpointManagementContextConfiguration { ...@@ -56,7 +56,8 @@ public class WebFluxEndpointManagementContextConfiguration {
WebEndpointProperties webEndpointProperties) { WebEndpointProperties webEndpointProperties) {
return new WebFluxEndpointHandlerMapping( return new WebFluxEndpointHandlerMapping(
new EndpointMapping(webEndpointProperties.getBasePath()), new EndpointMapping(webEndpointProperties.getBasePath()),
endpointDiscoverer.discoverEndpoints(), endpointMediaTypes, corsProperties.toCorsConfiguration()); endpointDiscoverer.discoverEndpoints(), endpointMediaTypes,
corsProperties.toCorsConfiguration());
} }
} }
...@@ -34,8 +34,8 @@ public class DatadogProperties extends StepRegistryProperties { ...@@ -34,8 +34,8 @@ public class DatadogProperties extends StepRegistryProperties {
private String apiKey; private String apiKey;
/** /**
* Datadog application key. Not strictly required, but improves the Datadog * Datadog application key. Not strictly required, but improves the Datadog experience
* experience by sending meter descriptions, types, and base units to Datadog. * by sending meter descriptions, types, and base units to Datadog.
*/ */
private String applicationKey; private String applicationKey;
...@@ -46,8 +46,8 @@ public class DatadogProperties extends StepRegistryProperties { ...@@ -46,8 +46,8 @@ public class DatadogProperties extends StepRegistryProperties {
private Boolean descriptions; private Boolean descriptions;
/** /**
* Tag that will be mapped to "host" when shipping metrics to Datadog. Can be * Tag that will be mapped to "host" when shipping metrics to Datadog. Can be omitted
* omitted if host should be omitted on publishing. * if host should be omitted on publishing.
*/ */
private String hostTag; private String hostTag;
......
...@@ -26,9 +26,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.StepRegistr ...@@ -26,9 +26,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.StepRegistr
* @author Jon Schneider * @author Jon Schneider
* @author Phillip Webb * @author Phillip Webb
*/ */
class DatadogPropertiesConfigAdapter class DatadogPropertiesConfigAdapter extends
extends StepRegistryPropertiesConfigAdapter<DatadogProperties> StepRegistryPropertiesConfigAdapter<DatadogProperties> implements DatadogConfig {
implements DatadogConfig {
DatadogPropertiesConfigAdapter(DatadogProperties properties) { DatadogPropertiesConfigAdapter(DatadogProperties properties) {
super(properties); super(properties);
...@@ -41,7 +40,8 @@ class DatadogPropertiesConfigAdapter ...@@ -41,7 +40,8 @@ class DatadogPropertiesConfigAdapter
@Override @Override
public String applicationKey() { public String applicationKey() {
return get(DatadogProperties::getApplicationKey, DatadogConfig.super::applicationKey); return get(DatadogProperties::getApplicationKey,
DatadogConfig.super::applicationKey);
} }
@Override @Override
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -31,8 +31,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; ...@@ -31,8 +31,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
public class InfluxProperties extends StepRegistryProperties { public class InfluxProperties extends StepRegistryProperties {
/** /**
* Tag that will be mapped to "host" when shipping metrics to Influx. Can be * Tag that will be mapped to "host" when shipping metrics to Influx. Can be omitted
* omitted if host should be omitted on publishing. * if host should be omitted on publishing.
*/ */
private String db; private String db;
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -27,9 +27,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.StepRegistr ...@@ -27,9 +27,8 @@ import org.springframework.boot.actuate.autoconfigure.metrics.export.StepRegistr
* @author Jon Schneider * @author Jon Schneider
* @author Phillip Webb * @author Phillip Webb
*/ */
class InfluxPropertiesConfigAdapter class InfluxPropertiesConfigAdapter extends
extends StepRegistryPropertiesConfigAdapter<InfluxProperties> StepRegistryPropertiesConfigAdapter<InfluxProperties> implements InfluxConfig {
implements InfluxConfig {
InfluxPropertiesConfigAdapter(InfluxProperties properties) { InfluxPropertiesConfigAdapter(InfluxProperties properties) {
super(properties); super(properties);
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -58,8 +58,8 @@ public class StatsdProperties { ...@@ -58,8 +58,8 @@ public class StatsdProperties {
private Integer maxPacketLength = 1400; private Integer maxPacketLength = 1400;
/** /**
* How often gauges will be polled. When a gauge is polled, its value is * How often gauges will be polled. When a gauge is polled, its value is recalculated
* recalculated and if the value has changed, it is sent to the StatsD server. * and if the value has changed, it is sent to the StatsD server.
*/ */
private Duration pollingFrequency = Duration.ofSeconds(10); private Duration pollingFrequency = Duration.ofSeconds(10);
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -39,8 +39,8 @@ import org.springframework.util.Assert; ...@@ -39,8 +39,8 @@ import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
/** /**
* Factory that can be used to create a {@link ServerWebExchangeMatcher} for actuator endpoint * Factory that can be used to create a {@link ServerWebExchangeMatcher} for actuator
* locations. * endpoint locations.
* *
* @author Madhura Bhave * @author Madhura Bhave
* @since 2.0.0 * @since 2.0.0
...@@ -52,8 +52,9 @@ public final class EndpointRequest { ...@@ -52,8 +52,9 @@ public final class EndpointRequest {
/** /**
* Returns a matcher that includes all {@link Endpoint actuator endpoints}. The * Returns a matcher that includes all {@link Endpoint actuator endpoints}. The
* {@link EndpointServerWebExchangeMatcher#excluding(Class...) excluding} method can be used to * {@link EndpointServerWebExchangeMatcher#excluding(Class...) excluding} method can
* further remove specific endpoints if required. For example: <pre class="code"> * be used to further remove specific endpoints if required. For example:
* <pre class="code">
* EndpointServerWebExchangeMatcher.toAnyEndpoint().excluding(ShutdownEndpoint.class) * EndpointServerWebExchangeMatcher.toAnyEndpoint().excluding(ShutdownEndpoint.class)
* </pre> * </pre>
* @return the configured {@link ServerWebExchangeMatcher} * @return the configured {@link ServerWebExchangeMatcher}
...@@ -87,7 +88,8 @@ public final class EndpointRequest { ...@@ -87,7 +88,8 @@ public final class EndpointRequest {
} }
/** /**
* The {@link ServerWebExchangeMatcher} used to match against {@link Endpoint actuator endpoints}. * The {@link ServerWebExchangeMatcher} used to match against {@link Endpoint actuator
* endpoints}.
*/ */
public final static class EndpointServerWebExchangeMatcher public final static class EndpointServerWebExchangeMatcher
extends ApplicationContextServerWebExchangeMatcher<EndpointPathProvider> { extends ApplicationContextServerWebExchangeMatcher<EndpointPathProvider> {
...@@ -116,7 +118,8 @@ public final class EndpointRequest { ...@@ -116,7 +118,8 @@ public final class EndpointRequest {
this.excludes = Collections.emptyList(); this.excludes = Collections.emptyList();
} }
private EndpointServerWebExchangeMatcher(List<Object> includes, List<Object> excludes) { private EndpointServerWebExchangeMatcher(List<Object> includes,
List<Object> excludes) {
super(EndpointPathProvider.class); super(EndpointPathProvider.class);
this.includes = includes; this.includes = includes;
this.excludes = excludes; this.excludes = excludes;
...@@ -167,7 +170,8 @@ public final class EndpointRequest { ...@@ -167,7 +170,8 @@ public final class EndpointRequest {
} }
private List<ServerWebExchangeMatcher> getDelegateMatchers(Set<String> paths) { private List<ServerWebExchangeMatcher> getDelegateMatchers(Set<String> paths) {
return paths.stream().map((path) -> new PathPatternParserServerWebExchangeMatcher(path + "/**")) return paths.stream().map(
(path) -> new PathPatternParserServerWebExchangeMatcher(path + "/**"))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -74,7 +74,7 @@ public class ExposeExcludePropertyEndpointFilterTests { ...@@ -74,7 +74,7 @@ public class ExposeExcludePropertyEndpointFilterTests {
public void createWhenPrefixIsNullShouldThrowException() { public void createWhenPrefixIsNullShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Prefix must not be empty"); this.thrown.expectMessage("Prefix must not be empty");
new ExposeExcludePropertyEndpointFilter<Operation>(TestEndpointDiscoverer.class, new ExposeExcludePropertyEndpointFilter<>(TestEndpointDiscoverer.class,
this.environment, null); this.environment, null);
} }
...@@ -82,7 +82,7 @@ public class ExposeExcludePropertyEndpointFilterTests { ...@@ -82,7 +82,7 @@ public class ExposeExcludePropertyEndpointFilterTests {
public void createWhenPrefixIsEmptyShouldThrowException() { public void createWhenPrefixIsEmptyShouldThrowException() {
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Prefix must not be empty"); this.thrown.expectMessage("Prefix must not be empty");
new ExposeExcludePropertyEndpointFilter<Operation>(TestEndpointDiscoverer.class, new ExposeExcludePropertyEndpointFilter<>(TestEndpointDiscoverer.class,
this.environment, ""); this.environment, "");
} }
......
...@@ -113,7 +113,7 @@ public class AbstractEndpointDocumentationTests { ...@@ -113,7 +113,7 @@ public class AbstractEndpointDocumentationTests {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> Map<String, Object> select(Map<String, Object> candidates, private <T> Map<String, Object> select(Map<String, Object> candidates,
Predicate<T> filter) { Predicate<T> filter) {
Map<String, Object> selected = new HashMap<String, Object>(); Map<String, Object> selected = new HashMap<>();
candidates.entrySet().stream().filter((candidate) -> filter.test((T) candidate)) candidates.entrySet().stream().filter((candidate) -> filter.test((T) candidate))
.limit(3) .limit(3)
.forEach((entry) -> selected.put(entry.getKey(), entry.getValue())); .forEach((entry) -> selected.put(entry.getKey(), entry.getValue()));
......
...@@ -56,11 +56,9 @@ public class LiquibaseEndpointDocumentationTests ...@@ -56,11 +56,9 @@ public class LiquibaseEndpointDocumentationTests
responseFields( responseFields(
fieldWithPath("contexts") fieldWithPath("contexts")
.description("Application contexts keyed by id"), .description("Application contexts keyed by id"),
changeSetsField) changeSetsField).andWithPrefix(
.andWithPrefix( "contexts.*.liquibaseBeans.*.changeSets[].",
"contexts.*.liquibaseBeans.*.changeSets[].", getChangeSetFieldDescriptors()).and(parentIdField())));
getChangeSetFieldDescriptors())
.and(parentIdField())));
} }
private List<FieldDescriptor> getChangeSetFieldDescriptors() { private List<FieldDescriptor> getChangeSetFieldDescriptors() {
......
...@@ -48,8 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. ...@@ -48,8 +48,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class LoggersEndpointDocumentationTests public class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
extends MockMvcEndpointDocumentationTests {
private static final List<FieldDescriptor> levelFields = Arrays.asList( private static final List<FieldDescriptor> levelFields = Arrays.asList(
fieldWithPath("configuredLevel") fieldWithPath("configuredLevel")
......
...@@ -39,8 +39,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. ...@@ -39,8 +39,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class MetricsEndpointDocumentationTests public class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTests {
extends MockMvcEndpointDocumentationTests {
@Test @Test
public void metricNames() throws Exception { public void metricNames() throws Exception {
......
...@@ -48,9 +48,9 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -48,9 +48,9 @@ public class WebFluxEndpointCorsIntegrationTests {
public void createContext() { public void createContext() {
this.context = new AnnotationConfigReactiveWebApplicationContext(); this.context = new AnnotationConfigReactiveWebApplicationContext();
this.context.register(JacksonAutoConfiguration.class, this.context.register(JacksonAutoConfiguration.class,
CodecsAutoConfiguration.class, CodecsAutoConfiguration.class, WebFluxAutoConfiguration.class,
WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class,
EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class,
ManagementContextAutoConfiguration.class, ManagementContextAutoConfiguration.class,
ReactiveManagementContextAutoConfiguration.class, ReactiveManagementContextAutoConfiguration.class,
BeansEndpointAutoConfiguration.class); BeansEndpointAutoConfiguration.class);
...@@ -59,13 +59,11 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -59,13 +59,11 @@ public class WebFluxEndpointCorsIntegrationTests {
@Test @Test
public void corsIsDisabledByDefault() { public void corsIsDisabledByDefault() {
createWebTestClient() createWebTestClient().options().uri("/actuator/beans")
.options().uri("/actuator/beans")
.header("Origin", "spring.example.org") .header("Origin", "spring.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange()
.exchange() .expectStatus().isForbidden().expectHeader()
.expectStatus().isForbidden() .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);
.expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);
} }
@Test @Test
...@@ -73,11 +71,9 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -73,11 +71,9 @@ public class WebFluxEndpointCorsIntegrationTests {
TestPropertyValues TestPropertyValues
.of("management.endpoints.web.cors.allowed-origins:spring.example.org") .of("management.endpoints.web.cors.allowed-origins:spring.example.org")
.applyTo(this.context); .applyTo(this.context);
createWebTestClient() createWebTestClient().options().uri("/actuator/beans")
.options().uri("/actuator/beans")
.header("Origin", "test.example.org") .header("Origin", "test.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange()
.exchange()
.expectStatus().isForbidden(); .expectStatus().isForbidden();
performAcceptedCorsRequest("/actuator/beans"); performAcceptedCorsRequest("/actuator/beans");
} }
...@@ -87,8 +83,8 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -87,8 +83,8 @@ public class WebFluxEndpointCorsIntegrationTests {
TestPropertyValues TestPropertyValues
.of("management.endpoints.web.cors.allowed-origins:spring.example.org") .of("management.endpoints.web.cors.allowed-origins:spring.example.org")
.applyTo(this.context); .applyTo(this.context);
performAcceptedCorsRequest("/actuator/beans") performAcceptedCorsRequest("/actuator/beans").expectHeader()
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"); .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800");
} }
@Test @Test
...@@ -97,8 +93,8 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -97,8 +93,8 @@ public class WebFluxEndpointCorsIntegrationTests {
.of("management.endpoints.web.cors.allowed-origins:spring.example.org", .of("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.max-age: 2400") "management.endpoints.web.cors.max-age: 2400")
.applyTo(this.context); .applyTo(this.context);
performAcceptedCorsRequest("/actuator/beans") performAcceptedCorsRequest("/actuator/beans").expectHeader()
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"); .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400");
} }
@Test @Test
...@@ -106,12 +102,10 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -106,12 +102,10 @@ public class WebFluxEndpointCorsIntegrationTests {
TestPropertyValues TestPropertyValues
.of("management.endpoints.web.cors.allowed-origins:spring.example.org") .of("management.endpoints.web.cors.allowed-origins:spring.example.org")
.applyTo(this.context); .applyTo(this.context);
createWebTestClient() createWebTestClient().options().uri("/actuator/beans")
.options().uri("/actuator/beans")
.header("Origin", "spring.example.org") .header("Origin", "spring.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange()
.exchange()
.expectStatus().isForbidden(); .expectStatus().isForbidden();
} }
...@@ -121,14 +115,12 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -121,14 +115,12 @@ public class WebFluxEndpointCorsIntegrationTests {
.of("management.endpoints.web.cors.allowed-origins:spring.example.org", .of("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allowed-headers:Alpha,Bravo") "management.endpoints.web.cors.allowed-headers:Alpha,Bravo")
.applyTo(this.context); .applyTo(this.context);
createWebTestClient() createWebTestClient().options().uri("/actuator/beans")
.options().uri("/actuator/beans")
.header("Origin", "spring.example.org") .header("Origin", "spring.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange()
.exchange() .expectStatus().isOk().expectHeader()
.expectStatus().isOk() .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha");
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha");
} }
@Test @Test
...@@ -136,11 +128,9 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -136,11 +128,9 @@ public class WebFluxEndpointCorsIntegrationTests {
TestPropertyValues TestPropertyValues
.of("management.endpoints.web.cors.allowed-origins:spring.example.org") .of("management.endpoints.web.cors.allowed-origins:spring.example.org")
.applyTo(this.context); .applyTo(this.context);
createWebTestClient() createWebTestClient().options().uri("/actuator/beans")
.options().uri("/actuator/beans")
.header("Origin", "spring.example.org") .header("Origin", "spring.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH").exchange()
.exchange()
.expectStatus().isForbidden(); .expectStatus().isForbidden();
} }
...@@ -150,13 +140,11 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -150,13 +140,11 @@ public class WebFluxEndpointCorsIntegrationTests {
.of("management.endpoints.web.cors.allowed-origins:spring.example.org", .of("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allowed-methods:GET,HEAD") "management.endpoints.web.cors.allowed-methods:GET,HEAD")
.applyTo(this.context); .applyTo(this.context);
createWebTestClient() createWebTestClient().options().uri("/actuator/beans")
.options().uri("/actuator/beans")
.header("Origin", "spring.example.org") .header("Origin", "spring.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD").exchange()
.exchange() .expectStatus().isOk().expectHeader()
.expectStatus().isOk() .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD");
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD");
} }
@Test @Test
...@@ -165,8 +153,8 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -165,8 +153,8 @@ public class WebFluxEndpointCorsIntegrationTests {
.of("management.endpoints.web.cors.allowed-origins:spring.example.org", .of("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allow-credentials:true") "management.endpoints.web.cors.allow-credentials:true")
.applyTo(this.context); .applyTo(this.context);
performAcceptedCorsRequest("/actuator/beans") performAcceptedCorsRequest("/actuator/beans").expectHeader()
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
} }
@Test @Test
...@@ -175,24 +163,22 @@ public class WebFluxEndpointCorsIntegrationTests { ...@@ -175,24 +163,22 @@ public class WebFluxEndpointCorsIntegrationTests {
.of("management.endpoints.web.cors.allowed-origins:spring.example.org", .of("management.endpoints.web.cors.allowed-origins:spring.example.org",
"management.endpoints.web.cors.allow-credentials:false") "management.endpoints.web.cors.allow-credentials:false")
.applyTo(this.context); .applyTo(this.context);
performAcceptedCorsRequest("/actuator/beans") performAcceptedCorsRequest("/actuator/beans").expectHeader()
.expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS); .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);
} }
private WebTestClient createWebTestClient() { private WebTestClient createWebTestClient() {
this.context.refresh(); this.context.refresh();
return WebTestClient.bindToApplicationContext(this.context) return WebTestClient.bindToApplicationContext(this.context).configureClient()
.configureClient().baseUrl("https://spring.example.org").build(); .baseUrl("https://spring.example.org").build();
} }
private WebTestClient.ResponseSpec performAcceptedCorsRequest(String url) { private WebTestClient.ResponseSpec performAcceptedCorsRequest(String url) {
return createWebTestClient() return createWebTestClient().options().uri(url)
.options().uri(url)
.header(HttpHeaders.ORIGIN, "spring.example.org") .header(HttpHeaders.ORIGIN, "spring.example.org")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange()
.exchange() .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "spring.example.org") "spring.example.org")
.expectStatus().isOk(); .expectStatus().isOk();
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -45,8 +45,7 @@ public class LogFileWebEndpointAutoConfigurationTests { ...@@ -45,8 +45,7 @@ public class LogFileWebEndpointAutoConfigurationTests {
public TemporaryFolder temp = new TemporaryFolder(); public TemporaryFolder temp = new TemporaryFolder();
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withUserConfiguration( .withUserConfiguration(LogFileWebEndpointAutoConfiguration.class);
LogFileWebEndpointAutoConfiguration.class);
@Test @Test
public void logFileWebEndpointIsAutoConfiguredWhenLoggingFileIsSet() { public void logFileWebEndpointIsAutoConfiguredWhenLoggingFileIsSet() {
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -32,8 +32,7 @@ public class HeapDumpWebEndpointAutoConfigurationTests { ...@@ -32,8 +32,7 @@ public class HeapDumpWebEndpointAutoConfigurationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withPropertyValues("management.endpoints.web.expose:*") .withPropertyValues("management.endpoints.web.expose:*")
.withUserConfiguration( .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class);
HeapDumpWebEndpointAutoConfiguration.class);
@Test @Test
public void runShouldCreateIndicator() { public void runShouldCreateIndicator() {
......
...@@ -39,15 +39,14 @@ public class CacheMetricsConfigurationTests { ...@@ -39,15 +39,14 @@ public class CacheMetricsConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withUserConfiguration(RegistryConfiguration.class) .withUserConfiguration(RegistryConfiguration.class)
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, CacheAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
CacheAutoConfiguration.class))
.withPropertyValues("management.metrics.use-global-registry=false"); .withPropertyValues("management.metrics.use-global-registry=false");
@Test @Test
public void autoConfiguredCacheManagerIsInstrumented() { public void autoConfiguredCacheManagerIsInstrumented() {
this.contextRunner this.contextRunner.withPropertyValues("spring.cache.type=caffeine",
.withPropertyValues("spring.cache.type=caffeine", "spring.cache.cache-names=cache1,cache2").run((context) -> {
"spring.cache.cache-names=cache1,cache2")
.run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class); MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("cache.requests").tags("name", "cache1") assertThat(registry.find("cache.requests").tags("name", "cache1")
.tags("cacheManager", "cacheManager").meter()).isPresent(); .tags("cacheManager", "cacheManager").meter()).isPresent();
...@@ -73,10 +72,8 @@ public class CacheMetricsConfigurationTests { ...@@ -73,10 +72,8 @@ public class CacheMetricsConfigurationTests {
@Test @Test
public void autoConfiguredNonSupportedCacheManagerIsIgnored() { public void autoConfiguredNonSupportedCacheManagerIsIgnored() {
this.contextRunner this.contextRunner.withPropertyValues("spring.cache.type=simple",
.withPropertyValues("spring.cache.type=simple", "spring.cache.cache-names=cache1,cache2").run((context) -> {
"spring.cache.cache-names=cache1,cache2")
.run((context) -> {
MeterRegistry registry = context.getBean(MeterRegistry.class); MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("cache.requests").tags("name", "cache1") assertThat(registry.find("cache.requests").tags("name", "cache1")
.tags("cacheManager", "cacheManager").meter()).isNotPresent(); .tags("cacheManager", "cacheManager").meter()).isNotPresent();
......
...@@ -45,11 +45,10 @@ public class RestTemplateMetricsConfigurationTests { ...@@ -45,11 +45,10 @@ public class RestTemplateMetricsConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("management.metrics.use-global-registry=false") .withPropertyValues("management.metrics.use-global-registry=false")
.withConfiguration(AutoConfigurations.of( .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class,
RestTemplateAutoConfiguration.class, MetricsAutoConfiguration.class)) MetricsAutoConfiguration.class))
.withUserConfiguration(RegistryConfiguration.class); .withUserConfiguration(RegistryConfiguration.class);
@Test @Test
public void restTemplateCreatedWithBuilderIsInstrumented() { public void restTemplateCreatedWithBuilderIsInstrumented() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
...@@ -64,8 +63,9 @@ public class RestTemplateMetricsConfigurationTests { ...@@ -64,8 +63,9 @@ public class RestTemplateMetricsConfigurationTests {
public void restTemplateCanBeCustomizedManually() { public void restTemplateCanBeCustomizedManually() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(MetricsRestTemplateCustomizer.class); assertThat(context).hasSingleBean(MetricsRestTemplateCustomizer.class);
RestTemplate restTemplate = new RestTemplateBuilder().customizers( RestTemplate restTemplate = new RestTemplateBuilder()
context.getBean(MetricsRestTemplateCustomizer.class)).build(); .customizers(context.getBean(MetricsRestTemplateCustomizer.class))
.build();
MeterRegistry registry = context.getBean(MeterRegistry.class); MeterRegistry registry = context.getBean(MeterRegistry.class);
validateRestTemplate(restTemplate, registry); validateRestTemplate(restTemplate, registry);
}); });
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -91,7 +91,8 @@ public class EndpointRequestTests { ...@@ -91,7 +91,8 @@ public class EndpointRequestTests {
@Test @Test
public void excludeByIdShouldNotMatchExcluded() { public void excludeByIdShouldNotMatchExcluded() {
ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("foo"); ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint()
.excluding("foo");
assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo");
assertMatcher(matcher).matches("/actuator/bar"); assertMatcher(matcher).matches("/actuator/bar");
} }
...@@ -113,13 +114,16 @@ public class EndpointRequestTests { ...@@ -113,13 +114,16 @@ public class EndpointRequestTests {
private final ServerWebExchangeMatcher matcher; private final ServerWebExchangeMatcher matcher;
RequestMatcherAssert(StaticApplicationContext context, ServerWebExchangeMatcher matcher) { RequestMatcherAssert(StaticApplicationContext context,
ServerWebExchangeMatcher matcher) {
this.context = context; this.context = context;
this.matcher = matcher; this.matcher = matcher;
} }
void matches(String path) { void matches(String path) {
ServerWebExchange exchange = webHandler().createExchange(MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); ServerWebExchange exchange = webHandler().createExchange(
MockServerHttpRequest.get(path).build(),
new MockServerHttpResponse());
matches(exchange); matches(exchange);
} }
...@@ -129,7 +133,9 @@ public class EndpointRequestTests { ...@@ -129,7 +133,9 @@ public class EndpointRequestTests {
} }
void doesNotMatch(String path) { void doesNotMatch(String path) {
ServerWebExchange exchange = webHandler().createExchange(MockServerHttpRequest.get(path).build(), new MockServerHttpResponse()); ServerWebExchange exchange = webHandler().createExchange(
MockServerHttpRequest.get(path).build(),
new MockServerHttpResponse());
doesNotMatch(exchange); doesNotMatch(exchange);
} }
...@@ -139,7 +145,8 @@ public class EndpointRequestTests { ...@@ -139,7 +145,8 @@ public class EndpointRequestTests {
} }
private TestHttpWebHandlerAdapter webHandler() { private TestHttpWebHandlerAdapter webHandler() {
TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(mock(WebHandler.class)); TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(
mock(WebHandler.class));
adapter.setApplicationContext(this.context); adapter.setApplicationContext(this.context);
return adapter; return adapter;
} }
...@@ -157,7 +164,8 @@ public class EndpointRequestTests { ...@@ -157,7 +164,8 @@ public class EndpointRequestTests {
} }
@Override @Override
protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { protected ServerWebExchange createExchange(ServerHttpRequest request,
ServerHttpResponse response) {
return super.createExchange(request, response); return super.createExchange(request, response);
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -76,8 +76,7 @@ public class EndpointMBean implements DynamicMBean { ...@@ -76,8 +76,7 @@ public class EndpointMBean implements DynamicMBean {
@Override @Override
public Object invoke(String actionName, Object[] params, String[] signature) public Object invoke(String actionName, Object[] params, String[] signature)
throws MBeanException, ReflectionException { throws MBeanException, ReflectionException {
JmxOperation operation = this.endpointInfo.getOperations() JmxOperation operation = this.endpointInfo.getOperations().get(actionName);
.get(actionName);
if (operation != null) { if (operation != null) {
Map<String, Object> arguments = getArguments(params, Map<String, Object> arguments = getArguments(params,
operation.getParameters()); operation.getParameters());
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -53,8 +53,7 @@ class EndpointMBeanInfoAssembler { ...@@ -53,8 +53,7 @@ class EndpointMBeanInfoAssembler {
* @param endpointInfo the endpoint to handle * @param endpointInfo the endpoint to handle
* @return the mbean info for the endpoint * @return the mbean info for the endpoint
*/ */
EndpointMBeanInfo createEndpointMBeanInfo( EndpointMBeanInfo createEndpointMBeanInfo(EndpointInfo<JmxOperation> endpointInfo) {
EndpointInfo<JmxOperation> endpointInfo) {
Map<String, OperationInfos> operationsMapping = getOperationInfo(endpointInfo); Map<String, OperationInfos> operationsMapping = getOperationInfo(endpointInfo);
ModelMBeanOperationInfo[] operationsMBeanInfo = operationsMapping.values() ModelMBeanOperationInfo[] operationsMBeanInfo = operationsMapping.values()
.stream().map((t) -> t.mBeanOperationInfo).collect(Collectors.toList()) .stream().map((t) -> t.mBeanOperationInfo).collect(Collectors.toList())
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -38,8 +38,7 @@ public class EndpointLinksResolver { ...@@ -38,8 +38,7 @@ public class EndpointLinksResolver {
* @return the links * @return the links
*/ */
public Map<String, Link> resolveLinks( public Map<String, Link> resolveLinks(
Collection<EndpointInfo<WebOperation>> webEndpoints, Collection<EndpointInfo<WebOperation>> webEndpoints, String requestUrl) {
String requestUrl) {
String normalizedUrl = normalizeRequestUrl(requestUrl); String normalizedUrl = normalizeRequestUrl(requestUrl);
Map<String, Link> links = new LinkedHashMap<>(); Map<String, Link> links = new LinkedHashMap<>();
links.put("self", new Link(normalizedUrl)); links.put("self", new Link(normalizedUrl));
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -117,8 +117,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping ...@@ -117,8 +117,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping
registerMapping(mapping, this, getLinks()); registerMapping(mapping, this, getLinks());
} }
protected RequestMappingInfo createRequestMappingInfo( protected RequestMappingInfo createRequestMappingInfo(WebOperation operationInfo) {
WebOperation operationInfo) {
OperationRequestPredicate requestPredicate = operationInfo.getRequestPredicate(); OperationRequestPredicate requestPredicate = operationInfo.getRequestPredicate();
PatternsRequestCondition patterns = new PatternsRequestCondition(pathPatternParser PatternsRequestCondition patterns = new PatternsRequestCondition(pathPatternParser
.parse(this.endpointMapping.createSubPath(requestPredicate.getPath()))); .parse(this.endpointMapping.createSubPath(requestPredicate.getPath())));
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -132,8 +132,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping ...@@ -132,8 +132,7 @@ public abstract class AbstractWebMvcEndpointHandlerMapping
protected abstract void registerMappingForOperation(WebOperation operation); protected abstract void registerMappingForOperation(WebOperation operation);
protected RequestMappingInfo createRequestMappingInfo( protected RequestMappingInfo createRequestMappingInfo(WebOperation operationInfo) {
WebOperation operationInfo) {
OperationRequestPredicate requestPredicate = operationInfo.getRequestPredicate(); OperationRequestPredicate requestPredicate = operationInfo.getRequestPredicate();
PatternsRequestCondition patterns = patternsRequestConditionForPattern( PatternsRequestCondition patterns = patternsRequestConditionForPattern(
requestPredicate.getPath()); requestPredicate.getPath());
......
...@@ -91,8 +91,7 @@ public class MetricsEndpoint { ...@@ -91,8 +91,7 @@ public class MetricsEndpoint {
Map<Statistic, Double> samples = getSamples(meters); Map<Statistic, Double> samples = getSamples(meters);
Map<String, Set<String>> availableTags = getAvailableTags(meters); Map<String, Set<String>> availableTags = getAvailableTags(meters);
tags.forEach((t) -> availableTags.remove(t.getKey())); tags.forEach((t) -> availableTags.remove(t.getKey()));
return new MetricResponse(requiredMetricName, return new MetricResponse(requiredMetricName, asList(samples, Sample::new),
asList(samples, Sample::new),
asList(availableTags, AvailableTag::new)); asList(availableTags, AvailableTag::new));
} }
......
...@@ -247,14 +247,15 @@ public class WebMvcMetricsFilterTests { ...@@ -247,14 +247,15 @@ public class WebMvcMetricsFilterTests {
@Bean @Bean
PrometheusMeterRegistry prometheus() { PrometheusMeterRegistry prometheus() {
PrometheusMeterRegistry r = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT, new CollectorRegistry(), Clock.SYSTEM); PrometheusMeterRegistry r = new PrometheusMeterRegistry(
PrometheusConfig.DEFAULT, new CollectorRegistry(), Clock.SYSTEM);
r.config().meterFilter(new MeterFilter() { r.config().meterFilter(new MeterFilter() {
@Override @Override
public MeterFilterReply accept(Meter.Id id) { public MeterFilterReply accept(Meter.Id id) {
for (Tag tag : id.getTags()) { for (Tag tag : id.getTags()) {
if (tag.getKey().equals("uri") if (tag.getKey().equals("uri")
&& (tag.getValue().contains("histogram") && (tag.getValue().contains("histogram")
|| tag.getValue().contains("percentiles"))) { || tag.getValue().contains("percentiles"))) {
return MeterFilterReply.ACCEPT; return MeterFilterReply.ACCEPT;
} }
} }
......
...@@ -64,8 +64,8 @@ public class GsonProperties { ...@@ -64,8 +64,8 @@ public class GsonProperties {
private LongSerializationPolicy longSerializationPolicy; private LongSerializationPolicy longSerializationPolicy;
/** /**
* Naming policy that should be applied to an object's field during serialization * Naming policy that should be applied to an object's field during serialization and
* and deserialization. * deserialization.
*/ */
private FieldNamingPolicy fieldNamingPolicy; private FieldNamingPolicy fieldNamingPolicy;
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -75,7 +75,8 @@ class GsonHttpMessageConvertersConfiguration { ...@@ -75,7 +75,8 @@ class GsonHttpMessageConvertersConfiguration {
} }
private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions { private static class JacksonAndJsonbUnavailableCondition
extends NoneNestedConditions {
JacksonAndJsonbUnavailableCondition() { JacksonAndJsonbUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN); super(ConfigurationPhase.REGISTER_BEAN);
......
...@@ -53,7 +53,8 @@ public class SessionProperties { ...@@ -53,7 +53,8 @@ public class SessionProperties {
public SessionProperties(ObjectProvider<ServerProperties> serverProperties) { public SessionProperties(ObjectProvider<ServerProperties> serverProperties) {
ServerProperties properties = serverProperties.getIfUnique(); ServerProperties properties = serverProperties.getIfUnique();
Session session = (properties == null ? null : properties.getServlet().getSession()); Session session = (properties == null ? null
: properties.getServlet().getSession());
this.timeout = (session == null ? null : session.getTimeout()); this.timeout = (session == null ? null : session.getTimeout());
} }
...@@ -68,7 +69,7 @@ public class SessionProperties { ...@@ -68,7 +69,7 @@ public class SessionProperties {
/** /**
* Return the session timeout. * Return the session timeout.
* @return the session timeout * @return the session timeout
* @see ServerProperties.Servlet#getSession() * @see Session#getTimeout()
*/ */
public Duration getTimeout() { public Duration getTimeout() {
return this.timeout; return this.timeout;
......
...@@ -35,8 +35,7 @@ import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer; ...@@ -35,8 +35,7 @@ import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
/** /**
* Customization for Jetty-specific features common * Customization for Jetty-specific features common for both Servlet and Reactive servers.
* for both Servlet and Reactive servers.
* *
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
...@@ -58,16 +57,14 @@ public final class JettyCustomizer { ...@@ -58,16 +57,14 @@ public final class JettyCustomizer {
factory.setSelectors(jettyProperties.getSelectors()); factory.setSelectors(jettyProperties.getSelectors());
} }
if (serverProperties.getMaxHttpHeaderSize() > 0) { if (serverProperties.getMaxHttpHeaderSize() > 0) {
customizeMaxHttpHeaderSize(factory, customizeMaxHttpHeaderSize(factory, serverProperties.getMaxHttpHeaderSize());
serverProperties.getMaxHttpHeaderSize());
} }
if (jettyProperties.getMaxHttpPostSize() > 0) { if (jettyProperties.getMaxHttpPostSize() > 0) {
customizeMaxHttpPostSize(factory, jettyProperties.getMaxHttpPostSize()); customizeMaxHttpPostSize(factory, jettyProperties.getMaxHttpPostSize());
} }
if (serverProperties.getConnectionTimeout() != null) { if (serverProperties.getConnectionTimeout() != null) {
customizeConnectionTimeout(factory, customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout());
serverProperties.getConnectionTimeout());
} }
if (jettyProperties.getAccesslog().isEnabled()) { if (jettyProperties.getAccesslog().isEnabled()) {
customizeAccessLog(factory, jettyProperties.getAccesslog()); customizeAccessLog(factory, jettyProperties.getAccesslog());
...@@ -86,8 +83,7 @@ public final class JettyCustomizer { ...@@ -86,8 +83,7 @@ public final class JettyCustomizer {
private static void customizeConnectionTimeout( private static void customizeConnectionTimeout(
ConfigurableJettyWebServerFactory factory, Duration connectionTimeout) { ConfigurableJettyWebServerFactory factory, Duration connectionTimeout) {
factory.addServerCustomizers((server) -> { factory.addServerCustomizers((server) -> {
for (org.eclipse.jetty.server.Connector connector : server for (org.eclipse.jetty.server.Connector connector : server.getConnectors()) {
.getConnectors()) {
if (connector instanceof AbstractConnector) { if (connector instanceof AbstractConnector) {
((AbstractConnector) connector) ((AbstractConnector) connector)
.setIdleTimeout(connectionTimeout.toMillis()); .setIdleTimeout(connectionTimeout.toMillis());
...@@ -123,8 +119,8 @@ public final class JettyCustomizer { ...@@ -123,8 +119,8 @@ public final class JettyCustomizer {
}); });
} }
private static void customizeMaxHttpPostSize(ConfigurableJettyWebServerFactory factory, private static void customizeMaxHttpPostSize(
int maxHttpPostSize) { ConfigurableJettyWebServerFactory factory, int maxHttpPostSize) {
factory.addServerCustomizers(new JettyServerCustomizer() { factory.addServerCustomizers(new JettyServerCustomizer() {
@Override @Override
...@@ -136,8 +132,7 @@ public final class JettyCustomizer { ...@@ -136,8 +132,7 @@ public final class JettyCustomizer {
Handler... handlers) { Handler... handlers) {
for (Handler handler : handlers) { for (Handler handler : handlers) {
if (handler instanceof ContextHandler) { if (handler instanceof ContextHandler) {
((ContextHandler) handler) ((ContextHandler) handler).setMaxFormContentSize(maxHttpPostSize);
.setMaxFormContentSize(maxHttpPostSize);
} }
else if (handler instanceof HandlerWrapper) { else if (handler instanceof HandlerWrapper) {
setHandlerMaxHttpPostSize(maxHttpPostSize, setHandlerMaxHttpPostSize(maxHttpPostSize,
......
...@@ -32,8 +32,8 @@ import org.springframework.core.env.Environment; ...@@ -32,8 +32,8 @@ import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* Customization for Tomcat-specific features common * Customization for Tomcat-specific features common for both Servlet and Reactive
* for both Servlet and Reactive servers. * servers.
* *
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
...@@ -50,8 +50,8 @@ public final class TomcatCustomizer { ...@@ -50,8 +50,8 @@ public final class TomcatCustomizer {
factory.setBaseDirectory(tomcatProperties.getBasedir()); factory.setBaseDirectory(tomcatProperties.getBasedir());
} }
if (tomcatProperties.getBackgroundProcessorDelay() != null) { if (tomcatProperties.getBackgroundProcessorDelay() != null) {
factory.setBackgroundProcessorDelay((int) tomcatProperties factory.setBackgroundProcessorDelay(
.getBackgroundProcessorDelay().getSeconds()); (int) tomcatProperties.getBackgroundProcessorDelay().getSeconds());
} }
customizeRemoteIpValve(serverProperties, environment, factory); customizeRemoteIpValve(serverProperties, environment, factory);
if (tomcatProperties.getMaxThreads() > 0) { if (tomcatProperties.getMaxThreads() > 0) {
...@@ -76,8 +76,7 @@ public final class TomcatCustomizer { ...@@ -76,8 +76,7 @@ public final class TomcatCustomizer {
factory.setUriEncoding(tomcatProperties.getUriEncoding()); factory.setUriEncoding(tomcatProperties.getUriEncoding());
} }
if (serverProperties.getConnectionTimeout() != null) { if (serverProperties.getConnectionTimeout() != null) {
customizeConnectionTimeout(factory, customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout());
serverProperties.getConnectionTimeout());
} }
if (tomcatProperties.getMaxConnections() > 0) { if (tomcatProperties.getMaxConnections() > 0) {
customizeMaxConnections(factory, tomcatProperties.getMaxConnections()); customizeMaxConnections(factory, tomcatProperties.getMaxConnections());
...@@ -99,8 +98,8 @@ public final class TomcatCustomizer { ...@@ -99,8 +98,8 @@ public final class TomcatCustomizer {
}); });
} }
private static void customizeMaxConnections(ConfigurableTomcatWebServerFactory factory, private static void customizeMaxConnections(
int maxConnections) { ConfigurableTomcatWebServerFactory factory, int maxConnections) {
factory.addConnectorCustomizers((connector) -> { factory.addConnectorCustomizers((connector) -> {
ProtocolHandler handler = connector.getProtocolHandler(); ProtocolHandler handler = connector.getProtocolHandler();
if (handler instanceof AbstractProtocol) { if (handler instanceof AbstractProtocol) {
...@@ -129,8 +128,8 @@ public final class TomcatCustomizer { ...@@ -129,8 +128,8 @@ public final class TomcatCustomizer {
if (StringUtils.hasText(protocolHeader) || StringUtils.hasText(remoteIpHeader) if (StringUtils.hasText(protocolHeader) || StringUtils.hasText(remoteIpHeader)
|| getOrDeduceUseForwardHeaders(properties, environment)) { || getOrDeduceUseForwardHeaders(properties, environment)) {
RemoteIpValve valve = new RemoteIpValve(); RemoteIpValve valve = new RemoteIpValve();
valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) ? protocolHeader
? protocolHeader : "X-Forwarded-Proto"); : "X-Forwarded-Proto");
if (StringUtils.hasLength(remoteIpHeader)) { if (StringUtils.hasLength(remoteIpHeader)) {
valve.setRemoteIpHeader(remoteIpHeader); valve.setRemoteIpHeader(remoteIpHeader);
} }
...@@ -213,7 +212,8 @@ public final class TomcatCustomizer { ...@@ -213,7 +212,8 @@ public final class TomcatCustomizer {
factory.addEngineValves(valve); factory.addEngineValves(valve);
} }
private static void customizeStaticResources(ServerProperties.Tomcat.Resource resource, private static void customizeStaticResources(
ServerProperties.Tomcat.Resource resource,
ConfigurableTomcatWebServerFactory factory) { ConfigurableTomcatWebServerFactory factory) {
if (resource.getCacheTtl() == null) { if (resource.getCacheTtl() == null) {
return; return;
......
...@@ -26,8 +26,8 @@ import org.springframework.boot.web.embedded.undertow.ConfigurableUndertowWebSer ...@@ -26,8 +26,8 @@ import org.springframework.boot.web.embedded.undertow.ConfigurableUndertowWebSer
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
/** /**
* Customization for Undertow-specific features common * Customization for Undertow-specific features common for both Servlet and Reactive
* for both Servlet and Reactive servers. * servers.
* *
* @author Brian Clozel * @author Brian Clozel
*/ */
...@@ -62,18 +62,16 @@ public final class UndertowCustomizer { ...@@ -62,18 +62,16 @@ public final class UndertowCustomizer {
factory.setAccessLogPrefix(accesslogProperties.getPrefix()); factory.setAccessLogPrefix(accesslogProperties.getPrefix());
factory.setAccessLogSuffix(accesslogProperties.getSuffix()); factory.setAccessLogSuffix(accesslogProperties.getSuffix());
factory.setAccessLogRotate(accesslogProperties.isRotate()); factory.setAccessLogRotate(accesslogProperties.isRotate());
factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders(serverProperties, environment)); factory.setUseForwardHeaders(
getOrDeduceUseForwardHeaders(serverProperties, environment));
if (serverProperties.getMaxHttpHeaderSize() > 0) { if (serverProperties.getMaxHttpHeaderSize() > 0) {
customizeMaxHttpHeaderSize(factory, customizeMaxHttpHeaderSize(factory, serverProperties.getMaxHttpHeaderSize());
serverProperties.getMaxHttpHeaderSize());
} }
if (undertowProperties.getMaxHttpPostSize() > 0) { if (undertowProperties.getMaxHttpPostSize() > 0) {
customizeMaxHttpPostSize(factory, customizeMaxHttpPostSize(factory, undertowProperties.getMaxHttpPostSize());
undertowProperties.getMaxHttpPostSize());
} }
if (serverProperties.getConnectionTimeout() != null) { if (serverProperties.getConnectionTimeout() != null) {
customizeConnectionTimeout(factory, customizeConnectionTimeout(factory, serverProperties.getConnectionTimeout());
serverProperties.getConnectionTimeout());
} }
factory.addDeploymentInfoCustomizers((deploymentInfo) -> deploymentInfo factory.addDeploymentInfoCustomizers((deploymentInfo) -> deploymentInfo
.setEagerFilterInit(undertowProperties.isEagerFilterInit())); .setEagerFilterInit(undertowProperties.isEagerFilterInit()));
...@@ -82,8 +80,7 @@ public final class UndertowCustomizer { ...@@ -82,8 +80,7 @@ public final class UndertowCustomizer {
private static void customizeConnectionTimeout( private static void customizeConnectionTimeout(
ConfigurableUndertowWebServerFactory factory, Duration connectionTimeout) { ConfigurableUndertowWebServerFactory factory, Duration connectionTimeout) {
factory.addBuilderCustomizers((builder) -> builder.setSocketOption( factory.addBuilderCustomizers((builder) -> builder.setSocketOption(
UndertowOptions.NO_REQUEST_TIMEOUT, UndertowOptions.NO_REQUEST_TIMEOUT, (int) connectionTimeout.toMillis()));
(int) connectionTimeout.toMillis()));
} }
private static void customizeMaxHttpHeaderSize( private static void customizeMaxHttpHeaderSize(
......
...@@ -35,8 +35,9 @@ import org.springframework.core.env.Environment; ...@@ -35,8 +35,9 @@ import org.springframework.core.env.Environment;
* @author Brian Clozel * @author Brian Clozel
* @since 2.0.0 * @since 2.0.0
*/ */
public class DefaultReactiveWebServerFactoryCustomizer implements public class DefaultReactiveWebServerFactoryCustomizer
WebServerFactoryCustomizer<ConfigurableReactiveWebServerFactory>, EnvironmentAware, Ordered { implements WebServerFactoryCustomizer<ConfigurableReactiveWebServerFactory>,
EnvironmentAware, Ordered {
private final ServerProperties serverProperties; private final ServerProperties serverProperties;
......
...@@ -192,7 +192,8 @@ public abstract class AbstractErrorWebExceptionHandler ...@@ -192,7 +192,8 @@ public abstract class AbstractErrorWebExceptionHandler
.append("<p>This application has no configured error view, so you are seeing this as a fallback.</p>") .append("<p>This application has no configured error view, so you are seeing this as a fallback.</p>")
.append("<div id='created'>").append(timestamp.toString()) .append("<div id='created'>").append(timestamp.toString())
.append("</div>").append("<div>There was an unexpected error (type=") .append("</div>").append("<div>There was an unexpected error (type=")
.append(HtmlUtils.htmlEscape(error.get("error").toString())).append(", status=") .append(HtmlUtils.htmlEscape(error.get("error").toString()))
.append(", status=")
.append(HtmlUtils.htmlEscape(error.get("status").toString())) .append(HtmlUtils.htmlEscape(error.get("status").toString()))
.append(").</div>").append("<div>") .append(").</div>").append("<div>")
.append(HtmlUtils.htmlEscape(error.get("message").toString())) .append(HtmlUtils.htmlEscape(error.get("message").toString()))
......
...@@ -118,8 +118,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { ...@@ -118,8 +118,8 @@ public class DefaultErrorAttributes implements ErrorAttributes {
errorAttributes.put("trace", stackTrace.toString()); errorAttributes.put("trace", stackTrace.toString());
} }
private void handleException(Map<String, Object> errorAttributes, private void handleException(Map<String, Object> errorAttributes, Throwable error,
Throwable error, boolean includeStackTrace) { boolean includeStackTrace) {
if (this.includeException) { if (this.includeException) {
errorAttributes.put("exception", error.getClass().getName()); errorAttributes.put("exception", error.getClass().getName());
} }
......
...@@ -217,22 +217,23 @@ public class WebMvcAutoConfiguration { ...@@ -217,22 +217,23 @@ public class WebMvcAutoConfiguration {
@Override @Override
public void configurePathMatch(PathMatchConfigurer configurer) { public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(this.mvcProperties configurer.setUseSuffixPatternMatch(
.getPathMatch().isUseSuffixPattern()); this.mvcProperties.getPathMatch().isUseSuffixPattern());
configurer.setUseRegisteredSuffixPatternMatch(this.mvcProperties configurer.setUseRegisteredSuffixPatternMatch(
.getPathMatch().isUseRegisteredSuffixPattern()); this.mvcProperties.getPathMatch().isUseRegisteredSuffixPattern());
} }
@Override @Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
WebMvcProperties.ContentNegotiation contentNegotiation WebMvcProperties.ContentNegotiation contentNegotiation = this.mvcProperties
= this.mvcProperties.getContentNegotiation(); .getContentNegotiation();
configurer.favorPathExtension(contentNegotiation.isFavorPathExtension()); configurer.favorPathExtension(contentNegotiation.isFavorPathExtension());
configurer.favorParameter(contentNegotiation.isFavorParameter()); configurer.favorParameter(contentNegotiation.isFavorParameter());
if (contentNegotiation.getParameterName() != null) { if (contentNegotiation.getParameterName() != null) {
configurer.parameterName(contentNegotiation.getParameterName()); configurer.parameterName(contentNegotiation.getParameterName());
} }
Map<String, MediaType> mediaTypes = this.mvcProperties.getContentNegotiation().getMediaTypes(); Map<String, MediaType> mediaTypes = this.mvcProperties.getContentNegotiation()
.getMediaTypes();
for (Entry<String, MediaType> mediaType : mediaTypes.entrySet()) { for (Entry<String, MediaType> mediaType : mediaTypes.entrySet()) {
configurer.mediaType(mediaType.getKey(), mediaType.getValue()); configurer.mediaType(mediaType.getKey(), mediaType.getValue());
} }
...@@ -324,8 +325,8 @@ public class WebMvcAutoConfiguration { ...@@ -324,8 +325,8 @@ public class WebMvcAutoConfiguration {
registry.addResourceHandler("/webjars/**") registry.addResourceHandler("/webjars/**")
.addResourceLocations( .addResourceLocations(
"classpath:/META-INF/resources/webjars/") "classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)) .setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl)); .setCacheControl(cacheControl));
} }
String staticPathPattern = this.mvcProperties.getStaticPathPattern(); String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) { if (!registry.hasMappingForPattern(staticPathPattern)) {
...@@ -333,8 +334,8 @@ public class WebMvcAutoConfiguration { ...@@ -333,8 +334,8 @@ public class WebMvcAutoConfiguration {
registry.addResourceHandler(staticPathPattern) registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations( .addResourceLocations(getResourceLocations(
this.resourceProperties.getStaticLocations())) this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)) .setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl)); .setCacheControl(cacheControl));
} }
} }
......
...@@ -273,20 +273,21 @@ public class WebMvcProperties { ...@@ -273,20 +273,21 @@ public class WebMvcProperties {
public static class ContentNegotiation { public static class ContentNegotiation {
/** /**
* Whether the path extension in the URL path should be used to determine * Whether the path extension in the URL path should be used to determine the
* the requested media type. If enabled a request "/users.pdf" will be * requested media type. If enabled a request "/users.pdf" will be interpreted as
* interpreted as a request for "application/pdf" regardless of the 'Accept' header. * a request for "application/pdf" regardless of the 'Accept' header.
*/ */
private boolean favorPathExtension = false; private boolean favorPathExtension = false;
/** /**
* Whether a request parameter ("format" by default) should be used to * Whether a request parameter ("format" by default) should be used to determine
* determine the requested media type. * the requested media type.
*/ */
private boolean favorParameter = false; private boolean favorParameter = false;
/** /**
* Maps file extensions to media types for content negotiation, e.g. yml to text/yaml. * Maps file extensions to media types for content negotiation, e.g. yml to
* text/yaml.
*/ */
private Map<String, MediaType> mediaTypes = new LinkedHashMap<>(); private Map<String, MediaType> mediaTypes = new LinkedHashMap<>();
...@@ -331,16 +332,16 @@ public class WebMvcProperties { ...@@ -331,16 +332,16 @@ public class WebMvcProperties {
public static class PathMatch { public static class PathMatch {
/** /**
* Whether to use suffix pattern match (".*") when matching patterns to * Whether to use suffix pattern match (".*") when matching patterns to requests.
* requests. If enabled a method mapped to "/users" also matches to "/users.*". * If enabled a method mapped to "/users" also matches to "/users.*".
*/ */
private boolean useSuffixPattern = false; private boolean useSuffixPattern = false;
/** /**
* Whether suffix pattern matching should work only against extensions * Whether suffix pattern matching should work only against extensions registered
* registered with "spring.mvc.content-negotiation.media-types.*". * with "spring.mvc.content-negotiation.media-types.*". This is generally
* This is generally recommended to reduce ambiguity and to * recommended to reduce ambiguity and to avoid issues such as when a "." appears
* avoid issues such as when a "." appears in the path for other reasons. * in the path for other reasons.
*/ */
private boolean useRegisteredSuffixPattern = false; private boolean useRegisteredSuffixPattern = false;
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -35,9 +35,7 @@ import org.springframework.messaging.converter.MessageConverter; ...@@ -35,9 +35,7 @@ import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.converter.StringMessageConverter; import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration; import org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration;
import org.springframework.util.MimeTypeUtils; import org.springframework.util.MimeTypeUtils;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration; import org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/** /**
...@@ -56,7 +54,7 @@ public class WebSocketMessagingAutoConfiguration { ...@@ -56,7 +54,7 @@ public class WebSocketMessagingAutoConfiguration {
ObjectMapper.class }) ObjectMapper.class })
@ConditionalOnClass({ ObjectMapper.class, AbstractMessageBrokerConfiguration.class }) @ConditionalOnClass({ ObjectMapper.class, AbstractMessageBrokerConfiguration.class })
static class WebSocketMessageConverterConfiguration static class WebSocketMessageConverterConfiguration
extends AbstractWebSocketMessageBrokerConfigurer { implements WebSocketMessageBrokerConfigurer {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
...@@ -64,11 +62,6 @@ public class WebSocketMessagingAutoConfiguration { ...@@ -64,11 +62,6 @@ public class WebSocketMessagingAutoConfiguration {
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
} }
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// The user must register their own endpoints
}
@Override @Override
public boolean configureMessageConverters( public boolean configureMessageConverters(
List<MessageConverter> messageConverters) { List<MessageConverter> messageConverters) {
......
...@@ -321,8 +321,7 @@ public class CacheAutoConfigurationTests { ...@@ -321,8 +321,7 @@ public class CacheAutoConfigurationTests {
@Test @Test
public void redisCacheWithCustomizers() { public void redisCacheWithCustomizers() {
this.contextRunner this.contextRunner.withUserConfiguration(RedisWithCustomizersConfiguration.class)
.withUserConfiguration(RedisWithCustomizersConfiguration.class)
.withPropertyValues("spring.cache.type=" + "redis") .withPropertyValues("spring.cache.type=" + "redis")
.run(dunno("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); .run(dunno("allCacheManagerCustomizer", "redisCacheManagerCustomizer"));
} }
...@@ -954,8 +953,7 @@ public class CacheAutoConfigurationTests { ...@@ -954,8 +953,7 @@ public class CacheAutoConfigurationTests {
@Bean @Bean
public org.springframework.data.redis.cache.RedisCacheConfiguration customRedisCacheConfiguration() { public org.springframework.data.redis.cache.RedisCacheConfiguration customRedisCacheConfiguration() {
return org.springframework.data.redis.cache.RedisCacheConfiguration return org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig() .defaultCacheConfig().entryTtl(java.time.Duration.ofSeconds(30))
.entryTtl(java.time.Duration.ofSeconds(30))
.prefixKeysWith("bar"); .prefixKeysWith("bar");
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -67,8 +67,8 @@ public class MongoRepositoriesAutoConfigurationTests { ...@@ -67,8 +67,8 @@ public class MongoRepositoriesAutoConfigurationTests {
@Test @Test
public void testNoRepositoryConfiguration() { public void testNoRepositoryConfiguration() {
this.runner.withUserConfiguration(EmptyConfiguration.class).run((context) -> this.runner.withUserConfiguration(EmptyConfiguration.class)
assertThat(context).hasSingleBean(MongoClient.class)); .run((context) -> assertThat(context).hasSingleBean(MongoClient.class));
} }
@Test @Test
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -60,8 +60,7 @@ public class DataSourceInitializerInvokerTests { ...@@ -60,8 +60,7 @@ public class DataSourceInitializerInvokerTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialization-mode=never", .withPropertyValues("spring.datasource.initialization-mode=never",
"spring.datasource.url:jdbc:hsqldb:mem:init-" "spring.datasource.url:jdbc:hsqldb:mem:init-" + UUID.randomUUID());
+ UUID.randomUUID());
@Test @Test
public void dataSourceInitialized() { public void dataSourceInitialized() {
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -194,8 +194,7 @@ public class MailSenderAutoConfigurationTests { ...@@ -194,8 +194,7 @@ public class MailSenderAutoConfigurationTests {
verify(mailSender, never()).testConnection(); verify(mailSender, never()).testConnection();
} }
private Session configureJndiSession(String name) private Session configureJndiSession(String name) throws IllegalStateException {
throws IllegalStateException {
Properties properties = new Properties(); Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties); Session session = Session.getDefaultInstance(properties);
TestableInitialContextFactory.bind(name, session); TestableInitialContextFactory.bind(name, session);
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -63,7 +63,8 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests { ...@@ -63,7 +63,8 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests {
context.refresh(); context.refresh();
int port = context.getWebServer().getPort(); int port = context.getWebServer().getPort();
String password = this.outputCapture.toString() String password = this.outputCapture.toString()
.split("Using generated security password: ")[1].split("\n")[0].trim(); .split("Using generated security password: ")[1].split("\n")[0]
.trim();
new TestRestTemplate("user", password) new TestRestTemplate("user", password)
.getForEntity("http://localhost:" + port, Object.class); .getForEntity("http://localhost:" + port, Object.class);
// If early initialization occurred a ConverterNotFoundException is thrown // If early initialization occurred a ConverterNotFoundException is thrown
......
...@@ -153,24 +153,24 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat ...@@ -153,24 +153,24 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat
@Test @Test
public void sessionCookieConfigurationIsPickedUp() { public void sessionCookieConfigurationIsPickedUp() {
new WebApplicationContextRunner( WebApplicationContextRunner webRunner = new WebApplicationContextRunner(
AnnotationConfigServletWebServerApplicationContext::new) AnnotationConfigServletWebServerApplicationContext::new)
.withConfiguration(AutoConfigurations .withConfiguration(AutoConfigurations
.of(ServletWebServerFactoryAutoConfiguration.class)) .of(ServletWebServerFactoryAutoConfiguration.class))
.withUserConfiguration(SessionRepositoryConfiguration.class) .withUserConfiguration(SessionRepositoryConfiguration.class)
.withPropertyValues("server.port=0", .withPropertyValues("server.port=0",
"server.servlet.session.cookie.name=testname") "server.servlet.session.cookie.name=testname");
.run((context) -> { webRunner.run((context) -> {
SessionRepositoryFilter<?> filter = context SessionRepositoryFilter<?> filter = context
.getBean(SessionRepositoryFilter.class); .getBean(SessionRepositoryFilter.class);
CookieHttpSessionIdResolver sessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils CookieHttpSessionIdResolver sessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils
.getField(filter, "httpSessionIdResolver"); .getField(filter, "httpSessionIdResolver");
DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils
.getField(sessionIdResolver, "cookieSerializer"); .getField(sessionIdResolver, "cookieSerializer");
String cookieName = (String) ReflectionTestUtils String cookieName = (String) ReflectionTestUtils.getField(cookieSerializer,
.getField(cookieSerializer, "cookieName"); "cookieName");
assertThat(cookieName).isEqualTo("testname"); assertThat(cookieName).isEqualTo("testname");
}); });
} }
@Configuration @Configuration
......
...@@ -170,7 +170,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -170,7 +170,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
public void defaultTomcatBackgroundProcessorDelay() { public void defaultTomcatBackgroundProcessorDelay() {
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory();
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer webServer = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer webServer = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
assertThat(webServer.getTomcat().getEngine().getBackgroundProcessorDelay()) assertThat(webServer.getTomcat().getEngine().getBackgroundProcessorDelay())
.isEqualTo(30); .isEqualTo(30);
webServer.stop(); webServer.stop();
...@@ -183,7 +184,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -183,7 +184,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory();
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer webServer = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer webServer = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
assertThat(webServer.getTomcat().getEngine().getBackgroundProcessorDelay()) assertThat(webServer.getTomcat().getEngine().getBackgroundProcessorDelay())
.isEqualTo(5); .isEqualTo(5);
webServer.stop(); webServer.stop();
...@@ -261,7 +263,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -261,7 +263,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0);
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer server = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer server = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
server.start(); server.start();
try { try {
assertThat(((AbstractProtocol<?>) server.getTomcat().getConnector() assertThat(((AbstractProtocol<?>) server.getTomcat().getConnector()
...@@ -279,7 +282,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -279,7 +282,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0);
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer server = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer server = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
server.start(); server.start();
try { try {
assertThat(((AbstractProtocol<?>) server.getTomcat().getConnector() assertThat(((AbstractProtocol<?>) server.getTomcat().getConnector()
...@@ -297,7 +301,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -297,7 +301,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0);
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer server = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer server = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
server.start(); server.start();
try { try {
assertThat(server.getTomcat().getConnector().getMaxPostSize()) assertThat(server.getTomcat().getConnector().getMaxPostSize())
...@@ -315,7 +320,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -315,7 +320,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0);
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer server = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer server = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
server.start(); server.start();
try { try {
assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1); assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1);
...@@ -340,7 +346,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -340,7 +346,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
bindProperties(map); bindProperties(map);
TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0); TomcatReactiveWebServerFactory factory = new TomcatReactiveWebServerFactory(0);
this.customizer.customize(factory); this.customizer.customize(factory);
TomcatWebServer server = (TomcatWebServer) factory.getWebServer(mock(HttpHandler.class)); TomcatWebServer server = (TomcatWebServer) factory
.getWebServer(mock(HttpHandler.class));
server.start(); server.start();
try { try {
Tomcat tomcat = server.getTomcat(); Tomcat tomcat = server.getTomcat();
...@@ -382,7 +389,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -382,7 +389,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
map.put("server.jetty.accesslog.enabled", "true"); map.put("server.jetty.accesslog.enabled", "true");
bindProperties(map); bindProperties(map);
this.customizer.customize(factory); this.customizer.customize(factory);
JettyWebServer webServer = (JettyWebServer) factory.getWebServer(mock(HttpHandler.class)); JettyWebServer webServer = (JettyWebServer) factory
.getWebServer(mock(HttpHandler.class));
try { try {
NCSARequestLog requestLog = getNCSARequestLog(webServer); NCSARequestLog requestLog = getNCSARequestLog(webServer);
assertThat(requestLog.getFilename()).isNull(); assertThat(requestLog.getFilename()).isNull();
...@@ -417,7 +425,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -417,7 +425,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
map.put("server.jetty.accesslog.log-latency", "true"); map.put("server.jetty.accesslog.log-latency", "true");
bindProperties(map); bindProperties(map);
this.customizer.customize(factory); this.customizer.customize(factory);
JettyWebServer webServer = (JettyWebServer) factory.getWebServer(mock(HttpHandler.class)); JettyWebServer webServer = (JettyWebServer) factory
.getWebServer(mock(HttpHandler.class));
NCSARequestLog requestLog = getNCSARequestLog(webServer); NCSARequestLog requestLog = getNCSARequestLog(webServer);
try { try {
assertThat(requestLog.getFilename()).isEqualTo(logFile.getAbsolutePath()); assertThat(requestLog.getFilename()).isEqualTo(logFile.getAbsolutePath());
...@@ -461,7 +470,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests { ...@@ -461,7 +470,8 @@ public class DefaultReactiveWebServerFactoryCustomizerTests {
@Test @Test
public void setUseForwardHeadersUndertow() { public void setUseForwardHeadersUndertow() {
this.properties.setUseForwardHeaders(true); this.properties.setUseForwardHeaders(true);
UndertowReactiveWebServerFactory factory = spy(new UndertowReactiveWebServerFactory()); UndertowReactiveWebServerFactory factory = spy(
new UndertowReactiveWebServerFactory());
this.customizer.customize(factory); this.customizer.customize(factory);
verify(factory).setUseForwardHeaders(true); verify(factory).setUseForwardHeaders(true);
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -54,8 +54,9 @@ public class ReactiveWebServerAutoConfigurationTests { ...@@ -54,8 +54,9 @@ public class ReactiveWebServerAutoConfigurationTests {
.hasSize(1); .hasSize(1);
assertThat(this.context.getBeansOfType(WebServerFactoryCustomizer.class)) assertThat(this.context.getBeansOfType(WebServerFactoryCustomizer.class))
.hasSize(1); .hasSize(1);
assertThat(this.context.getBeansOfType(DefaultReactiveWebServerFactoryCustomizer.class)) assertThat(this.context
.hasSize(1); .getBeansOfType(DefaultReactiveWebServerFactoryCustomizer.class))
.hasSize(1);
} }
@Test @Test
......
...@@ -233,8 +233,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { ...@@ -233,8 +233,7 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
.contentType(MediaType.TEXT_HTML).expectBody(String.class) .contentType(MediaType.TEXT_HTML).expectBody(String.class)
.returnResult().getResponseBody(); .returnResult().getResponseBody();
assertThat(body).contains("Whitelabel Error Page") assertThat(body).contains("Whitelabel Error Page")
.doesNotContain("<script>") .doesNotContain("<script>").contains("&lt;script&gt;");
.contains("&lt;script&gt;");
this.output.expect( this.output.expect(
allOf(containsString("Failed to handle request [GET /html]"), allOf(containsString("Failed to handle request [GET /html]"),
containsString("IllegalStateException"))); containsString("IllegalStateException")));
......
...@@ -471,9 +471,10 @@ public class WebMvcAutoConfigurationTests { ...@@ -471,9 +471,10 @@ public class WebMvcAutoConfigurationTests {
@Test @Test
public void customMediaTypes() { public void customMediaTypes() {
this.contextRunner.withPropertyValues( this.contextRunner
"spring.mvc.content-negotiation.media-types.yaml:text/yaml", .withPropertyValues(
"spring.mvc.content-negotiation.favor-path-extension:true") "spring.mvc.content-negotiation.media-types.yaml:text/yaml",
"spring.mvc.content-negotiation.favor-path-extension:true")
.run((context) -> { .run((context) -> {
RequestMappingHandlerAdapter adapter = context RequestMappingHandlerAdapter adapter = context
.getBean(RequestMappingHandlerAdapter.class); .getBean(RequestMappingHandlerAdapter.class);
...@@ -744,7 +745,8 @@ public class WebMvcAutoConfigurationTests { ...@@ -744,7 +745,8 @@ public class WebMvcAutoConfigurationTests {
@Test @Test
public void defaultPathMatching() { public void defaultPathMatching() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); RequestMappingHandlerMapping handlerMapping = context
.getBean(RequestMappingHandlerMapping.class);
assertThat(handlerMapping.useSuffixPatternMatch()).isFalse(); assertThat(handlerMapping.useSuffixPatternMatch()).isFalse();
assertThat(handlerMapping.useRegisteredSuffixPatternMatch()).isFalse(); assertThat(handlerMapping.useRegisteredSuffixPatternMatch()).isFalse();
}); });
...@@ -756,34 +758,40 @@ public class WebMvcAutoConfigurationTests { ...@@ -756,34 +758,40 @@ public class WebMvcAutoConfigurationTests {
.withPropertyValues("spring.mvc.path-match.use-suffix-pattern:true", .withPropertyValues("spring.mvc.path-match.use-suffix-pattern:true",
"spring.mvc.path-match.use-registered-suffix-pattern:true") "spring.mvc.path-match.use-registered-suffix-pattern:true")
.run((context) -> { .run((context) -> {
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); RequestMappingHandlerMapping handlerMapping = context
assertThat(handlerMapping.useSuffixPatternMatch()).isTrue(); .getBean(RequestMappingHandlerMapping.class);
assertThat(handlerMapping.useRegisteredSuffixPatternMatch()).isTrue(); assertThat(handlerMapping.useSuffixPatternMatch()).isTrue();
}); assertThat(handlerMapping.useRegisteredSuffixPatternMatch()).isTrue();
});
} }
@Test @Test
public void defaultContentNegotiation() { public void defaultContentNegotiation() {
this.contextRunner.run((context) -> { this.contextRunner.run((context) -> {
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); RequestMappingHandlerMapping handlerMapping = context
ContentNegotiationManager contentNegotiationManager = handlerMapping.getContentNegotiationManager(); .getBean(RequestMappingHandlerMapping.class);
ContentNegotiationManager contentNegotiationManager = handlerMapping
.getContentNegotiationManager();
assertThat(contentNegotiationManager.getStrategies()) assertThat(contentNegotiationManager.getStrategies())
.doesNotHaveAnyElementsOfTypes(WebMvcAutoConfiguration .doesNotHaveAnyElementsOfTypes(
.OptionalPathExtensionContentNegotiationStrategy.class); WebMvcAutoConfiguration.OptionalPathExtensionContentNegotiationStrategy.class);
}); });
} }
@Test @Test
public void pathExtensionContentNegotiation() { public void pathExtensionContentNegotiation() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.mvc.content-negotiation.favor-path-extension:true") .withPropertyValues(
"spring.mvc.content-negotiation.favor-path-extension:true")
.run((context) -> { .run((context) -> {
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); RequestMappingHandlerMapping handlerMapping = context
ContentNegotiationManager contentNegotiationManager = handlerMapping.getContentNegotiationManager(); .getBean(RequestMappingHandlerMapping.class);
assertThat(contentNegotiationManager.getStrategies()) ContentNegotiationManager contentNegotiationManager = handlerMapping
.hasAtLeastOneElementOfType(WebMvcAutoConfiguration .getContentNegotiationManager();
.OptionalPathExtensionContentNegotiationStrategy.class); assertThat(contentNegotiationManager.getStrategies())
}); .hasAtLeastOneElementOfType(
WebMvcAutoConfiguration.OptionalPathExtensionContentNegotiationStrategy.class);
});
} }
@Test @Test
...@@ -791,10 +799,13 @@ public class WebMvcAutoConfigurationTests { ...@@ -791,10 +799,13 @@ public class WebMvcAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues("spring.mvc.content-negotiation.favor-parameter:true") .withPropertyValues("spring.mvc.content-negotiation.favor-parameter:true")
.run((context) -> { .run((context) -> {
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); RequestMappingHandlerMapping handlerMapping = context
ContentNegotiationManager contentNegotiationManager = handlerMapping.getContentNegotiationManager(); .getBean(RequestMappingHandlerMapping.class);
ContentNegotiationManager contentNegotiationManager = handlerMapping
.getContentNegotiationManager();
assertThat(contentNegotiationManager.getStrategies()) assertThat(contentNegotiationManager.getStrategies())
.hasAtLeastOneElementOfType(ParameterContentNegotiationStrategy.class); .hasAtLeastOneElementOfType(
ParameterContentNegotiationStrategy.class);
}); });
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -75,7 +75,8 @@ public class WelcomePageHandlerMappingTests { ...@@ -75,7 +75,8 @@ public class WelcomePageHandlerMappingTests {
public void handlesRequestForStaticPageThatAcceptsAll() { public void handlesRequestForStaticPageThatAcceptsAll() {
this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class) this.contextRunner.withUserConfiguration(StaticResourceConfiguration.class)
.run((context) -> MockMvcBuilders.webAppContextSetup(context).build() .run((context) -> MockMvcBuilders.webAppContextSetup(context).build()
.perform(get("/").accept(MediaType.ALL)).andExpect(status().isOk()) .perform(get("/").accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(forwardedUrl("index.html"))); .andExpect(forwardedUrl("index.html")));
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -57,11 +57,11 @@ import org.springframework.stereotype.Controller; ...@@ -57,11 +57,11 @@ import org.springframework.stereotype.Controller;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration; import org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration;
import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.messaging.WebSocketStompClient; import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport; import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport;
import org.springframework.web.socket.sockjs.client.SockJsClient; import org.springframework.web.socket.sockjs.client.SockJsClient;
...@@ -213,7 +213,7 @@ public class WebSocketMessagingAutoConfigurationTests { ...@@ -213,7 +213,7 @@ public class WebSocketMessagingAutoConfigurationTests {
WebSocketMessagingAutoConfiguration.class, WebSocketMessagingAutoConfiguration.class,
DispatcherServletAutoConfiguration.class }) DispatcherServletAutoConfiguration.class })
static class WebSocketMessagingConfiguration static class WebSocketMessagingConfiguration
extends AbstractWebSocketMessageBrokerConfigurer { implements WebSocketMessageBrokerConfigurer {
@Override @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { public void registerStompEndpoints(StompEndpointRegistry registry) {
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -43,8 +43,8 @@ import org.springframework.core.Ordered; ...@@ -43,8 +43,8 @@ import org.springframework.core.Ordered;
* dependencies in the BOM (and its transitives) will be added to the dependency * dependencies in the BOM (and its transitives) will be added to the dependency
* management lookup, so an app can use just the artifact id (e.g. "spring-jdbc") in a * management lookup, so an app can use just the artifact id (e.g. "spring-jdbc") in a
* {@code @Grab}. To install, implement the missing methods and list the class in * {@code @Grab}. To install, implement the missing methods and list the class in
* {@code META-INF/services/org.springframework.boot.cli.compiler.SpringBootAstTransformation}. * {@code META-INF/services/org.springframework.boot.cli.compiler.SpringBootAstTransformation}
* The {@link #getOrder()} value needs to be before * . The {@link #getOrder()} value needs to be before
* {@link DependencyManagementBomTransformation#ORDER}. * {@link DependencyManagementBomTransformation#ORDER}.
* *
* @author Dave Syer * @author Dave Syer
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -40,7 +40,6 @@ public class UserServiceAutoConfiguration { ...@@ -40,7 +40,6 @@ public class UserServiceAutoConfiguration {
return new UserService(properties.getName()); return new UserService(properties.getName());
} }
@ConfigurationProperties("user") @ConfigurationProperties("user")
static class UserProperties { static class UserProperties {
......
...@@ -36,10 +36,7 @@ public class RandomPortWebTestClientExampleTests { ...@@ -36,10 +36,7 @@ public class RandomPortWebTestClientExampleTests {
@Test @Test
public void exampleTest() { public void exampleTest() {
this.webClient.get() this.webClient.get().uri("/").exchange().expectStatus().isOk()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello World"); .expectBody(String.class).isEqualTo("Hello World");
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -38,7 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; ...@@ -38,7 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(properties = { "app.datasource.second.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1", @SpringBootTest(properties = {
"app.datasource.second.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1",
"app.datasource.second.max-total=42" }) "app.datasource.second.max-total=42" })
@Import(SimpleTwoDataSourcesExample.SimpleDataSourcesConfiguration.class) @Import(SimpleTwoDataSourcesExample.SimpleDataSourcesConfiguration.class)
public class SimpleTwoDataSourcesExampleTests { public class SimpleTwoDataSourcesExampleTests {
...@@ -55,7 +56,8 @@ public class SimpleTwoDataSourcesExampleTests { ...@@ -55,7 +56,8 @@ public class SimpleTwoDataSourcesExampleTests {
.startsWith("jdbc:h2:mem:"); .startsWith("jdbc:h2:mem:");
BasicDataSource secondDataSource = this.context.getBean("secondDataSource", BasicDataSource secondDataSource = this.context.getBean("secondDataSource",
BasicDataSource.class); BasicDataSource.class);
assertThat(secondDataSource.getUrl()).isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1"); assertThat(secondDataSource.getUrl())
.isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1");
assertThat(secondDataSource.getMaxTotal()).isEqualTo(42); assertThat(secondDataSource.getMaxTotal()).isEqualTo(42);
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -371,8 +371,7 @@ public abstract class AbstractJsonMarshalTester<T> { ...@@ -371,8 +371,7 @@ public abstract class AbstractJsonMarshalTester<T> {
initFields(testInstance, () -> marshaller); initFields(testInstance, () -> marshaller);
} }
public void initFields(Object testInstance, public void initFields(Object testInstance, final ObjectFactory<M> marshaller) {
final ObjectFactory<M> marshaller) {
Assert.notNull(testInstance, "TestInstance must not be null"); Assert.notNull(testInstance, "TestInstance must not be null");
Assert.notNull(marshaller, "Marshaller must not be null"); Assert.notNull(marshaller, "Marshaller must not be null");
ReflectionUtils.doWithFields(testInstance.getClass(), ReflectionUtils.doWithFields(testInstance.getClass(),
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -131,8 +131,7 @@ public class TestRestTemplateTests { ...@@ -131,8 +131,7 @@ public class TestRestTemplateTests {
ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() { ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() {
@Override @Override
public void doWith(Method method) public void doWith(Method method) throws IllegalArgumentException {
throws IllegalArgumentException {
Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class,
method.getName(), method.getParameterTypes()); method.getName(), method.getParameterTypes());
assertThat(equivalent).as("Method %s not found", method).isNotNull(); assertThat(equivalent).as("Method %s not found", method).isNotNull();
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -155,8 +155,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { ...@@ -155,8 +155,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
} }
/** /**
* Create a new builder instance using {@link StandardCharsets#UTF_8} as the default charset and the * Create a new builder instance using {@link StandardCharsets#UTF_8} as the default
* specified json resource. * charset and the specified json resource.
* @param inputStreams the source input streams * @param inputStreams the source input streams
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
* @throws IOException on error * @throws IOException on error
...@@ -171,7 +171,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder { ...@@ -171,7 +171,8 @@ public final class ConfigurationMetadataRepositoryJsonBuilder {
} }
/** /**
* Create a new builder instance using {@link StandardCharsets#UTF_8} as the default charset. * Create a new builder instance using {@link StandardCharsets#UTF_8} as the default
* charset.
* @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance.
*/ */
public static ConfigurationMetadataRepositoryJsonBuilder create() { public static ConfigurationMetadataRepositoryJsonBuilder create() {
......
...@@ -52,7 +52,7 @@ public class JSONArray { ...@@ -52,7 +52,7 @@ public class JSONArray {
* Creates a {@code JSONArray} with no values. * Creates a {@code JSONArray} with no values.
*/ */
public JSONArray() { public JSONArray() {
this.values = new ArrayList<Object>(); this.values = new ArrayList<>();
} }
/** /**
...@@ -111,7 +111,7 @@ public class JSONArray { ...@@ -111,7 +111,7 @@ public class JSONArray {
throw new JSONException("Not a primitive array: " + array.getClass()); throw new JSONException("Not a primitive array: " + array.getClass());
} }
final int length = Array.getLength(array); final int length = Array.getLength(array);
this.values = new ArrayList<Object>(length); this.values = new ArrayList<>(length);
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
put(JSONObject.wrap(Array.get(array, i))); put(JSONObject.wrap(Array.get(array, i)));
} }
......
...@@ -111,7 +111,7 @@ public class JSONObject { ...@@ -111,7 +111,7 @@ public class JSONObject {
* Creates a {@code JSONObject} with no name/value mappings. * Creates a {@code JSONObject} with no name/value mappings.
*/ */
public JSONObject() { public JSONObject() {
this.nameValuePairs = new HashMap<String, Object>(); this.nameValuePairs = new HashMap<>();
} }
/** /**
...@@ -691,7 +691,7 @@ public class JSONObject { ...@@ -691,7 +691,7 @@ public class JSONObject {
*/ */
public JSONArray names() { public JSONArray names() {
return this.nameValuePairs.isEmpty() ? null return this.nameValuePairs.isEmpty() ? null
: new JSONArray(new ArrayList<String>(this.nameValuePairs.keySet())); : new JSONArray(new ArrayList<>(this.nameValuePairs.keySet()));
} }
/** /**
......
...@@ -109,7 +109,7 @@ public class JSONStringer { ...@@ -109,7 +109,7 @@ public class JSONStringer {
* Unlike the original implementation, this stack isn't limited to 20 levels of * Unlike the original implementation, this stack isn't limited to 20 levels of
* nesting. * nesting.
*/ */
private final List<Scope> stack = new ArrayList<Scope>(); private final List<Scope> stack = new ArrayList<>();
/** /**
* A string containing a full set of spaces for a single level of indentation, or null * A string containing a full set of spaces for a single level of indentation, or null
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -166,7 +166,6 @@ class TypeUtils { ...@@ -166,7 +166,6 @@ class TypeUtils {
return WRAPPER_TO_PRIMITIVE.get(type.toString()); return WRAPPER_TO_PRIMITIVE.get(type.toString());
} }
/** /**
* A visitor that extracts the full qualified name of a type, including generic * A visitor that extracts the full qualified name of a type, including generic
* information. * information.
...@@ -202,7 +201,7 @@ class TypeUtils { ...@@ -202,7 +201,7 @@ class TypeUtils {
if (enclosingElement != null) { if (enclosingElement != null) {
return getQualifiedName(enclosingElement) + "$" return getQualifiedName(enclosingElement) + "$"
+ ((DeclaredType) element.asType()).asElement().getSimpleName() + ((DeclaredType) element.asType()).asElement().getSimpleName()
.toString(); .toString();
} }
if (element instanceof TypeElement) { if (element instanceof TypeElement) {
return ((TypeElement) element).getQualifiedName().toString(); return ((TypeElement) element).getQualifiedName().toString();
......
...@@ -167,7 +167,8 @@ public class JsonMarshaller { ...@@ -167,7 +167,8 @@ public class JsonMarshaller {
private String toString(InputStream inputStream) throws IOException { private String toString(InputStream inputStream) throws IOException {
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); InputStreamReader reader = new InputStreamReader(inputStream,
StandardCharsets.UTF_8);
char[] buffer = new char[BUFFER_SIZE]; char[] buffer = new char[BUFFER_SIZE];
int bytesRead; int bytesRead;
while ((bytesRead = reader.read(buffer)) != -1) { while ((bytesRead = reader.read(buffer)) != -1) {
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -191,8 +191,7 @@ public class TestProject { ...@@ -191,8 +191,7 @@ public class TestProject {
return new File(TestCompiler.SOURCE_FOLDER, TestCompiler.sourcePathFor(type)); return new File(TestCompiler.SOURCE_FOLDER, TestCompiler.sourcePathFor(type));
} }
private static void putContents(File targetFile, String contents) private static void putContents(File targetFile, String contents) throws IOException {
throws IOException {
FileCopyUtils.copy(new StringReader(contents), new FileWriter(targetFile)); FileCopyUtils.copy(new StringReader(contents), new FileWriter(targetFile));
} }
......
...@@ -47,6 +47,7 @@ import org.springframework.util.StringUtils; ...@@ -47,6 +47,7 @@ import org.springframework.util.StringUtils;
final class JavaPluginAction implements PluginApplicationAction { final class JavaPluginAction implements PluginApplicationAction {
private static final String PARAMETERS_COMPILER_ARG = "-parameters"; private static final String PARAMETERS_COMPILER_ARG = "-parameters";
private final SinglePublishedArtifact singlePublishedArtifact; private final SinglePublishedArtifact singlePublishedArtifact;
JavaPluginAction(SinglePublishedArtifact singlePublishedArtifact) { JavaPluginAction(SinglePublishedArtifact singlePublishedArtifact) {
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -86,8 +86,7 @@ public class TestJarFile { ...@@ -86,8 +86,7 @@ public class TestJarFile {
return file; return file;
} }
private void copyToFile(InputStream inputStream, File file) private void copyToFile(InputStream inputStream, File file) throws IOException {
throws IOException {
try (OutputStream outputStream = new FileOutputStream(file)) { try (OutputStream outputStream = new FileOutputStream(file)) {
copy(inputStream, outputStream); copy(inputStream, outputStream);
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -24,8 +24,8 @@ import java.util.Set; ...@@ -24,8 +24,8 @@ import java.util.Set;
* Helper class for resolving placeholders in texts. Usually applied to file paths. * Helper class for resolving placeholders in texts. Usually applied to file paths.
* <p> * <p>
* A text may contain {@code $ ...} placeholders, to be resolved as system properties: * A text may contain {@code $ ...} placeholders, to be resolved as system properties:
* e.g. {@code $ user.dir}. Default values can be supplied using the ":" separator * e.g. {@code $ user.dir}. Default values can be supplied using the ":" separator between
* between key and value. * key and value.
* <p> * <p>
* Adapted from Spring. * Adapted from Spring.
* *
......
...@@ -104,8 +104,8 @@ public class RandomAccessDataFileTests { ...@@ -104,8 +104,8 @@ public class RandomAccessDataFileTests {
public void fileExists() { public void fileExists() {
File file = new File("/does/not/exist"); File file = new File("/does/not/exist");
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage(String.format("File %s must exist", this.thrown.expectMessage(
file.getAbsolutePath())); String.format("File %s must exist", file.getAbsolutePath()));
new RandomAccessDataFile(file); new RandomAccessDataFile(file);
} }
...@@ -120,8 +120,8 @@ public class RandomAccessDataFileTests { ...@@ -120,8 +120,8 @@ public class RandomAccessDataFileTests {
public void fileExistsWithConcurrentReads() { public void fileExistsWithConcurrentReads() {
File file = new File("/does/not/exist"); File file = new File("/does/not/exist");
this.thrown.expect(IllegalArgumentException.class); this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage(String.format("File %s must exist", this.thrown.expectMessage(
file.getAbsolutePath())); String.format("File %s must exist", file.getAbsolutePath()));
new RandomAccessDataFile(file, 1); new RandomAccessDataFile(file, 1);
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -112,7 +112,7 @@ public final class PropertyMapper { ...@@ -112,7 +112,7 @@ public final class PropertyMapper {
if (this.parent != null) { if (this.parent != null) {
return this.parent.from(supplier); return this.parent.from(supplier);
} }
return new Source<T>(new CachingSupplier<>(supplier), (Predicate<T>) ALWAYS); return new Source<>(new CachingSupplier<>(supplier), (Predicate<T>) ALWAYS);
} }
/** /**
...@@ -207,7 +207,7 @@ public final class PropertyMapper { ...@@ -207,7 +207,7 @@ public final class PropertyMapper {
} }
return null; return null;
}; };
return new Source<R>(supplier, predicate); return new Source<>(supplier, predicate);
} }
/** /**
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -351,8 +351,8 @@ public class Binder { ...@@ -351,8 +351,8 @@ public class Binder {
* @return a {@link Binder} instance * @return a {@link Binder} instance
*/ */
public static Binder get(Environment environment) { public static Binder get(Environment environment) {
return new Binder(ConfigurationPropertySources return new Binder(ConfigurationPropertySources.get(environment),
.get(environment), new PropertySourcesPlaceholdersResolver(environment)); new PropertySourcesPlaceholdersResolver(environment));
} }
/** /**
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -51,7 +51,8 @@ class DurationConverter implements GenericConverter { ...@@ -51,7 +51,8 @@ class DurationConverter implements GenericConverter {
private static final Pattern ISO8601 = Pattern.compile("^[\\+\\-]?P.*$"); private static final Pattern ISO8601 = Pattern.compile("^[\\+\\-]?P.*$");
private static final Pattern SIMPLE = Pattern.compile("^([\\+\\-]?\\d+)([a-zA-Z]{0,2})$"); private static final Pattern SIMPLE = Pattern
.compile("^([\\+\\-]?\\d+)([a-zA-Z]{0,2})$");
private static final Map<String, ChronoUnit> UNITS; private static final Map<String, ChronoUnit> UNITS;
...@@ -90,7 +91,8 @@ class DurationConverter implements GenericConverter { ...@@ -90,7 +91,8 @@ class DurationConverter implements GenericConverter {
return Duration.parse(source); return Duration.parse(source);
} }
Matcher matcher = SIMPLE.matcher(source); Matcher matcher = SIMPLE.matcher(source);
Assert.state(matcher.matches(), () -> "'" + source + "' is not a valid duration"); Assert.state(matcher.matches(),
() -> "'" + source + "' is not a valid duration");
long amount = Long.parseLong(matcher.group(1)); long amount = Long.parseLong(matcher.group(1));
ChronoUnit unit = getUnit(matcher.group(2), defaultUnit); ChronoUnit unit = getUnit(matcher.group(2), defaultUnit);
return Duration.of(amount, unit); return Duration.of(amount, unit);
......
...@@ -26,8 +26,8 @@ import org.springframework.util.Assert; ...@@ -26,8 +26,8 @@ import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
/** /**
* {@link ApplicationContext} backed {@link ServerWebExchangeMatcher}. Can work directly with the * {@link ApplicationContext} backed {@link ServerWebExchangeMatcher}. Can work directly
* {@link ApplicationContext}, obtain an existing bean or * with the {@link ApplicationContext}, obtain an existing bean or
* {@link AutowireCapableBeanFactory#createBean(Class, int, boolean) create a new bean} * {@link AutowireCapableBeanFactory#createBean(Class, int, boolean) create a new bean}
* that is autowired in the usual way. * that is autowired in the usual way.
* *
...@@ -38,7 +38,8 @@ import org.springframework.web.server.ServerWebExchange; ...@@ -38,7 +38,8 @@ import org.springframework.web.server.ServerWebExchange;
* @author Madhura Bhave * @author Madhura Bhave
* @since 2.0.0 * @since 2.0.0
*/ */
public abstract class ApplicationContextServerWebExchangeMatcher<C> implements ServerWebExchangeMatcher { public abstract class ApplicationContextServerWebExchangeMatcher<C>
implements ServerWebExchangeMatcher {
private final Class<? extends C> contextClass; private final Class<? extends C> contextClass;
...@@ -101,4 +102,3 @@ public abstract class ApplicationContextServerWebExchangeMatcher<C> implements S ...@@ -101,4 +102,3 @@ public abstract class ApplicationContextServerWebExchangeMatcher<C> implements S
} }
} }
...@@ -178,8 +178,8 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact ...@@ -178,8 +178,8 @@ public class JettyReactiveWebServerFactory extends AbstractReactiveWebServerFact
JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); JettyHandlerWrappers.createGzipHandlerWrapper(getCompression()));
} }
if (StringUtils.hasText(getServerHeader())) { if (StringUtils.hasText(getServerHeader())) {
handler = applyWrapper(handler, handler = applyWrapper(handler, JettyHandlerWrappers
JettyHandlerWrappers.createServerHeaderHandlerWrapper(getServerHeader())); .createServerHeaderHandlerWrapper(getServerHeader()));
} }
return handler; return handler;
} }
......
...@@ -182,8 +182,8 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor ...@@ -182,8 +182,8 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor
JettyHandlerWrappers.createGzipHandlerWrapper(getCompression())); JettyHandlerWrappers.createGzipHandlerWrapper(getCompression()));
} }
if (StringUtils.hasText(getServerHeader())) { if (StringUtils.hasText(getServerHeader())) {
handler = applyWrapper(handler, handler = applyWrapper(handler, JettyHandlerWrappers
JettyHandlerWrappers.createServerHeaderHandlerWrapper(getServerHeader())); .createServerHeaderHandlerWrapper(getServerHeader()));
} }
return handler; return handler;
} }
...@@ -530,7 +530,6 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor ...@@ -530,7 +530,6 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor
} }
} }
private static final class LoaderHidingResource extends Resource { private static final class LoaderHidingResource extends Resource {
private final Resource delegate; private final Resource delegate;
......
...@@ -80,7 +80,6 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac ...@@ -80,7 +80,6 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac
private int backgroundProcessorDelay; private int backgroundProcessorDelay;
/** /**
* Create a new {@link TomcatServletWebServerFactory} instance. * Create a new {@link TomcatServletWebServerFactory} instance.
*/ */
...@@ -304,8 +303,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac ...@@ -304,8 +303,8 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac
} }
/** /**
* Set {@link LifecycleListener}s that should be applied to the Tomcat {@link Context}. * Set {@link LifecycleListener}s that should be applied to the Tomcat
* Calling this method will replace any existing listeners. * {@link Context}. Calling this method will replace any existing listeners.
* @param contextLifecycleListeners the listeners to set * @param contextLifecycleListeners the listeners to set
*/ */
public void setContextLifecycleListeners( public void setContextLifecycleListeners(
......
...@@ -42,8 +42,8 @@ import org.springframework.util.Assert; ...@@ -42,8 +42,8 @@ import org.springframework.util.Assert;
/** /**
* {@link WebServer} that can be used to control a Tomcat web server. Usually this class * {@link WebServer} that can be used to control a Tomcat web server. Usually this class
* should be created using the {@link TomcatReactiveWebServerFactory} * should be created using the {@link TomcatReactiveWebServerFactory} of
* of {@link TomcatServletWebServerFactory}, but not directly. * {@link TomcatServletWebServerFactory}, but not directly.
* *
* @author Brian Clozel * @author Brian Clozel
* @author Kristine Jetzke * @author Kristine Jetzke
......
...@@ -52,7 +52,8 @@ final class UndertowCompressionConfigurer { ...@@ -52,7 +52,8 @@ final class UndertowCompressionConfigurer {
* @param httpHandler the HTTP handler to wrap * @param httpHandler the HTTP handler to wrap
* @return the wrapped HTTP handler if compression is enabled, or the handler itself * @return the wrapped HTTP handler if compression is enabled, or the handler itself
*/ */
public static HttpHandler configureCompression(Compression compression, HttpHandler httpHandler) { public static HttpHandler configureCompression(Compression compression,
HttpHandler httpHandler) {
if (compression == null || !compression.getEnabled()) { if (compression == null || !compression.getEnabled()) {
return httpHandler; return httpHandler;
} }
......
...@@ -77,7 +77,6 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -77,7 +77,6 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
private boolean useForwardHeaders; private boolean useForwardHeaders;
/** /**
* Create a new {@link UndertowReactiveWebServerFactory} instance. * Create a new {@link UndertowReactiveWebServerFactory} instance.
*/ */
...@@ -94,7 +93,8 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -94,7 +93,8 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
} }
@Override @Override
public WebServer getWebServer(org.springframework.http.server.reactive.HttpHandler httpHandler) { public WebServer getWebServer(
org.springframework.http.server.reactive.HttpHandler httpHandler) {
Undertow.Builder builder = createBuilder(getPort()); Undertow.Builder builder = createBuilder(getPort());
HttpHandler handler = createUndertowHandler(httpHandler); HttpHandler handler = createUndertowHandler(httpHandler);
builder.setHandler(handler); builder.setHandler(handler);
...@@ -127,19 +127,22 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -127,19 +127,22 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
return builder; return builder;
} }
private HttpHandler createUndertowHandler(org.springframework.http.server.reactive.HttpHandler httpHandler) { private HttpHandler createUndertowHandler(
org.springframework.http.server.reactive.HttpHandler httpHandler) {
HttpHandler handler = new UndertowHttpHandlerAdapter(httpHandler); HttpHandler handler = new UndertowHttpHandlerAdapter(httpHandler);
if (this.useForwardHeaders) { if (this.useForwardHeaders) {
handler = Handlers.proxyPeerAddress(handler); handler = Handlers.proxyPeerAddress(handler);
} }
handler = UndertowCompressionConfigurer.configureCompression(getCompression(), handler); handler = UndertowCompressionConfigurer.configureCompression(getCompression(),
handler);
if (isAccessLogEnabled()) { if (isAccessLogEnabled()) {
handler = createAccessLogHandler(handler); handler = createAccessLogHandler(handler);
} }
return handler; return handler;
} }
private AccessLogHandler createAccessLogHandler(io.undertow.server.HttpHandler handler) { private AccessLogHandler createAccessLogHandler(
io.undertow.server.HttpHandler handler) {
try { try {
createAccessLogDirectoryIfNecessary(); createAccessLogDirectoryIfNecessary();
String prefix = (this.accessLogPrefix != null ? this.accessLogPrefix String prefix = (this.accessLogPrefix != null ? this.accessLogPrefix
...@@ -175,8 +178,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -175,8 +178,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
new SslBuilderCustomizer(getPort(), getAddress(), getSsl(), getSslStoreProvider()) new SslBuilderCustomizer(getPort(), getAddress(), getSsl(), getSslStoreProvider())
.customize(builder); .customize(builder);
if (getHttp2() != null) { if (getHttp2() != null) {
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, builder.setServerOption(UndertowOptions.ENABLE_HTTP2, getHttp2().isEnabled());
getHttp2().isEnabled());
} }
} }
...@@ -304,6 +306,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF ...@@ -304,6 +306,7 @@ public class UndertowReactiveWebServerFactory extends AbstractReactiveWebServerF
* Undertow {@link io.undertow.Undertow.Builder Builder}. * Undertow {@link io.undertow.Undertow.Builder Builder}.
* @param customizers the customizers to add * @param customizers the customizers to add
*/ */
@Override
public void addBuilderCustomizers(UndertowBuilderCustomizer... customizers) { public void addBuilderCustomizers(UndertowBuilderCustomizer... customizers) {
Assert.notNull(customizers, "Customizers must not be null"); Assert.notNull(customizers, "Customizers must not be null");
this.builderCustomizers.addAll(Arrays.asList(customizers)); this.builderCustomizers.addAll(Arrays.asList(customizers));
......
...@@ -452,6 +452,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac ...@@ -452,6 +452,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac
this.ioThreads = ioThreads; this.ioThreads = ioThreads;
} }
@Override
public void setWorkerThreads(Integer workerThreads) { public void setWorkerThreads(Integer workerThreads) {
this.workerThreads = workerThreads; this.workerThreads = workerThreads;
} }
......
...@@ -35,8 +35,9 @@ import org.springframework.util.ReflectionUtils; ...@@ -35,8 +35,9 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* {@link WebServer} that can be used to control an Undertow web server. Usually this class * {@link WebServer} that can be used to control an Undertow web server. Usually this
* should be created using the {@link UndertowReactiveWebServerFactory} and not directly. * class should be created using the {@link UndertowReactiveWebServerFactory} and not
* directly.
* *
* @author Ivan Sopov * @author Ivan Sopov
* @author Andy Wilkinson * @author Andy Wilkinson
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -125,8 +125,8 @@ public class AnnotationConfigReactiveWebServerApplicationContext ...@@ -125,8 +125,8 @@ public class AnnotationConfigReactiveWebServerApplicationContext
/** /**
* Provide a custom {@link BeanNameGenerator} for use with * Provide a custom {@link BeanNameGenerator} for use with
* {@link AnnotatedBeanDefinitionReader} and/or {@link ClassPathBeanDefinitionScanner}, * {@link AnnotatedBeanDefinitionReader} and/or
* if any. * {@link ClassPathBeanDefinitionScanner}, if any.
* <p> * <p>
* Default is * Default is
* {@link org.springframework.context.annotation.AnnotationBeanNameGenerator}. * {@link org.springframework.context.annotation.AnnotationBeanNameGenerator}.
......
...@@ -58,8 +58,8 @@ public abstract class DynamicRegistrationBean<D extends Registration.Dynamic> ...@@ -58,8 +58,8 @@ public abstract class DynamicRegistrationBean<D extends Registration.Dynamic>
} }
/** /**
* Sets if asynchronous operations are supported for this registration. If not specified * Sets if asynchronous operations are supported for this registration. If not
* defaults to {@code true}. * specified defaults to {@code true}.
* @param asyncSupported if async is supported * @param asyncSupported if async is supported
*/ */
public void setAsyncSupported(boolean asyncSupported) { public void setAsyncSupported(boolean asyncSupported) {
......
...@@ -246,8 +246,8 @@ public class ServletContextInitializerBeans ...@@ -246,8 +246,8 @@ public class ServletContextInitializerBeans
} }
/** /**
* Adapter to convert a given Bean type into a {@link RegistrationBean} (and * Adapter to convert a given Bean type into a {@link RegistrationBean} (and hence a
* hence a {@link ServletContextInitializer}). * {@link ServletContextInitializer}).
*/ */
private interface RegistrationBeanAdapter<T> { private interface RegistrationBeanAdapter<T> {
......
...@@ -123,8 +123,8 @@ public class AnnotationConfigServletWebServerApplicationContext ...@@ -123,8 +123,8 @@ public class AnnotationConfigServletWebServerApplicationContext
/** /**
* Provide a custom {@link BeanNameGenerator} for use with * Provide a custom {@link BeanNameGenerator} for use with
* {@link AnnotatedBeanDefinitionReader} and/or {@link ClassPathBeanDefinitionScanner}, * {@link AnnotatedBeanDefinitionReader} and/or
* if any. * {@link ClassPathBeanDefinitionScanner}, if any.
* <p> * <p>
* Default is * Default is
* {@link org.springframework.context.annotation.AnnotationBeanNameGenerator}. * {@link org.springframework.context.annotation.AnnotationBeanNameGenerator}.
...@@ -169,6 +169,7 @@ public class AnnotationConfigServletWebServerApplicationContext ...@@ -169,6 +169,7 @@ public class AnnotationConfigServletWebServerApplicationContext
* @see #scan(String...) * @see #scan(String...)
* @see #refresh() * @see #refresh()
*/ */
@Override
public final void register(Class<?>... annotatedClasses) { public final void register(Class<?>... annotatedClasses) {
Assert.notEmpty(annotatedClasses, Assert.notEmpty(annotatedClasses,
"At least one annotated class must be specified"); "At least one annotated class must be specified");
...@@ -182,6 +183,7 @@ public class AnnotationConfigServletWebServerApplicationContext ...@@ -182,6 +183,7 @@ public class AnnotationConfigServletWebServerApplicationContext
* @see #register(Class...) * @see #register(Class...)
* @see #refresh() * @see #refresh()
*/ */
@Override
public final void scan(String... basePackages) { public final void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified"); Assert.notEmpty(basePackages, "At least one base package must be specified");
this.basePackages = basePackages; this.basePackages = basePackages;
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -56,7 +56,8 @@ class SessionStoreDirectory { ...@@ -56,7 +56,8 @@ class SessionStoreDirectory {
} }
private void assertDirectory(boolean mkdirs, File dir) { private void assertDirectory(boolean mkdirs, File dir) {
Assert.state(!mkdirs || dir.exists(), () -> "Session dir " + dir + " does not exist"); Assert.state(!mkdirs || dir.exists(),
() -> "Session dir " + dir + " does not exist");
Assert.state(!dir.isFile(), () -> "Session dir " + dir + " points to a file"); Assert.state(!dir.isFile(), () -> "Session dir " + dir + " points to a file");
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -100,8 +100,7 @@ public class ExitCodeGeneratorsTests { ...@@ -100,8 +100,7 @@ public class ExitCodeGeneratorsTests {
return generator; return generator;
} }
private ExitCodeExceptionMapper mockMapper(Class<?> exceptionType, private ExitCodeExceptionMapper mockMapper(Class<?> exceptionType, int exitCode) {
int exitCode) {
return (exception) -> { return (exception) -> {
if (exceptionType.isInstance(exception)) { if (exceptionType.isInstance(exception)) {
return exitCode; return exitCode;
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -137,7 +137,8 @@ public class DurationConverterTests { ...@@ -137,7 +137,8 @@ public class DurationConverterTests {
private Duration convert(String source, ChronoUnit defaultUnit) { private Duration convert(String source, ChronoUnit defaultUnit) {
TypeDescriptor targetType = mock(TypeDescriptor.class); TypeDescriptor targetType = mock(TypeDescriptor.class);
DefaultDurationUnit annotation = AnnotationUtils.synthesizeAnnotation( DefaultDurationUnit annotation = AnnotationUtils.synthesizeAnnotation(
Collections.singletonMap("value", defaultUnit), DefaultDurationUnit.class, null); Collections.singletonMap("value", defaultUnit), DefaultDurationUnit.class,
null);
given(targetType.getAnnotation(DefaultDurationUnit.class)).willReturn(annotation); given(targetType.getAnnotation(DefaultDurationUnit.class)).willReturn(annotation);
return (Duration) this.converter.convert(source, TypeDescriptor.forObject(source), return (Duration) this.converter.convert(source, TypeDescriptor.forObject(source),
targetType); targetType);
......
...@@ -69,8 +69,8 @@ public class LiquibaseServiceLocatorApplicationListenerTests { ...@@ -69,8 +69,8 @@ public class LiquibaseServiceLocatorApplicationListenerTests {
SpringApplication application = new SpringApplication(Conf.class); SpringApplication application = new SpringApplication(Conf.class);
application.setWebApplicationType(WebApplicationType.NONE); application.setWebApplicationType(WebApplicationType.NONE);
DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
resourceLoader.setClassLoader(new ClassHidingClassLoader( resourceLoader.setClassLoader(
CustomResolverServiceLocator.class)); new ClassHidingClassLoader(CustomResolverServiceLocator.class));
application.setResourceLoader(resourceLoader); application.setResourceLoader(resourceLoader);
this.context = application.run(); this.context = application.run();
Object resolver = getServiceLocator(); Object resolver = getServiceLocator();
...@@ -94,7 +94,8 @@ public class LiquibaseServiceLocatorApplicationListenerTests { ...@@ -94,7 +94,8 @@ public class LiquibaseServiceLocatorApplicationListenerTests {
private final List<Class<?>> hiddenClasses; private final List<Class<?>> hiddenClasses;
private ClassHidingClassLoader(Class<?>... hiddenClasses) { private ClassHidingClassLoader(Class<?>... hiddenClasses) {
super(new URL[0], LiquibaseServiceLocatorApplicationListenerTests.class.getClassLoader()); super(new URL[0], LiquibaseServiceLocatorApplicationListenerTests.class
.getClassLoader());
this.hiddenClasses = Arrays.asList(hiddenClasses); this.hiddenClasses = Arrays.asList(hiddenClasses);
} }
......
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -55,34 +55,40 @@ public class ApplicationContextServerWebExchangeMatcherTests { ...@@ -55,34 +55,40 @@ public class ApplicationContextServerWebExchangeMatcherTests {
@Test @Test
public void matchesWhenContextClassIsApplicationContextShouldProvideContext() { public void matchesWhenContextClassIsApplicationContextShouldProvideContext() {
ServerWebExchange exchange = createHttpWebHandlerAdapter(); ServerWebExchange exchange = createHttpWebHandlerAdapter();
StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); StaticApplicationContext context = (StaticApplicationContext) exchange
assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ApplicationContext.class) .getApplicationContext();
.callMatchesAndReturnProvidedContext(exchange)).isEqualTo(context); assertThat(new TestApplicationContextServerWebExchangeMatcher<>(
ApplicationContext.class).callMatchesAndReturnProvidedContext(exchange))
.isEqualTo(context);
} }
@Test @Test
public void matchesWhenContextClassIsExistingBeanShouldProvideBean() { public void matchesWhenContextClassIsExistingBeanShouldProvideBean() {
ServerWebExchange exchange = createHttpWebHandlerAdapter(); ServerWebExchange exchange = createHttpWebHandlerAdapter();
StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); StaticApplicationContext context = (StaticApplicationContext) exchange
.getApplicationContext();
context.registerSingleton("existingBean", ExistingBean.class); context.registerSingleton("existingBean", ExistingBean.class);
assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) assertThat(
.callMatchesAndReturnProvidedContext(exchange)) new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class)
.isEqualTo(context.getBean(ExistingBean.class)); .callMatchesAndReturnProvidedContext(exchange))
.isEqualTo(context.getBean(ExistingBean.class));
} }
@Test @Test
public void matchesWhenContextClassIsNewBeanShouldProvideBean() { public void matchesWhenContextClassIsNewBeanShouldProvideBean() {
ServerWebExchange exchange = createHttpWebHandlerAdapter(); ServerWebExchange exchange = createHttpWebHandlerAdapter();
StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); StaticApplicationContext context = (StaticApplicationContext) exchange
.getApplicationContext();
context.registerSingleton("existingBean", ExistingBean.class); context.registerSingleton("existingBean", ExistingBean.class);
assertThat(new TestApplicationContextServerWebExchangeMatcher<>(NewBean.class) assertThat(new TestApplicationContextServerWebExchangeMatcher<>(NewBean.class)
.callMatchesAndReturnProvidedContext(exchange).getBean()) .callMatchesAndReturnProvidedContext(exchange).getBean())
.isEqualTo(context.getBean(ExistingBean.class)); .isEqualTo(context.getBean(ExistingBean.class));
} }
@Test @Test
public void matchesWhenContextIsNull() { public void matchesWhenContextIsNull() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").build()); MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/path").build());
this.thrown.expect(IllegalStateException.class); this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("No WebApplicationContext found."); this.thrown.expectMessage("No WebApplicationContext found.");
new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class)
...@@ -91,9 +97,11 @@ public class ApplicationContextServerWebExchangeMatcherTests { ...@@ -91,9 +97,11 @@ public class ApplicationContextServerWebExchangeMatcherTests {
private ServerWebExchange createHttpWebHandlerAdapter() { private ServerWebExchange createHttpWebHandlerAdapter() {
StaticApplicationContext context = new StaticApplicationContext(); StaticApplicationContext context = new StaticApplicationContext();
TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(mock(WebHandler.class)); TestHttpWebHandlerAdapter adapter = new TestHttpWebHandlerAdapter(
mock(WebHandler.class));
adapter.setApplicationContext(context); adapter.setApplicationContext(context);
return adapter.createExchange(MockServerHttpRequest.get("/path").build(), new MockServerHttpResponse()); return adapter.createExchange(MockServerHttpRequest.get("/path").build(),
new MockServerHttpResponse());
} }
static class TestHttpWebHandlerAdapter extends HttpWebHandlerAdapter { static class TestHttpWebHandlerAdapter extends HttpWebHandlerAdapter {
...@@ -103,7 +111,8 @@ public class ApplicationContextServerWebExchangeMatcherTests { ...@@ -103,7 +111,8 @@ public class ApplicationContextServerWebExchangeMatcherTests {
} }
@Override @Override
protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { protected ServerWebExchange createExchange(ServerHttpRequest request,
ServerHttpResponse response) {
return super.createExchange(request, response); return super.createExchange(request, response);
} }
...@@ -154,4 +163,3 @@ public class ApplicationContextServerWebExchangeMatcherTests { ...@@ -154,4 +163,3 @@ public class ApplicationContextServerWebExchangeMatcherTests {
} }
} }
...@@ -149,7 +149,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -149,7 +149,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
} }
@Test @Test
public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { public void sslWantsClientAuthenticationSucceedsWithClientCertificate()
throws Exception {
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
ssl.setClientAuth(Ssl.ClientAuth.WANT); ssl.setClientAuth(Ssl.ClientAuth.WANT);
ssl.setKeyStore("classpath:test.jks"); ssl.setKeyStore("classpath:test.jks");
...@@ -159,9 +160,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -159,9 +160,9 @@ public abstract class AbstractReactiveWebServerFactoryTests {
testClientAuthSuccess(ssl, buildTrustAllSslWithClientKeyConnector()); testClientAuthSuccess(ssl, buildTrustAllSslWithClientKeyConnector());
} }
@Test @Test
public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate()
throws Exception {
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
ssl.setClientAuth(Ssl.ClientAuth.WANT); ssl.setClientAuth(Ssl.ClientAuth.WANT);
ssl.setKeyStore("classpath:test.jks"); ssl.setKeyStore("classpath:test.jks");
...@@ -171,12 +172,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -171,12 +172,13 @@ public abstract class AbstractReactiveWebServerFactoryTests {
testClientAuthSuccess(ssl, buildTrustAllSslConnector()); testClientAuthSuccess(ssl, buildTrustAllSslConnector());
} }
protected ReactorClientHttpConnector buildTrustAllSslWithClientKeyConnector() throws Exception { protected ReactorClientHttpConnector buildTrustAllSslWithClientKeyConnector()
throws Exception {
KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientKeyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), clientKeyStore.load(new FileInputStream(new File("src/test/resources/test.jks")),
"secret".toCharArray()); "secret".toCharArray());
KeyManagerFactory clientKeyManagerFactory = KeyManagerFactory clientKeyManagerFactory = KeyManagerFactory
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); .getInstance(KeyManagerFactory.getDefaultAlgorithm());
clientKeyManagerFactory.init(clientKeyStore, "password".toCharArray()); clientKeyManagerFactory.init(clientKeyStore, "password".toCharArray());
return new ReactorClientHttpConnector( return new ReactorClientHttpConnector(
(options) -> options.sslSupport(sslContextBuilder -> { (options) -> options.sslSupport(sslContextBuilder -> {
...@@ -186,7 +188,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -186,7 +188,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
})); }));
} }
protected void testClientAuthSuccess(Ssl sslConfiguration, ReactorClientHttpConnector clientConnector) { protected void testClientAuthSuccess(Ssl sslConfiguration,
ReactorClientHttpConnector clientConnector) {
AbstractReactiveWebServerFactory factory = getFactory(); AbstractReactiveWebServerFactory factory = getFactory();
factory.setSsl(sslConfiguration); factory.setSsl(sslConfiguration);
...@@ -203,7 +206,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -203,7 +206,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
} }
@Test @Test
public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { public void sslNeedsClientAuthenticationSucceedsWithClientCertificate()
throws Exception {
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
ssl.setClientAuth(Ssl.ClientAuth.NEED); ssl.setClientAuth(Ssl.ClientAuth.NEED);
ssl.setKeyStore("classpath:test.jks"); ssl.setKeyStore("classpath:test.jks");
...@@ -214,9 +218,11 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -214,9 +218,11 @@ public abstract class AbstractReactiveWebServerFactoryTests {
} }
@Test @Test
public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { public void sslNeedsClientAuthenticationFailsWithoutClientCertificate()
throws Exception {
// Ignored for Undertow, see https://github.com/reactor/reactor-netty/issues/257 // Ignored for Undertow, see https://github.com/reactor/reactor-netty/issues/257
Assumptions.assumeThat(getFactory()).isNotInstanceOf(UndertowReactiveWebServerFactory.class); Assumptions.assumeThat(getFactory())
.isNotInstanceOf(UndertowReactiveWebServerFactory.class);
Ssl ssl = new Ssl(); Ssl ssl = new Ssl();
ssl.setClientAuth(Ssl.ClientAuth.NEED); ssl.setClientAuth(Ssl.ClientAuth.NEED);
ssl.setKeyStore("classpath:test.jks"); ssl.setKeyStore("classpath:test.jks");
...@@ -226,7 +232,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -226,7 +232,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
testClientAuthFailure(ssl, buildTrustAllSslConnector()); testClientAuthFailure(ssl, buildTrustAllSslConnector());
} }
protected void testClientAuthFailure(Ssl sslConfiguration, ReactorClientHttpConnector clientConnector) { protected void testClientAuthFailure(Ssl sslConfiguration,
ReactorClientHttpConnector clientConnector) {
AbstractReactiveWebServerFactory factory = getFactory(); AbstractReactiveWebServerFactory factory = getFactory();
factory.setSsl(sslConfiguration); factory.setSsl(sslConfiguration);
...@@ -240,17 +247,17 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -240,17 +247,17 @@ public abstract class AbstractReactiveWebServerFactoryTests {
.body(BodyInserters.fromObject("Hello World")).exchange() .body(BodyInserters.fromObject("Hello World")).exchange()
.flatMap((response) -> response.bodyToMono(String.class)); .flatMap((response) -> response.bodyToMono(String.class));
StepVerifier.create(result) StepVerifier.create(result).expectError(SSLException.class)
.expectError(SSLException.class)
.verify(Duration.ofSeconds(10)); .verify(Duration.ofSeconds(10));
} }
protected WebClient.Builder getWebClient() { protected WebClient.Builder getWebClient() {
return getWebClient(options -> { return getWebClient((options) -> {
}); });
} }
protected WebClient.Builder getWebClient(Consumer<? super HttpClientOptions.Builder> clientOptions) { protected WebClient.Builder getWebClient(
Consumer<? super HttpClientOptions.Builder> clientOptions) {
return WebClient.builder() return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(clientOptions)) .clientConnector(new ReactorClientHttpConnector(clientOptions))
.baseUrl("http://localhost:" + this.webServer.getPort()); .baseUrl("http://localhost:" + this.webServer.getPort());
...@@ -259,51 +266,54 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -259,51 +266,54 @@ public abstract class AbstractReactiveWebServerFactoryTests {
@Test @Test
public void compressionOfResponseToGetRequest() throws Exception { public void compressionOfResponseToGetRequest() throws Exception {
WebClient client = prepareCompressionTest(); WebClient client = prepareCompressionTest();
ResponseEntity<Void> response = client.get() ResponseEntity<Void> response = client.get().exchange()
.exchange().flatMap(res -> res.toEntity(Void.class)).block(); .flatMap((res) -> res.toEntity(Void.class)).block();
assertResponseIsCompressed(response); assertResponseIsCompressed(response);
} }
@Test @Test
public void compressionOfResponseToPostRequest() throws Exception { public void compressionOfResponseToPostRequest() throws Exception {
WebClient client = prepareCompressionTest(); WebClient client = prepareCompressionTest();
ResponseEntity<Void> response = client.post() ResponseEntity<Void> response = client.post().exchange()
.exchange().flatMap(res -> res.toEntity(Void.class)).block(); .flatMap((res) -> res.toEntity(Void.class)).block();
assertResponseIsCompressed(response); assertResponseIsCompressed(response);
} }
@Test @Test
public void noCompressionForSmallResponse() throws Exception { public void noCompressionForSmallResponse() throws Exception {
Assumptions.assumeThat(getFactory()).isInstanceOf(NettyReactiveWebServerFactory.class); Assumptions.assumeThat(getFactory())
.isInstanceOf(NettyReactiveWebServerFactory.class);
Compression compression = new Compression(); Compression compression = new Compression();
compression.setEnabled(true); compression.setEnabled(true);
compression.setMinResponseSize(3001); compression.setMinResponseSize(3001);
WebClient client = prepareCompressionTest(compression); WebClient client = prepareCompressionTest(compression);
ResponseEntity<Void> response = client.get() ResponseEntity<Void> response = client.get().exchange()
.exchange().flatMap(res -> res.toEntity(Void.class)).block(); .flatMap((res) -> res.toEntity(Void.class)).block();
assertResponseIsNotCompressed(response); assertResponseIsNotCompressed(response);
} }
@Test @Test
public void noCompressionForMimeType() throws Exception { public void noCompressionForMimeType() throws Exception {
Assumptions.assumeThat(getFactory()).isNotInstanceOf(NettyReactiveWebServerFactory.class); Assumptions.assumeThat(getFactory())
.isNotInstanceOf(NettyReactiveWebServerFactory.class);
Compression compression = new Compression(); Compression compression = new Compression();
compression.setMimeTypes(new String[] {"application/json"}); compression.setMimeTypes(new String[] { "application/json" });
WebClient client = prepareCompressionTest(compression); WebClient client = prepareCompressionTest(compression);
ResponseEntity<Void> response = client.get() ResponseEntity<Void> response = client.get().exchange()
.exchange().flatMap(res -> res.toEntity(Void.class)).block(); .flatMap((res) -> res.toEntity(Void.class)).block();
assertResponseIsNotCompressed(response); assertResponseIsNotCompressed(response);
} }
@Test @Test
public void noCompressionForUserAgent() throws Exception { public void noCompressionForUserAgent() throws Exception {
Assumptions.assumeThat(getFactory()).isNotInstanceOf(NettyReactiveWebServerFactory.class); Assumptions.assumeThat(getFactory())
.isNotInstanceOf(NettyReactiveWebServerFactory.class);
Compression compression = new Compression(); Compression compression = new Compression();
compression.setEnabled(true); compression.setEnabled(true);
compression.setExcludedUserAgents(new String[] { "testUserAgent" }); compression.setExcludedUserAgents(new String[] { "testUserAgent" });
WebClient client = prepareCompressionTest(compression); WebClient client = prepareCompressionTest(compression);
ResponseEntity<Void> response = client.get().header("User-Agent", "testUserAgent") ResponseEntity<Void> response = client.get().header("User-Agent", "testUserAgent")
.exchange().flatMap(res -> res.toEntity(Void.class)).block(); .exchange().flatMap((res) -> res.toEntity(Void.class)).block();
assertResponseIsNotCompressed(response); assertResponseIsNotCompressed(response);
} }
...@@ -313,15 +323,17 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -313,15 +323,17 @@ public abstract class AbstractReactiveWebServerFactoryTests {
return prepareCompressionTest(compression); return prepareCompressionTest(compression);
} }
protected WebClient prepareCompressionTest(Compression compression) { protected WebClient prepareCompressionTest(Compression compression) {
AbstractReactiveWebServerFactory factory = getFactory(); AbstractReactiveWebServerFactory factory = getFactory();
factory.setCompression(compression); factory.setCompression(compression);
this.webServer = factory.getWebServer(new CharsHandler(3000, MediaType.TEXT_PLAIN)); this.webServer = factory
.getWebServer(new CharsHandler(3000, MediaType.TEXT_PLAIN));
this.webServer.start(); this.webServer.start();
return getWebClient(options -> options.compression(true).afterChannelInit(channel -> { return getWebClient((options) -> options.compression(true)
channel.pipeline().addBefore(NettyPipeline.HttpDecompressor, .afterChannelInit((channel) -> channel.pipeline().addBefore(
"CompressionTest", new CompressionDetectionHandler()); NettyPipeline.HttpDecompressor, "CompressionTest",
})).build(); new CompressionDetectionHandler()))).build();
} }
protected void assertResponseIsCompressed(ResponseEntity<Void> response) { protected void assertResponseIsCompressed(ResponseEntity<Void> response) {
...@@ -345,7 +357,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { ...@@ -345,7 +357,8 @@ public abstract class AbstractReactiveWebServerFactoryTests {
} }
protected static class CompressionDetectionHandler extends ChannelInboundHandlerAdapter { protected static class CompressionDetectionHandler
extends ChannelInboundHandlerAdapter {
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
......
...@@ -1018,7 +1018,7 @@ public abstract class AbstractServletWebServerFactoryTests { ...@@ -1018,7 +1018,7 @@ public abstract class AbstractServletWebServerFactoryTests {
factory.getSession().getCookie().setHttpOnly(true); factory.getSession().getCookie().setHttpOnly(true);
factory.getSession().getCookie().setSecure(true); factory.getSession().getCookie().setSecure(true);
factory.getSession().getCookie().setMaxAge(Duration.ofMinutes(1)); factory.getSession().getCookie().setMaxAge(Duration.ofMinutes(1));
AtomicReference<ServletContext> contextReference = new AtomicReference<ServletContext>(); AtomicReference<ServletContext> contextReference = new AtomicReference<>();
factory.getWebServer(contextReference::set).start(); factory.getWebServer(contextReference::set).start();
ServletContext servletContext = contextReference.get(); ServletContext servletContext = contextReference.get();
assertThat(servletContext.getEffectiveSessionTrackingModes()) assertThat(servletContext.getEffectiveSessionTrackingModes())
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment