Merge branch '2.0.x'

This commit is contained in:
Andy Wilkinson
2018-05-02 12:22:16 +01:00
10 changed files with 122 additions and 129 deletions

View File

@@ -34,7 +34,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.mock.http.client.reactive.MockClientHttpResponse;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
@@ -49,9 +48,9 @@ import static org.mockito.Mockito.mock;
*/
public class WebClientMetricsAutoConfigurationTests {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner().with(MetricsRun.simple())
.withConfiguration(AutoConfigurations.of(WebClientAutoConfiguration.class));
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.with(MetricsRun.simple())
.withConfiguration(AutoConfigurations.of(WebClientAutoConfiguration.class));
private ClientHttpConnector connector;
@@ -72,8 +71,7 @@ public class WebClientMetricsAutoConfigurationTests {
WebClient webClient = builder.clientConnector(this.connector).build();
MeterRegistry registry = context.getBean(MeterRegistry.class);
assertThat(registry.find("http.client.requests").meter()).isNull();
ClientResponse response = webClient.get()
.uri("http://example.org/projects/{project}", "spring-boot")
webClient.get().uri("http://example.org/projects/{project}", "spring-boot")
.exchange().block();
assertThat(registry.find("http.client.requests")
.tags("uri", "/projects/{project}").meter()).isNotNull();
@@ -83,11 +81,9 @@ public class WebClientMetricsAutoConfigurationTests {
@Test
public void shouldNotOverrideCustomTagsProvider() {
this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class)
.run((context) -> {
assertThat(context)
.getBeans(WebClientExchangeTagsProvider.class)
.hasSize(1).containsKey("customTagProvider");
});
.run((context) -> assertThat(context)
.getBeans(WebClientExchangeTagsProvider.class).hasSize(1)
.containsKey("customTagProvider"));
}
@Test
@@ -97,15 +93,16 @@ public class WebClientMetricsAutoConfigurationTests {
.run((context) -> {
WebClient.Builder builder = context.getBean(WebClient.Builder.class);
WebClient webClient = builder.clientConnector(this.connector).build();
MetricsProperties properties = context.getBean(MetricsProperties.class);
MetricsProperties properties = context
.getBean(MetricsProperties.class);
int maxUriTags = properties.getWeb().getClient().getMaxUriTags();
MeterRegistry registry = context.getBean(MeterRegistry.class);
for (int i = 0; i < maxUriTags + 10; i++) {
webClient.get()
.uri("http://example.org/projects/" + i)
.exchange().block();
webClient.get().uri("http://example.org/projects/" + i).exchange()
.block();
}
assertThat(registry.get("http.client.requests").meters()).hasSize(maxUriTags);
assertThat(registry.get("http.client.requests").meters())
.hasSize(maxUriTags);
assertThat(this.out.toString())
.contains("Reached the maximum number of URI tags "
+ "for 'http.client.requests'");

View File

@@ -38,33 +38,24 @@ import static org.mockito.Mockito.mock;
*/
public class WebFluxMetricsAutoConfigurationTests {
private ReactiveWebApplicationContextRunner contextRunner =
new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
MetricsAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class,
WebFluxMetricsAutoConfiguration.class));
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class,
WebFluxMetricsAutoConfiguration.class));
@Test
public void shouldProvideWebFluxMetricsBeans() {
this.contextRunner
.run((context) -> {
assertThat(context)
.getBeans(MetricsWebFilter.class).hasSize(1);
assertThat(context)
.getBeans(DefaultWebFluxTagsProvider.class).hasSize(1);
});
this.contextRunner.run((context) -> {
assertThat(context).getBeans(MetricsWebFilter.class).hasSize(1);
assertThat(context).getBeans(DefaultWebFluxTagsProvider.class).hasSize(1);
});
}
@Test
public void shouldNotOverrideCustomTagsProvider() {
this.contextRunner
.withUserConfiguration(CustomWebFluxTagsProviderConfig.class)
.run((context) -> {
assertThat(context)
.getBeans(WebFluxTagsProvider.class)
.hasSize(1).containsKey("customWebFluxTagsProvider");
});
this.contextRunner.withUserConfiguration(CustomWebFluxTagsProviderConfig.class)
.run((context) -> assertThat(context).getBeans(WebFluxTagsProvider.class)
.hasSize(1).containsKey("customWebFluxTagsProvider"));
}
@Configuration

View File

@@ -22,8 +22,8 @@ import org.springframework.boot.web.reactive.function.client.WebClientCustomizer
import org.springframework.web.reactive.function.client.WebClient;
/**
* {@link WebClientCustomizer} that configures the {@link WebClient}
* to record request metrics.
* {@link WebClientCustomizer} that configures the {@link WebClient} to record request
* metrics.
*
* @author Brian Clozel
* @since 2.1.0
@@ -33,9 +33,9 @@ public class MetricsWebClientCustomizer implements WebClientCustomizer {
private final MetricsWebClientFilterFunction filterFunction;
/**
* Create a new {@code MetricsWebClientFilterFunction} that will record
* metrics using the given {@code meterRegistry} with tags provided by the
* given {@code tagProvider}.
* Create a new {@code MetricsWebClientFilterFunction} that will record metrics using
* the given {@code meterRegistry} with tags provided by the given
* {@code tagProvider}.
* @param meterRegistry the meter registry
* @param tagProvider the tag provider
* @param metricName the name of the recorded metric
@@ -48,10 +48,11 @@ public class MetricsWebClientCustomizer implements WebClientCustomizer {
@Override
public void customize(WebClient.Builder webClientBuilder) {
webClientBuilder.filters(filterFunctions -> {
webClientBuilder.filters((filterFunctions) -> {
if (!filterFunctions.contains(this.filterFunction)) {
filterFunctions.add(0, this.filterFunction);
}
});
}
}

View File

@@ -48,20 +48,16 @@ public class MetricsWebClientCustomizerTests {
public void customizeShouldAddFilterFunction() {
this.clientBuilder.filter(mock(ExchangeFilterFunction.class));
this.customizer.customize(this.clientBuilder);
this.clientBuilder.filters(filters ->
assertThat(filters)
.hasSize(2)
.first().isInstanceOf(MetricsWebClientFilterFunction.class));
this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(2).first()
.isInstanceOf(MetricsWebClientFilterFunction.class));
}
@Test
public void customizeShouldNotAddDuplicateFilterFunction() {
this.customizer.customize(this.clientBuilder);
this.clientBuilder.filters(filters -> assertThat(filters).hasSize(1));
this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(1));
this.customizer.customize(this.clientBuilder);
this.clientBuilder.filters(filters ->
assertThat(filters)
.hasSize(1)
.first().isInstanceOf(MetricsWebClientFilterFunction.class));
this.clientBuilder.filters((filters) -> assertThat(filters).hasSize(1).first()
.isInstanceOf(MetricsWebClientFilterFunction.class));
}
}

View File

@@ -38,7 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link MetricsWebClientFilterFunction}
*
@@ -46,7 +45,8 @@ import static org.mockito.Mockito.mock;
*/
public class MetricsWebClientFilterFunctionTests {
private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName() + ".uriTemplate";
private static final String URI_TEMPLATE_ATTRIBUTE = WebClient.class.getName()
+ ".uriTemplate";
private MeterRegistry registry;
@@ -62,58 +62,59 @@ public class MetricsWebClientFilterFunctionTests {
this.filterFunction = new MetricsWebClientFilterFunction(this.registry,
new DefaultWebClientExchangeTagsProvider(), "http.client.requests");
this.response = mock(ClientResponse.class);
this.exchange = r -> Mono.just(this.response);
this.exchange = (r) -> Mono.just(this.response);
}
@Test
public void filterShouldRecordTimer() {
ClientRequest request = ClientRequest
.create(HttpMethod.GET, URI.create("http://example.com/projects/spring-boot"))
.build();
ClientRequest request = ClientRequest.create(HttpMethod.GET,
URI.create("http://example.com/projects/spring-boot")).build();
given(this.response.statusCode()).willReturn(HttpStatus.OK);
this.filterFunction.filter(request, this.exchange).block();
assertThat(this.registry.get("http.client.requests")
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "200").timer()
.count()).isEqualTo(1);
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "200")
.timer().count()).isEqualTo(1);
}
@Test
public void filterWhenUriTemplatePresentShouldRecordTimer() {
ClientRequest request = ClientRequest
.create(HttpMethod.GET, URI.create("http://example.com/projects/spring-boot"))
.attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}")
.build();
.create(HttpMethod.GET,
URI.create("http://example.com/projects/spring-boot"))
.attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build();
given(this.response.statusCode()).willReturn(HttpStatus.OK);
this.filterFunction.filter(request, this.exchange).block();
assertThat(this.registry.get("http.client.requests")
.tags("method", "GET", "uri", "/projects/{project}", "status", "200").timer()
.count()).isEqualTo(1);
.tags("method", "GET", "uri", "/projects/{project}", "status", "200")
.timer().count()).isEqualTo(1);
}
@Test
public void filterWhenIoExceptionThrownShouldRecordTimer() {
ClientRequest request = ClientRequest
.create(HttpMethod.GET, URI.create("http://example.com/projects/spring-boot"))
.build();
ExchangeFunction errorExchange = r -> Mono.error(new IOException());
ClientRequest request = ClientRequest.create(HttpMethod.GET,
URI.create("http://example.com/projects/spring-boot")).build();
ExchangeFunction errorExchange = (r) -> Mono.error(new IOException());
this.filterFunction.filter(request, errorExchange)
.onErrorResume(IOException.class, t -> Mono.empty()).block();
assertThat(this.registry.get("http.client.requests")
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "IO_ERROR").timer()
.count()).isEqualTo(1);
.onErrorResume(IOException.class, (t) -> Mono.empty()).block();
assertThat(
this.registry
.get("http.client.requests").tags("method", "GET", "uri",
"/projects/spring-boot", "status", "IO_ERROR")
.timer().count()).isEqualTo(1);
}
@Test
public void filterWhenExceptionThrownShouldRecordTimer() {
ClientRequest request = ClientRequest
.create(HttpMethod.GET, URI.create("http://example.com/projects/spring-boot"))
.build();
ExchangeFunction exchange = r -> Mono.error(new IllegalArgumentException());
ClientRequest request = ClientRequest.create(HttpMethod.GET,
URI.create("http://example.com/projects/spring-boot")).build();
ExchangeFunction exchange = (r) -> Mono.error(new IllegalArgumentException());
this.filterFunction.filter(request, exchange)
.onErrorResume(IllegalArgumentException.class, t -> Mono.empty()).block();
assertThat(this.registry.get("http.client.requests")
.tags("method", "GET", "uri", "/projects/spring-boot", "status", "CLIENT_ERROR").timer()
.count()).isEqualTo(1);
.onErrorResume(IllegalArgumentException.class, (t) -> Mono.empty())
.block();
assertThat(this.registry
.get("http.client.requests").tags("method", "GET", "uri",
"/projects/spring-boot", "status", "CLIENT_ERROR")
.timer().count()).isEqualTo(1);
}
}

View File

@@ -54,8 +54,10 @@ public class MetricsWebFilterTests {
public void filterAddsTagsToRegistry() {
MockServerWebExchange exchange = createExchange("/projects/spring-boot",
"/projects/{project}");
this.webFilter.filter(exchange,
serverWebExchange -> exchange.getResponse().setComplete()).block();
this.webFilter
.filter(exchange,
(serverWebExchange) -> exchange.getResponse().setComplete())
.block();
assertMetricsContainsTag("uri", "/projects/{project}");
assertMetricsContainsTag("status", "200");
}
@@ -64,9 +66,11 @@ public class MetricsWebFilterTests {
public void filterAddsTagsToRegistryForExceptions() {
MockServerWebExchange exchange = createExchange("/projects/spring-boot",
"/projects/{project}");
this.webFilter.filter(exchange,
serverWebExchange -> Mono.error(new IllegalStateException("test error")))
.onErrorResume(t -> {
this.webFilter
.filter(exchange,
(serverWebExchange) -> Mono
.error(new IllegalStateException("test error")))
.onErrorResume((t) -> {
exchange.getResponse().setStatusCodeValue(500);
return exchange.getResponse().setComplete();
}).block();
@@ -78,14 +82,11 @@ public class MetricsWebFilterTests {
public void filterAddsTagsToRegistryForExceptionsAndCommittedResponse() {
MockServerWebExchange exchange = createExchange("/projects/spring-boot",
"/projects/{project}");
this.webFilter.filter(exchange,
serverWebExchange -> {
exchange.getResponse().setStatusCodeValue(500);
return exchange.getResponse().setComplete()
.then(Mono.error(new IllegalStateException("test error")));
})
.onErrorResume(t -> Mono.empty())
.block();
this.webFilter.filter(exchange, (serverWebExchange) -> {
exchange.getResponse().setStatusCodeValue(500);
return exchange.getResponse().setComplete()
.then(Mono.error(new IllegalStateException("test error")));
}).onErrorResume((t) -> Mono.empty()).block();
assertMetricsContainsTag("uri", "/projects/{project}");
assertMetricsContainsTag("status", "500");
}
@@ -94,15 +95,14 @@ public class MetricsWebFilterTests {
PathPatternParser parser = new PathPatternParser();
MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get(path).build());
exchange.getAttributes()
.put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, parser.parse(pathPattern));
exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE,
parser.parse(pathPattern));
return exchange;
}
private void assertMetricsContainsTag(String tagKey, String tagValue) {
assertThat(this.registry.get(REQUEST_METRICS_NAME)
.tag(tagKey, tagValue).timer().count())
.isEqualTo(1);
assertThat(this.registry.get(REQUEST_METRICS_NAME).tag(tagKey, tagValue).timer()
.count()).isEqualTo(1);
}
}

View File

@@ -101,22 +101,25 @@ public class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurat
@Test
public void autoConfigWhenSpringSessionTimeoutIsSetShouldUseThat() {
this.contextRunner.withUserConfiguration(ServerPropertiesConfiguration.class,
SessionRepositoryConfiguration.class)
this.contextRunner
.withUserConfiguration(ServerPropertiesConfiguration.class,
SessionRepositoryConfiguration.class)
.withPropertyValues("server.servlet.session.timeout=1",
"spring.session.timeout=3").run((context) ->
assertThat(context.getBean(SessionProperties.class).getTimeout())
.isEqualTo(Duration.ofSeconds(3)));
"spring.session.timeout=3")
.run((context) -> assertThat(
context.getBean(SessionProperties.class).getTimeout())
.isEqualTo(Duration.ofSeconds(3)));
}
@Test
public void autoConfigWhenSpringSessionTimeoutIsNotSetShouldUseServerSessionTimeout() {
this.contextRunner.withUserConfiguration(ServerPropertiesConfiguration.class,
SessionRepositoryConfiguration.class)
.withPropertyValues("server.servlet.session.timeout=3").run((context) -> {
assertThat(context.getBean(SessionProperties.class).getTimeout())
.isEqualTo(Duration.ofSeconds(3));
});
this.contextRunner
.withUserConfiguration(ServerPropertiesConfiguration.class,
SessionRepositoryConfiguration.class)
.withPropertyValues("server.servlet.session.timeout=3")
.run((context) -> assertThat(
context.getBean(SessionProperties.class).getTimeout())
.isEqualTo(Duration.ofSeconds(3)));
}
@SuppressWarnings("unchecked")

View File

@@ -213,7 +213,8 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo {
* @see #logDisabledFork()
*/
protected boolean enableForkByDefault() {
return hasAgent() || hasJvmArgs() || hasEnvVariables() || hasWorkingDirectorySet();
return hasAgent() || hasJvmArgs() || hasEnvVariables()
|| hasWorkingDirectorySet();
}
private boolean hasAgent() {
@@ -221,13 +222,14 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo {
}
private boolean hasJvmArgs() {
return (this.jvmArguments != null && !this.jvmArguments.isEmpty()) ||
(this.systemPropertyVariables != null
return (this.jvmArguments != null && !this.jvmArguments.isEmpty())
|| (this.systemPropertyVariables != null
&& !this.systemPropertyVariables.isEmpty());
}
private boolean hasEnvVariables() {
return (this.environmentVariables != null && !this.environmentVariables.isEmpty());
return (this.environmentVariables != null
&& !this.environmentVariables.isEmpty());
}
private boolean hasWorkingDirectorySet() {
@@ -259,9 +261,9 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo {
}
if (hasJvmArgs()) {
RunArguments runArguments = resolveJvmArguments();
getLog().warn("Fork mode disabled, ignoring JVM argument(s) ["
+ Arrays.stream(runArguments.asArray()).collect(
Collectors.joining(" ")) + "]");
getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" + Arrays
.stream(runArguments.asArray()).collect(Collectors.joining(" "))
+ "]");
}
if (hasWorkingDirectorySet()) {
getLog().warn("Fork mode disabled, ignoring working directory configuration");
@@ -338,10 +340,8 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo {
protected RunArguments resolveJvmArguments() {
final StringBuilder stringBuilder = new StringBuilder();
if (this.systemPropertyVariables != null) {
stringBuilder.append(this.systemPropertyVariables
.entrySet()
.stream()
.map(e -> SystemPropertyFormatter.format(e.getKey(), e.getValue()))
stringBuilder.append(this.systemPropertyVariables.entrySet().stream()
.map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue()))
.collect(Collectors.joining(" ")));
}
if (this.jvmArguments != null) {

View File

@@ -342,15 +342,16 @@ public class ConfigFileApplicationListener
* properties that are already set.
*/
private void initializeProfiles() {
//The default profile for these purposes is represented as null. We add it
// The default profile for these purposes is represented as null. We add it
// first so that it is processed first and has lowest priority.
this.profiles.add(null);
Set<Profile> activatedViaProperty = getProfilesActivatedViaActiveProfileProperty();
processOtherActiveProfiles(activatedViaProperty);
// Any pre-existing active activeProfiles set via property sources (e.g. System
// Any pre-existing active activeProfiles set via property sources (e.g.
// System
// properties) take precedence over those added in config files.
addActiveProfiles(activatedViaProperty);
if (this.profiles.size() == 1) { //only has null profile
if (this.profiles.size() == 1) { // only has null profile
for (String defaultProfileName : this.environment.getDefaultProfiles()) {
ConfigFileApplicationListener.Profile defaultProfile = new ConfigFileApplicationListener.Profile(
defaultProfileName, true);
@@ -372,9 +373,10 @@ public class ConfigFileApplicationListener
}
private void processOtherActiveProfiles(Set<Profile> activatedViaProperty) {
List<Profile> otherActiveProfiles = Arrays.stream(this.environment.getActiveProfiles())
.map(Profile::new)
.filter(o -> !activatedViaProperty.contains(o)).collect(Collectors.toList());
List<Profile> otherActiveProfiles = Arrays
.stream(this.environment.getActiveProfiles()).map(Profile::new)
.filter((o) -> !activatedViaProperty.contains(o))
.collect(Collectors.toList());
this.profiles.addAll(otherActiveProfiles);
}
@@ -397,7 +399,8 @@ public class ConfigFileApplicationListener
}
private void removeUnprocessedDefaultProfiles() {
this.profiles.removeIf(profile -> (profile != null && profile.isDefaultProfile()));
this.profiles.removeIf(
(profile) -> (profile != null && profile.isDefaultProfile()));
}
private DocumentFilter getPositiveProfileFilter(Profile profile) {

View File

@@ -198,7 +198,7 @@ public class TomcatWebServer implements WebServer {
addPreviouslyRemovedConnectors();
Connector connector = this.tomcat.getConnector();
if (connector != null && this.autoStart) {
startConnector();
performDeferredLoadOnStartup();
}
checkThatConnectorsHaveStarted();
this.started = true;
@@ -272,7 +272,7 @@ public class TomcatWebServer implements WebServer {
}
}
private void startConnector() {
private void performDeferredLoadOnStartup() {
try {
for (Container child : this.tomcat.getHost().findChildren()) {
if (child instanceof TomcatEmbeddedContext) {
@@ -349,4 +349,5 @@ public class TomcatWebServer implements WebServer {
public Tomcat getTomcat() {
return this.tomcat;
}
}