pull/12767/merge
Phillip Webb 7 years ago
parent dfb9dc2d26
commit 598e9bb842

@ -58,8 +58,8 @@ public class JmxMetricsExportAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) { public JmxMeterRegistry jmxMeterRegistry(JmxConfig jmxConfig, Clock clock) {
return new JmxMeterRegistry(config, clock); return new JmxMeterRegistry(jmxConfig, clock);
} }
} }

@ -59,9 +59,9 @@ public class NewRelicMetricsExportAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig config, public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig,
Clock clock) { Clock clock) {
return new NewRelicMeterRegistry(config, clock); return new NewRelicMeterRegistry(newRelicConfig, clock);
} }
} }

@ -58,9 +58,9 @@ public class WavefrontMetricsExportAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public WavefrontMeterRegistry wavefrontMeterRegistry(WavefrontConfig config, public WavefrontMeterRegistry wavefrontMeterRegistry(WavefrontConfig wavefrontConfig,
Clock clock) { Clock clock) {
return new WavefrontMeterRegistry(config, clock); return new WavefrontMeterRegistry(wavefrontConfig, clock);
} }
} }

@ -57,11 +57,12 @@ public class GraphiteMetricsExportAutoConfigurationTests {
@Test @Test
public void autoConfiguresUseTagsAsPrefix() { public void autoConfiguresUseTagsAsPrefix() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class) this.contextRunner.withUserConfiguration(BaseConfiguration.class)
.withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app") .withPropertyValues(
"management.metrics.export.graphite.tags-as-prefix=app")
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); assertThat(context).hasSingleBean(GraphiteMeterRegistry.class);
GraphiteMeterRegistry registry = context.getBean( GraphiteMeterRegistry registry = context
GraphiteMeterRegistry.class); .getBean(GraphiteMeterRegistry.class);
registry.counter("test.count", Tags.of("app", "myapp")); registry.counter("test.count", Tags.of("app", "myapp"));
assertThat(registry.getDropwizardRegistry().getMeters()) assertThat(registry.getDropwizardRegistry().getMeters())
.containsOnlyKeys("myapp.testCount"); .containsOnlyKeys("myapp.testCount");

@ -126,7 +126,7 @@ public class JmxMetricsExportAutoConfigurationTests {
@Bean @Bean
public JmxConfig customConfig() { public JmxConfig customConfig() {
return k -> null; return (key) -> null;
} }
} }

@ -128,7 +128,7 @@ public class StatsdMetricsExportAutoConfigurationTests {
@Bean @Bean
public StatsdConfig customConfig() { public StatsdConfig customConfig() {
return k -> null; return (key) -> null;
} }
} }

@ -39,14 +39,14 @@ public class WebMvcEndpointChildContextConfigurationTests {
public void contextShouldConfigureRequestContextFilter() { public void contextShouldConfigureRequestContextFilter() {
this.contextRunner this.contextRunner
.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) .withUserConfiguration(WebMvcEndpointChildContextConfiguration.class)
.run(context -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); .run((context) -> assertThat(context)
.hasSingleBean(OrderedRequestContextFilter.class));
} }
@Test @Test
public void contextShouldNotConfigureRequestContextFilterWhenPresent() { public void contextShouldNotConfigureRequestContextFilterWhenPresent() {
this.contextRunner this.contextRunner.withUserConfiguration(ExistingConfig.class,
.withUserConfiguration(ExistingConfig.class, WebMvcEndpointChildContextConfiguration.class) WebMvcEndpointChildContextConfiguration.class).run((context) -> {
.run(context -> {
assertThat(context).hasSingleBean(RequestContextFilter.class); assertThat(context).hasSingleBean(RequestContextFilter.class);
assertThat(context).hasBean("testRequestContextFilter"); assertThat(context).hasBean("testRequestContextFilter");
}); });
@ -54,12 +54,11 @@ public class WebMvcEndpointChildContextConfigurationTests {
@Test @Test
public void contextShouldNotConfigureRequestContextFilterWhenRequestContextListenerPresent() { public void contextShouldNotConfigureRequestContextFilterWhenRequestContextListenerPresent() {
this.contextRunner this.contextRunner.withUserConfiguration(RequestContextListenerConfig.class,
.withUserConfiguration(RequestContextListenerConfig.class, WebMvcEndpointChildContextConfiguration.class).run((context) -> {
WebMvcEndpointChildContextConfiguration.class)
.run(context -> {
assertThat(context).hasSingleBean(RequestContextListener.class); assertThat(context).hasSingleBean(RequestContextListener.class);
assertThat(context).doesNotHaveBean(OrderedRequestContextFilter.class); assertThat(context)
.doesNotHaveBean(OrderedRequestContextFilter.class);
}); });
} }

@ -1,5 +1,5 @@
/* /*
* 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,12 +74,11 @@ public final class WebFluxTags {
*/ */
public static Tag uri(ServerWebExchange exchange) { public static Tag uri(ServerWebExchange exchange) {
if (exchange != null) { if (exchange != null) {
PathPattern pathPattern = exchange.getAttribute( PathPattern pathPattern = exchange
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); .getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
if (pathPattern != null) { if (pathPattern != null) {
return Tag.of("uri", pathPattern.getPatternString()); return Tag.of("uri", pathPattern.getPatternString());
} }
else {
HttpStatus status = exchange.getResponse().getStatusCode(); HttpStatus status = exchange.getResponse().getStatusCode();
if (status != null && status.is3xxRedirection()) { if (status != null && status.is3xxRedirection()) {
return URI_REDIRECTION; return URI_REDIRECTION;
@ -87,7 +86,6 @@ public final class WebFluxTags {
if (status != null && status.equals(HttpStatus.NOT_FOUND)) { if (status != null && status.equals(HttpStatus.NOT_FOUND)) {
return URI_NOT_FOUND; return URI_NOT_FOUND;
} }
}
String path = exchange.getRequest().getPath().value(); String path = exchange.getRequest().getPath().value();
return Tag.of("uri", path.isEmpty() ? "root" : path); return Tag.of("uri", path.isEmpty() ? "root" : path);
} }

@ -30,6 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Tests for {@link WebFluxTags}. * Tests for {@link WebFluxTags}.
*
* @author Brian Clozel * @author Brian Clozel
*/ */
public class WebFluxTagsTests { public class WebFluxTagsTests {
@ -40,14 +41,13 @@ public class WebFluxTagsTests {
@Before @Before
public void setup() { public void setup() {
this.exchange = MockServerWebExchange this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
.from(MockServerHttpRequest.get(""));
} }
@Test @Test
public void uriTagValueIsBestMatchingPatternWhenAvailable() { public void uriTagValueIsBestMatchingPatternWhenAvailable() {
this.exchange.getAttributes().put( this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE,
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring")); this.parser.parse("/spring"));
this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY);
Tag tag = WebFluxTags.uri(this.exchange); Tag tag = WebFluxTags.uri(this.exchange);
assertThat(tag.getValue()).isEqualTo("/spring"); assertThat(tag.getValue()).isEqualTo("/spring");

@ -137,14 +137,15 @@ public class ConditionEvaluationReportMessage {
private Map<String, ConditionAndOutcomes> orderByName( private Map<String, ConditionAndOutcomes> orderByName(
Map<String, ConditionAndOutcomes> outcomes) { Map<String, ConditionAndOutcomes> outcomes) {
MultiValueMap<String, String> map = mapShortNameToFullyQualifiedNames(outcomes.keySet()); MultiValueMap<String, String> map = mapToFullyQualifiedNames(outcomes.keySet());
List<String> shortNames = new ArrayList<>(map.keySet()); List<String> shortNames = new ArrayList<>(map.keySet());
Collections.sort(shortNames); Collections.sort(shortNames);
Map<String, ConditionAndOutcomes> result = new LinkedHashMap<>(); Map<String, ConditionAndOutcomes> result = new LinkedHashMap<>();
for (String shortName : shortNames) { for (String shortName : shortNames) {
List<String> fullyQualifiedNames = map.get(shortName); List<String> fullyQualifiedNames = map.get(shortName);
if (fullyQualifiedNames.size() > 1) { if (fullyQualifiedNames.size() > 1) {
fullyQualifiedNames.forEach(k -> result.put(k, outcomes.get(k))); fullyQualifiedNames.forEach((fullyQualifiedName) -> result
.put(fullyQualifiedName, outcomes.get(fullyQualifiedName)));
} }
else { else {
result.put(shortName, outcomes.get(fullyQualifiedNames.get(0))); result.put(shortName, outcomes.get(fullyQualifiedNames.get(0)));
@ -153,9 +154,10 @@ public class ConditionEvaluationReportMessage {
return result; return result;
} }
private MultiValueMap<String, String> mapShortNameToFullyQualifiedNames(Set<String> keySet) { private MultiValueMap<String, String> mapToFullyQualifiedNames(Set<String> keySet) {
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(); LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
keySet.forEach(k -> map.add(ClassUtils.getShortName(k), k)); keySet.forEach((fullyQualifiedName) -> map
.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName));
return map; return map;
} }

@ -1,5 +1,5 @@
/* /*
* 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.

@ -1,5 +1,5 @@
/* /*
* 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,16 +131,13 @@ public class ConditionEvaluationReportTests {
.getConditionAndOutcomesBySource(); .getConditionAndOutcomesBySource();
assertThat(map.size()).isEqualTo(2); assertThat(map.size()).isEqualTo(2);
Iterator<ConditionAndOutcome> iterator = map.get("a").iterator(); Iterator<ConditionAndOutcome> iterator = map.get("a").iterator();
ConditionAndOutcome conditionAndOutcome = iterator.next(); ConditionAndOutcome conditionAndOutcome = iterator.next();
assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition1); assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition1);
assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome1); assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome1);
conditionAndOutcome = iterator.next(); conditionAndOutcome = iterator.next();
assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition2); assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition2);
assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome2); assertThat(conditionAndOutcome.getOutcome()).isEqualTo(this.outcome2);
assertThat(iterator.hasNext()).isFalse(); assertThat(iterator.hasNext()).isFalse();
iterator = map.get("b").iterator(); iterator = map.get("b").iterator();
conditionAndOutcome = iterator.next(); conditionAndOutcome = iterator.next();
assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition3); assertThat(conditionAndOutcome.getCondition()).isEqualTo(this.condition3);
@ -187,16 +184,13 @@ public class ConditionEvaluationReportTests {
new ConditionOutcome(true, "Message 2")); new ConditionOutcome(true, "Message 2"));
ConditionAndOutcome outcome3 = new ConditionAndOutcome(this.condition3, ConditionAndOutcome outcome3 = new ConditionAndOutcome(this.condition3,
new ConditionOutcome(true, "Message 2")); new ConditionOutcome(true, "Message 2"));
assertThat(outcome1).isEqualTo(outcome1); assertThat(outcome1).isEqualTo(outcome1);
assertThat(outcome1).isNotEqualTo(outcome2); assertThat(outcome1).isNotEqualTo(outcome2);
assertThat(outcome2).isEqualTo(outcome3); assertThat(outcome2).isEqualTo(outcome3);
ConditionAndOutcomes outcomes = new ConditionAndOutcomes(); ConditionAndOutcomes outcomes = new ConditionAndOutcomes();
outcomes.add(this.condition1, new ConditionOutcome(true, "Message 1")); outcomes.add(this.condition1, new ConditionOutcome(true, "Message 1"));
outcomes.add(this.condition2, new ConditionOutcome(true, "Message 2")); outcomes.add(this.condition2, new ConditionOutcome(true, "Message 2"));
outcomes.add(this.condition3, new ConditionOutcome(true, "Message 2")); outcomes.add(this.condition3, new ConditionOutcome(true, "Message 2"));
assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2); assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2);
} }
@ -207,12 +201,10 @@ public class ConditionEvaluationReportTests {
ConditionEvaluationReport report = ConditionEvaluationReport ConditionEvaluationReport report = ConditionEvaluationReport
.get(context.getBeanFactory()); .get(context.getBeanFactory());
String autoconfigKey = MultipartAutoConfiguration.class.getName(); String autoconfigKey = MultipartAutoConfiguration.class.getName();
ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource() ConditionAndOutcomes outcomes = report.getConditionAndOutcomesBySource()
.get(autoconfigKey); .get(autoconfigKey);
assertThat(outcomes).isNotEqualTo(nullValue()); assertThat(outcomes).isNotEqualTo(nullValue());
assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2); assertThat(getNumberOfOutcomes(outcomes)).isEqualTo(2);
List<String> messages = new ArrayList<>(); List<String> messages = new ArrayList<>();
for (ConditionAndOutcome outcome : outcomes) { for (ConditionAndOutcome outcome : outcomes) {
messages.add(outcome.getOutcome().getMessage()); messages.add(outcome.getOutcome().getMessage());
@ -251,10 +243,11 @@ public class ConditionEvaluationReportTests {
context.refresh(); context.refresh();
ConditionEvaluationReport report = ConditionEvaluationReport ConditionEvaluationReport report = ConditionEvaluationReport
.get(context.getBeanFactory()); .get(context.getBeanFactory());
assertThat(report.getConditionAndOutcomesBySource()) assertThat(report.getConditionAndOutcomesBySource()).containsKeys(
.containsKeys("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration", "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration",
"org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration",
"org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration"); "org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration");
context.close();
} }
@Test @Test
@ -267,10 +260,12 @@ public class ConditionEvaluationReportTests {
ConditionEvaluationReport report = ConditionEvaluationReport ConditionEvaluationReport report = ConditionEvaluationReport
.get(context.getBeanFactory()); .get(context.getBeanFactory());
String reportMessage = new ConditionEvaluationReportMessage(report).toString(); String reportMessage = new ConditionEvaluationReportMessage(report).toString();
assertThat(reportMessage) assertThat(reportMessage).contains("WebMvcAutoConfiguration",
.contains("WebMvcAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration",
"org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration"); "org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration");
assertThat(reportMessage).doesNotContain("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); assertThat(reportMessage).doesNotContain(
"org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration");
context.close();
} }
private int getNumberOfOutcomes(ConditionAndOutcomes outcomes) { private int getNumberOfOutcomes(ConditionAndOutcomes outcomes) {

@ -46,8 +46,8 @@ import static org.mockito.Mockito.verify;
public class WebTestClientAutoConfigurationTests { public class WebTestClientAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of( .withConfiguration(
WebTestClientAutoConfiguration.class)); AutoConfigurations.of(WebTestClientAutoConfiguration.class));
@Test @Test
public void shouldNotBeConfiguredWithoutWebHandler() { public void shouldNotBeConfiguredWithoutWebHandler() {
@ -63,8 +63,8 @@ public class WebTestClientAutoConfigurationTests {
.run((context) -> { .run((context) -> {
assertThat(context).hasSingleBean(WebTestClient.class); assertThat(context).hasSingleBean(WebTestClient.class);
assertThat(context).hasSingleBean(CodecCustomizer.class); assertThat(context).hasSingleBean(CodecCustomizer.class);
verify(context.getBean(CodecCustomizer.class)).customize( verify(context.getBean(CodecCustomizer.class))
any(CodecConfigurer.class)); .customize(any(CodecConfigurer.class));
}); });
} }

@ -1,5 +1,5 @@
/* /*
* 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.
@ -212,8 +212,8 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource {
} }
/** /**
* {@link PropertyMapper} that delegates to other {@link PropertyMapper}s. * {@link PropertyMapper} that delegates to other {@link PropertyMapper}s and also
* It also swallows exceptions when the mapping fails. * swallows exceptions when the mapping fails.
*/ */
private static class DelegatingPropertyMapper implements PropertyMapper { private static class DelegatingPropertyMapper implements PropertyMapper {
@ -226,27 +226,22 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource {
@Override @Override
public PropertyMapping[] map( public PropertyMapping[] map(
ConfigurationPropertyName configurationPropertyName) { ConfigurationPropertyName configurationPropertyName) {
List<PropertyMapping> mappings = new ArrayList<>(); return callMappers((mapper) -> mapper.map(configurationPropertyName));
for (PropertyMapper mapper : this.mappers) {
try {
mappings.addAll(Arrays.asList(mapper.map(configurationPropertyName)));
}
catch (Exception ex) {
}
}
return mappings.toArray(new PropertyMapping[] {});
} }
@Override @Override
public PropertyMapping[] map(String propertySourceName) { public PropertyMapping[] map(String propertySourceName) {
return callMappers((mapper) -> mapper.map(propertySourceName));
}
private PropertyMapping[] callMappers(
Function<PropertyMapper, PropertyMapping[]> function) {
List<PropertyMapping> mappings = new ArrayList<>(); List<PropertyMapping> mappings = new ArrayList<>();
for (PropertyMapper mapper : this.mappers) { for (PropertyMapper mapper : this.mappers) {
try { try {
mappings.addAll(Arrays.asList(mapper.map(propertySourceName))); mappings.addAll(Arrays.asList(function.apply(mapper)));
} }
catch (Exception ex) { catch (Exception ex) {
} }
} }
return mappings.toArray(new PropertyMapping[] {}); return mappings.toArray(new PropertyMapping[] {});

@ -1,5 +1,5 @@
/* /*
* 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.

@ -1,5 +1,5 @@
/* /*
* 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.

@ -20,11 +20,13 @@ import java.io.IOException;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpServletResponseWrapper;
@ -65,7 +67,8 @@ public class ErrorPageFilterTests {
private MockHttpServletResponse response = new MockHttpServletResponse(); private MockHttpServletResponse response = new MockHttpServletResponse();
private MockFilterChain chain = new MockFilterChain(); private MockFilterChain chain = new TestFilterChain((request, response, chain) -> {
});
@Rule @Rule
public OutputCapture output = new OutputCapture(); public OutputCapture output = new OutputCapture();
@ -82,15 +85,11 @@ public class ErrorPageFilterTests {
@Test @Test
public void notAnErrorButNotOK() throws Exception { public void notAnErrorButNotOK() throws Exception {
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override response.setStatus(201);
public void doFilter(ServletRequest request, ServletResponse response) chain.call();
throws IOException, ServletException {
((HttpServletResponse) response).setStatus(201);
super.doFilter(request, response);
response.flushBuffer(); response.flushBuffer();
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus())
.isEqualTo(201); .isEqualTo(201);
@ -102,14 +101,8 @@ public class ErrorPageFilterTests {
@Test @Test
public void unauthorizedWithErrorPath() throws Exception { public void unauthorizedWithErrorPath() throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain(
@Override (request, response, chain) -> response.sendError(401, "UNAUTHORIZED"));
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(401, "UNAUTHORIZED");
super.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain HttpServletResponseWrapper wrapper = (HttpServletResponseWrapper) this.chain
@ -126,14 +119,8 @@ public class ErrorPageFilterTests {
public void responseCommitted() throws Exception { public void responseCommitted() throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.response.setCommitted(true); this.response.setCommitted(true);
this.chain = new MockFilterChain() { this.chain = new TestFilterChain(
@Override (request, response, chain) -> response.sendError(400, "BAD"));
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400, "BAD");
super.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse())
@ -146,14 +133,8 @@ public class ErrorPageFilterTests {
@Test @Test
public void responseUncommittedWithoutErrorPage() throws Exception { public void responseUncommittedWithoutErrorPage() throws Exception {
this.chain = new MockFilterChain() { this.chain = new TestFilterChain(
@Override (request, response, chain) -> response.sendError(400, "BAD"));
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400, "BAD");
super.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse())
@ -166,15 +147,10 @@ public class ErrorPageFilterTests {
@Test @Test
public void oncePerRequest() throws Exception { public void oncePerRequest() throws Exception {
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override response.sendError(400, "BAD");
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400, "BAD");
assertThat(request.getAttribute("FILTER.FILTERED")).isNotNull(); assertThat(request.getAttribute("FILTER.FILTERED")).isNotNull();
super.doFilter(request, response); });
}
};
this.filter.init(new MockFilterConfig("FILTER")); this.filter.init(new MockFilterConfig("FILTER"));
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
} }
@ -182,14 +158,8 @@ public class ErrorPageFilterTests {
@Test @Test
public void globalError() throws Exception { public void globalError() throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain(
@Override (request, response, chain) -> response.sendError(400, "BAD"));
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400, "BAD");
super.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(400); .isEqualTo(400);
@ -206,14 +176,8 @@ public class ErrorPageFilterTests {
@Test @Test
public void statusError() throws Exception { public void statusError() throws Exception {
this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain(
@Override (request, response, chain) -> response.sendError(400, "BAD"));
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400, "BAD");
super.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(400); .isEqualTo(400);
@ -230,15 +194,10 @@ public class ErrorPageFilterTests {
@Test @Test
public void statusErrorWithCommittedResponse() throws Exception { public void statusErrorWithCommittedResponse() throws Exception {
this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); this.filter.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override response.sendError(400, "BAD");
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400, "BAD");
response.flushBuffer(); response.flushBuffer();
super.doFilter(request, response); });
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(400); .isEqualTo(400);
@ -249,14 +208,10 @@ public class ErrorPageFilterTests {
@Test @Test
public void exceptionError() throws Exception { public void exceptionError() throws Exception {
this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new RuntimeException("BAD"); throw new RuntimeException("BAD");
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(500); .isEqualTo(500);
@ -281,29 +236,20 @@ public class ErrorPageFilterTests {
@Test @Test
public void exceptionErrorWithCommittedResponse() throws Exception { public void exceptionErrorWithCommittedResponse() throws Exception {
this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
response.flushBuffer(); response.flushBuffer();
throw new RuntimeException("BAD"); throw new RuntimeException("BAD");
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getForwardedUrl()).isNull(); assertThat(this.response.getForwardedUrl()).isNull();
} }
@Test @Test
public void statusCode() throws Exception { public void statusCode() throws Exception {
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override assertThat(response.getStatus()).isEqualTo(200);
public void doFilter(ServletRequest request, ServletResponse response) });
throws IOException, ServletException {
assertThat(((HttpServletResponse) response).getStatus()).isEqualTo(200);
super.doFilter(request, response);
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(200); .isEqualTo(200);
@ -312,14 +258,10 @@ public class ErrorPageFilterTests {
@Test @Test
public void subClassExceptionError() throws Exception { public void subClassExceptionError() throws Exception {
this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new IllegalStateException("BAD"); throw new IllegalStateException("BAD");
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(500); .isEqualTo(500);
@ -355,14 +297,10 @@ public class ErrorPageFilterTests {
throws Exception { throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.request.setAsyncStarted(true); this.request.setAsyncStarted(true);
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new RuntimeException("BAD"); throw new RuntimeException("BAD");
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse())
@ -375,14 +313,10 @@ public class ErrorPageFilterTests {
throws Exception { throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.request.setAsyncStarted(true); this.request.setAsyncStarted(true);
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response) response.sendError(400, "BAD");
throws IOException, ServletException { });
super.doFilter(request, response);
((HttpServletResponse) response).sendError(400, "BAD");
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse())
@ -405,14 +339,10 @@ public class ErrorPageFilterTests {
throws Exception { throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
setUpAsyncDispatch(); setUpAsyncDispatch();
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new RuntimeException("BAD"); throw new RuntimeException("BAD");
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse())
@ -425,14 +355,10 @@ public class ErrorPageFilterTests {
throws Exception { throws Exception {
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
setUpAsyncDispatch(); setUpAsyncDispatch();
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response) response.sendError(400, "BAD");
throws IOException, ServletException { });
super.doFilter(request, response);
((HttpServletResponse) response).sendError(400, "BAD");
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.chain.getRequest()).isEqualTo(this.request); assertThat(this.chain.getRequest()).isEqualTo(this.request);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse())
@ -455,16 +381,10 @@ public class ErrorPageFilterTests {
throws IOException, ServletException { throws IOException, ServletException {
this.request.setServletPath("/test"); this.request.setServletPath("/test");
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
chain.call();
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new RuntimeException(); throw new RuntimeException();
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.output.toString()).contains("request [/test]"); assertThat(this.output.toString()).contains("request [/test]");
} }
@ -475,16 +395,10 @@ public class ErrorPageFilterTests {
this.request.setServletPath("/test"); this.request.setServletPath("/test");
this.request.setPathInfo("/alpha"); this.request.setPathInfo("/alpha");
this.filter.addErrorPages(new ErrorPage("/error")); this.filter.addErrorPages(new ErrorPage("/error"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
chain.call();
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new RuntimeException(); throw new RuntimeException();
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.output.toString()).contains("request [/test/alpha]"); assertThat(this.output.toString()).contains("request [/test/alpha]");
} }
@ -492,14 +406,10 @@ public class ErrorPageFilterTests {
@Test @Test
public void nestedServletExceptionIsUnwrapped() throws Exception { public void nestedServletExceptionIsUnwrapped() throws Exception {
this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500")); this.filter.addErrorPages(new ErrorPage(RuntimeException.class, "/500"));
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override chain.call();
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
super.doFilter(request, response);
throw new NestedServletException("Wrapper", new RuntimeException("BAD")); throw new NestedServletException("Wrapper", new RuntimeException("BAD"));
} });
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()) assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus())
.isEqualTo(500); .isEqualTo(500);
@ -524,15 +434,10 @@ public class ErrorPageFilterTests {
@Test @Test
public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient() public void whenErrorIsSentAndWriterIsFlushedErrorIsSentToTheClient()
throws Exception { throws Exception {
this.chain = new MockFilterChain() { this.chain = new TestFilterChain((request, response, chain) -> {
@Override response.sendError(400);
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
((HttpServletResponse) response).sendError(400);
response.getWriter().flush(); response.getWriter().flush();
super.doFilter(request, response); });
}
};
this.filter.doFilter(this.request, this.response, this.chain); this.filter.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(400); assertThat(this.response.getStatus()).isEqualTo(400);
} }
@ -551,6 +456,45 @@ public class ErrorPageFilterTests {
return this.request.getDispatcher(path).getRequestAttributes(); return this.request.getDispatcher(path).getRequestAttributes();
} }
private static class TestFilterChain extends MockFilterChain {
private final FilterHandler handler;
TestFilterChain(FilterHandler handler) {
this.handler = handler;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
AtomicBoolean called = new AtomicBoolean();
Chain chain = () -> {
if (called.compareAndSet(false, true)) {
super.doFilter(request, response);
}
};
this.handler.handle((HttpServletRequest) request,
(HttpServletResponse) response, chain);
chain.call();
}
}
@FunctionalInterface
private interface FilterHandler {
void handle(HttpServletRequest request, HttpServletResponse response, Chain chain)
throws IOException, ServletException;
}
@FunctionalInterface
private interface Chain {
void call() throws IOException, ServletException;
}
private static final class DispatchRecordingMockHttpServletRequest private static final class DispatchRecordingMockHttpServletRequest
extends MockHttpServletRequest { extends MockHttpServletRequest {

Loading…
Cancel
Save