Move ErrorController to autoconfig
This commit is contained in:
@@ -31,10 +31,10 @@ import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping;
|
||||
import org.springframework.boot.actuate.endpoint.mvc.ManagementErrorEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoints;
|
||||
import org.springframework.boot.actuate.web.ErrorController;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
|
||||
import org.springframework.boot.autoconfigure.web.ErrorController;
|
||||
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
|
||||
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainer;
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2014 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.boot.actuate.autoconfigure;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.actuate.web.BasicErrorController;
|
||||
import org.springframework.boot.actuate.web.ErrorController;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
|
||||
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
|
||||
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration.DefaultTemplateResolverConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
|
||||
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
|
||||
import org.springframework.boot.context.embedded.ErrorPage;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.expression.MapAccessor;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.PropertyPlaceholderHelper;
|
||||
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.view.BeanNameViewResolver;
|
||||
|
||||
/**
|
||||
* {@link EnableAutoConfiguration Auto-configuration} to render errors via a MVC error
|
||||
* controller.
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
|
||||
@ConditionalOnWebApplication
|
||||
// Ensure this loads before the main WebMvcAutoConfiguration so that the error View is
|
||||
// available
|
||||
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
|
||||
public class ErrorMvcAutoConfiguration implements EmbeddedServletContainerCustomizer {
|
||||
|
||||
@Value("${error.path:/error}")
|
||||
private String errorPath = "/error";
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
|
||||
public BasicErrorController basicErrorController() {
|
||||
return new BasicErrorController();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customize(ConfigurableEmbeddedServletContainer container) {
|
||||
container.addErrorPages(new ErrorPage(this.errorPath));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnExpression("${error.whitelabel.enabled:true}")
|
||||
@Conditional(ErrorTemplateMissingCondition.class)
|
||||
protected static class WhitelabelErrorViewConfiguration {
|
||||
|
||||
private final SpelView defaultErrorView = new SpelView(
|
||||
"<html><body><h1>Whitelabel Error Page</h1>"
|
||||
+ "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
|
||||
+ "<div id='created'>${timestamp}</div>"
|
||||
+ "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
|
||||
+ "<div>${message}</div>" + "</body></html>");
|
||||
|
||||
@Bean(name = "error")
|
||||
@ConditionalOnMissingBean(name = "error")
|
||||
public View defaultErrorView() {
|
||||
return this.defaultErrorView;
|
||||
}
|
||||
|
||||
// If the user adds @EnableWebMvc then the bean name view resolver from
|
||||
// WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(BeanNameViewResolver.class)
|
||||
public BeanNameViewResolver beanNameViewResolver() {
|
||||
BeanNameViewResolver resolver = new BeanNameViewResolver();
|
||||
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class ErrorTemplateMissingCondition extends SpringBootCondition {
|
||||
|
||||
@Override
|
||||
public ConditionOutcome getMatchOutcome(ConditionContext context,
|
||||
AnnotatedTypeMetadata metadata) {
|
||||
if (ClassUtils.isPresent("org.thymeleaf.spring4.SpringTemplateEngine",
|
||||
context.getClassLoader())) {
|
||||
if (DefaultTemplateResolverConfiguration.templateExists(
|
||||
context.getEnvironment(), context.getResourceLoader(), "error")) {
|
||||
return ConditionOutcome
|
||||
.noMatch("Thymeleaf template found for error view");
|
||||
}
|
||||
}
|
||||
if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig",
|
||||
context.getClassLoader())) {
|
||||
if (WebMvcAutoConfiguration.templateExists(context.getEnvironment(),
|
||||
context.getResourceLoader(), "error")) {
|
||||
return ConditionOutcome.noMatch("JSP template found for error view");
|
||||
}
|
||||
}
|
||||
return ConditionOutcome.match("no error template view detected");
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
private static class SpelView implements View {
|
||||
|
||||
private final String template;
|
||||
|
||||
private final SpelExpressionParser parser = new SpelExpressionParser();
|
||||
|
||||
private final StandardEvaluationContext context = new StandardEvaluationContext();
|
||||
|
||||
private PropertyPlaceholderHelper helper;
|
||||
|
||||
private PlaceholderResolver resolver;
|
||||
|
||||
public SpelView(String template) {
|
||||
this.template = template;
|
||||
this.context.addPropertyAccessor(new MapAccessor());
|
||||
this.helper = new PropertyPlaceholderHelper("${", "}");
|
||||
this.resolver = new PlaceholderResolver() {
|
||||
@Override
|
||||
public String resolvePlaceholder(String name) {
|
||||
Expression expression = SpelView.this.parser.parseExpression(name);
|
||||
Object value = expression.getValue(SpelView.this.context);
|
||||
return value == null ? null : value.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return "text/html";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(Map<String, ?> model, HttpServletRequest request,
|
||||
HttpServletResponse response) throws Exception {
|
||||
if (response.getContentType() == null) {
|
||||
response.setContentType(getContentType());
|
||||
}
|
||||
Map<String, Object> map = new HashMap<String, Object>(model);
|
||||
map.put("path", request.getContextPath());
|
||||
this.context.setRootObject(map);
|
||||
String result = this.helper.replacePlaceholders(this.template, this.resolver);
|
||||
response.getWriter().append(result);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,14 +22,11 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping;
|
||||
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
|
||||
import org.springframework.boot.actuate.web.ErrorController;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
@@ -43,12 +40,12 @@ import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
|
||||
import org.springframework.boot.autoconfigure.security.SecurityPrequisite;
|
||||
import org.springframework.boot.autoconfigure.security.SecurityProperties;
|
||||
import org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.ErrorController;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
@@ -56,12 +53,9 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity.I
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
|
||||
/**
|
||||
* {@link EnableAutoConfiguration Auto-configuration} for security of framework endpoints.
|
||||
@@ -91,19 +85,6 @@ public class ManagementSecurityAutoConfiguration {
|
||||
return new IgnoredPathsWebSecurityConfigurerAdapter();
|
||||
}
|
||||
|
||||
@ConditionalOnWebApplication
|
||||
@ControllerAdvice
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
|
||||
protected static class SecurityExceptionRethrowingAdvice {
|
||||
|
||||
@ExceptionHandler({ AccessDeniedException.class, AuthenticationException.class })
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response,
|
||||
Exception e) throws Exception {
|
||||
throw e;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
protected static class ManagementSecurityPropertiesConfiguration implements
|
||||
SecurityPrequisite {
|
||||
|
||||
@@ -24,10 +24,10 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.actuate.trace.TraceRepository;
|
||||
import org.springframework.boot.actuate.trace.WebRequestTraceFilter;
|
||||
import org.springframework.boot.actuate.web.BasicErrorController;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.web.BasicErrorController;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ package org.springframework.boot.actuate.endpoint.mvc;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.boot.actuate.web.ErrorController;
|
||||
import org.springframework.boot.autoconfigure.web.ErrorController;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@@ -34,7 +34,7 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.boot.actuate.web.BasicErrorController;
|
||||
import org.springframework.boot.autoconfigure.web.BasicErrorController;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2014 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.boot.actuate.web;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactory;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.context.request.RequestAttributes;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
|
||||
|
||||
/**
|
||||
* Basic global error {@link Controller}, rendering servlet container error codes and
|
||||
* messages where available. More specific errors can be handled either using Spring MVC
|
||||
* abstractions (e.g. {@code @ExceptionHandler}) or by adding servlet
|
||||
* {@link AbstractEmbeddedServletContainerFactory#setErrorPages(java.util.Set) container
|
||||
* error pages}.
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
@Controller
|
||||
@ControllerAdvice
|
||||
@Order(0)
|
||||
public class BasicErrorController implements ErrorController {
|
||||
|
||||
private static final String ERROR_KEY = "error";
|
||||
|
||||
private final Log logger = LogFactory.getLog(BasicErrorController.class);
|
||||
|
||||
private DefaultHandlerExceptionResolver resolver = new DefaultHandlerExceptionResolver();
|
||||
|
||||
@Value("${error.path:/error}")
|
||||
private String errorPath;
|
||||
|
||||
@Override
|
||||
public String getErrorPath() {
|
||||
return this.errorPath;
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response,
|
||||
Exception e) throws Exception {
|
||||
this.resolver.resolveException(request, response, null, e);
|
||||
if (response.getStatus() == HttpServletResponse.SC_OK) {
|
||||
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
// There's only one exception so it's easier for the error controller to identify
|
||||
// it this way...
|
||||
request.setAttribute(ErrorController.class.getName(), e);
|
||||
if (e instanceof BindException) {
|
||||
// ... but other error pages might be looking for it here as well
|
||||
request.setAttribute(
|
||||
BindingResult.MODEL_KEY_PREFIX + ((BindException) e).getObjectName(),
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "${error.path:/error}", produces = "text/html")
|
||||
public ModelAndView errorHtml(HttpServletRequest request) {
|
||||
Map<String, Object> map = extract(new ServletRequestAttributes(request), false,
|
||||
false);
|
||||
return new ModelAndView(ERROR_KEY, map);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "${error.path:/error}")
|
||||
@ResponseBody
|
||||
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
|
||||
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
|
||||
String trace = request.getParameter("trace");
|
||||
Map<String, Object> extracted = extract(attributes,
|
||||
trace != null && !"false".equals(trace.toLowerCase()), true);
|
||||
HttpStatus statusCode = getStatus((Integer) extracted.get("status"));
|
||||
return new ResponseEntity<Map<String, Object>>(extracted, statusCode);
|
||||
}
|
||||
|
||||
private HttpStatus getStatus(Integer value) {
|
||||
try {
|
||||
return HttpStatus.valueOf(value);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
return HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> extract(RequestAttributes attributes, boolean trace,
|
||||
boolean log) {
|
||||
Map<String, Object> map = new LinkedHashMap<String, Object>();
|
||||
map.put("timestamp", new Date());
|
||||
try {
|
||||
Throwable error = (Throwable) attributes.getAttribute(
|
||||
ErrorController.class.getName(), RequestAttributes.SCOPE_REQUEST);
|
||||
Object obj = attributes.getAttribute("javax.servlet.error.status_code",
|
||||
RequestAttributes.SCOPE_REQUEST);
|
||||
int status = 999;
|
||||
if (obj != null) {
|
||||
status = (Integer) obj;
|
||||
map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
|
||||
}
|
||||
else {
|
||||
map.put(ERROR_KEY, "None");
|
||||
}
|
||||
map.put("status", status);
|
||||
if (error == null) {
|
||||
error = (Throwable) attributes.getAttribute(
|
||||
"javax.servlet.error.exception", RequestAttributes.SCOPE_REQUEST);
|
||||
}
|
||||
if (error != null) {
|
||||
while (error instanceof ServletException && error.getCause() != null) {
|
||||
error = ((ServletException) error).getCause();
|
||||
}
|
||||
map.put("exception", error.getClass().getName());
|
||||
addMessage(map, error);
|
||||
if (trace) {
|
||||
StringWriter stackTrace = new StringWriter();
|
||||
error.printStackTrace(new PrintWriter(stackTrace));
|
||||
stackTrace.flush();
|
||||
map.put("trace", stackTrace.toString());
|
||||
}
|
||||
if (log) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
else {
|
||||
Object message = attributes.getAttribute("javax.servlet.error.message",
|
||||
RequestAttributes.SCOPE_REQUEST);
|
||||
map.put("message", message == null ? "No message available" : message);
|
||||
}
|
||||
String path = (String) attributes.getAttribute(
|
||||
"javax.servlet.error.request_uri", RequestAttributes.SCOPE_REQUEST);
|
||||
map.put("path", path == null ? "No path available" : path);
|
||||
return map;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
map.put(ERROR_KEY, ex.getClass().getName());
|
||||
map.put("message", ex.getMessage());
|
||||
if (log) {
|
||||
this.logger.error(ex);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
protected void addMessage(Map<String, Object> map, Throwable error) {
|
||||
if (error instanceof BindingResult) {
|
||||
BindingResult result = (BindingResult) error;
|
||||
if (result.getErrorCount() > 0) {
|
||||
map.put("errors", result.getAllErrors());
|
||||
map.put("message",
|
||||
"Validation failed for object='" + result.getObjectName()
|
||||
+ "'. Error count: " + result.getErrorCount());
|
||||
}
|
||||
else {
|
||||
map.put("message", "No errors");
|
||||
}
|
||||
}
|
||||
else {
|
||||
map.put("message", error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2014 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.boot.actuate.web;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.context.request.RequestAttributes;
|
||||
|
||||
/**
|
||||
* Marker interface used to indicate that a {@link Controller @Controller} is used to
|
||||
* render errors.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public interface ErrorController {
|
||||
|
||||
/**
|
||||
* Returns the path of the error page.
|
||||
*/
|
||||
public String getErrorPath();
|
||||
|
||||
/**
|
||||
* Extract a useful model of the error from the request attributes.
|
||||
* @param attributes the request attributes
|
||||
* @param trace flag to indicate that stack trace information should be included
|
||||
* @param log flag to indicate that an error should be logged
|
||||
* @return a model containing error messages and codes etc.
|
||||
*/
|
||||
public Map<String, Object> extract(RequestAttributes attributes, boolean trace,
|
||||
boolean log);
|
||||
|
||||
}
|
||||
@@ -5,7 +5,6 @@ org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.JolokiaAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.ManagementServerPropertiesAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration,\
|
||||
org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration,\
|
||||
|
||||
@@ -29,6 +29,7 @@ import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
|
||||
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.web.ServerProperties;
|
||||
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
|
||||
|
||||
@@ -19,7 +19,7 @@ package org.springframework.boot.actuate.trace;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.actuate.web.BasicErrorController;
|
||||
import org.springframework.boot.autoconfigure.web.BasicErrorController;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.boot.actuate.web;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.DispatcherType;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration;
|
||||
import org.springframework.boot.actuate.web.BasicErrorControllerIntegrationTests.TestConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.RequestBuilder;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.view.AbstractView;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
@SpringApplicationConfiguration(classes = TestConfiguration.class)
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
public class BasicErrorControllerIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDirectAccessForMachineClient() throws Exception {
|
||||
MvcResult response = this.mockMvc.perform(get("/error"))
|
||||
.andExpect(status().is5xxServerError()).andReturn();
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testErrorForMachineClient() throws Exception {
|
||||
MvcResult result = this.mockMvc.perform(get("/"))
|
||||
.andExpect(status().is5xxServerError()).andReturn();
|
||||
MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error"))
|
||||
.andReturn();
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("Expected!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingExceptionForMachineClient() throws Exception {
|
||||
// In a real container the response is carried over into the error dispatcher, but
|
||||
// in the mock a new one is created so we have to assert the status at this
|
||||
// intermediate point
|
||||
MvcResult result = this.mockMvc.perform(get("/bind"))
|
||||
.andExpect(status().is4xxClientError()).andReturn();
|
||||
MvcResult response = this.mockMvc.perform(new ErrorDispatcher(result, "/error"))
|
||||
.andReturn();
|
||||
// And the rendered status code is always wrong (but would be 400 in a real
|
||||
// system)
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("Error count: 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDirectAccessForBrowserClient() throws Exception {
|
||||
MvcResult response = this.mockMvc
|
||||
.perform(get("/error").accept(MediaType.TEXT_HTML))
|
||||
.andExpect(status().isOk()).andReturn();
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("ERROR_BEAN"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class,
|
||||
ManagementSecurityAutoConfiguration.class,
|
||||
EndpointMBeanExportAutoConfiguration.class })
|
||||
public static class TestConfiguration {
|
||||
|
||||
// For manual testing
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TestConfiguration.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public View error() {
|
||||
return new AbstractView() {
|
||||
@Override
|
||||
protected void renderMergedOutputModel(Map<String, Object> model,
|
||||
HttpServletRequest request, HttpServletResponse response)
|
||||
throws Exception {
|
||||
response.getWriter().write("ERROR_BEAN");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@RestController
|
||||
protected static class Errors {
|
||||
|
||||
public String getFoo() {
|
||||
return "foo";
|
||||
}
|
||||
|
||||
@RequestMapping("/")
|
||||
public String home() {
|
||||
throw new IllegalStateException("Expected!");
|
||||
}
|
||||
|
||||
@RequestMapping("/bind")
|
||||
public String bind() throws Exception {
|
||||
BindException error = new BindException(this, "test");
|
||||
error.rejectValue("foo", "bar.error");
|
||||
throw error;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class ErrorDispatcher implements RequestBuilder {
|
||||
|
||||
private MvcResult result;
|
||||
private String path;
|
||||
|
||||
public ErrorDispatcher(MvcResult result, String path) {
|
||||
this.result = result;
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
|
||||
MockHttpServletRequest request = this.result.getRequest();
|
||||
request.setDispatcherType(DispatcherType.ERROR);
|
||||
request.setRequestURI(this.path);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.boot.actuate.web;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public class BasicErrorControllerSpecialIntegrationTests {
|
||||
|
||||
private ConfigurableWebApplicationContext wac;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
if (this.wac != null) {
|
||||
this.wac.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void setup(ConfigurableWebApplicationContext context) {
|
||||
this.wac = context;
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorPageAvailableWithParentContext() throws Exception {
|
||||
setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(
|
||||
ParentConfiguration.class).child(ChildConfiguration.class).run(
|
||||
"--server.port=0"));
|
||||
MvcResult response = this.mockMvc
|
||||
.perform(get("/error").accept(MediaType.TEXT_HTML))
|
||||
.andExpect(status().isOk()).andReturn();
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("status=999"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorPageAvailableWithMvcIncluded() throws Exception {
|
||||
setup((ConfigurableWebApplicationContext) new SpringApplication(
|
||||
WebMvcIncludedConfiguration.class).run("--server.port=0"));
|
||||
MvcResult response = this.mockMvc
|
||||
.perform(get("/error").accept(MediaType.TEXT_HTML))
|
||||
.andExpect(status().isOk()).andReturn();
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("status=999"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class,
|
||||
ManagementSecurityAutoConfiguration.class,
|
||||
EndpointMBeanExportAutoConfiguration.class })
|
||||
protected static class ParentConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class,
|
||||
ManagementSecurityAutoConfiguration.class,
|
||||
EndpointMBeanExportAutoConfiguration.class })
|
||||
@EnableWebMvc
|
||||
protected static class WebMvcIncludedConfiguration {
|
||||
// For manual testing
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebMvcIncludedConfiguration.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class,
|
||||
ManagementSecurityAutoConfiguration.class,
|
||||
EndpointMBeanExportAutoConfiguration.class })
|
||||
protected static class VanillaConfiguration {
|
||||
// For manual testing
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(VanillaConfiguration.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class,
|
||||
ManagementSecurityAutoConfiguration.class,
|
||||
EndpointMBeanExportAutoConfiguration.class })
|
||||
protected static class ChildConfiguration {
|
||||
// For manual testing
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(ParentConfiguration.class).child(
|
||||
ChildConfiguration.class).run(args);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.boot.actuate.web;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.actuate.web.DefaultErrorViewIntegrationTests.TestConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
@SpringApplicationConfiguration(classes = TestConfiguration.class)
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
public class DefaultErrorViewIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testErrorForBrowserClient() throws Exception {
|
||||
MvcResult response = this.mockMvc
|
||||
.perform(get("/error").accept(MediaType.TEXT_HTML))
|
||||
.andExpect(status().isOk()).andReturn();
|
||||
String content = response.getResponse().getContentAsString();
|
||||
assertTrue("Wrong content: " + content, content.contains("<html>"));
|
||||
assertTrue("Wrong content: " + content, content.contains("999"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
public static class TestConfiguration {
|
||||
|
||||
// For manual testing
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TestConfiguration.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user