Revisit Assert to avoid single-arg assert methods (with refined messages)

Issue: SPR-15196
(cherry picked from commit 1b2dc36)
This commit is contained in:
Juergen Hoeller
2017-01-30 22:15:53 +01:00
parent b386be1529
commit 28849e0987
85 changed files with 683 additions and 602 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 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.
@@ -41,6 +41,7 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.ServletContextResourceLoader;
import org.springframework.web.context.support.StandardServletEnvironment;
@@ -78,8 +79,7 @@ import org.springframework.web.context.support.StandardServletEnvironment;
* @see #doPost
*/
@SuppressWarnings("serial")
public abstract class HttpServletBean extends HttpServlet
implements EnvironmentCapable, EnvironmentAware {
public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
@@ -128,7 +128,9 @@ public abstract class HttpServletBean extends HttpServlet
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
@@ -190,7 +192,7 @@ public abstract class HttpServletBean extends HttpServlet
*/
@Override
public void setEnvironment(Environment environment) {
Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
Assert.isInstanceOf(ConfigurableEnvironment.class, environment, "ConfigurableEnvironment required");
this.environment = (ConfigurableEnvironment) environment;
}
@@ -231,12 +233,12 @@ public abstract class HttpServletBean extends HttpServlet
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
throws ServletException {
Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
new HashSet<String>(requiredProperties) : null;
Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty() ?
new HashSet<String>(requiredProperties) : null);
Enumeration<String> en = config.getInitParameterNames();
while (en.hasMoreElements()) {
String property = en.nextElement();
Enumeration<String> paramNames = config.getInitParameterNames();
while (paramNames.hasMoreElements()) {
String property = paramNames.nextElement();
Object value = config.getInitParameter(property);
addPropertyValue(new PropertyValue(property, value));
if (missingProps != null) {
@@ -245,7 +247,7 @@ public abstract class HttpServletBean extends HttpServlet
}
// Fail if we are still missing properties.
if (missingProps != null && missingProps.size() > 0) {
if (!CollectionUtils.isEmpty(missingProps)) {
throw new ServletException(
"Initialization from ServletConfig for servlet '" + config.getServletName() +
"' failed; the following required properties were missing: " +

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -681,8 +681,8 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private final String mappingName;
public MappingRegistration(T mapping, HandlerMethod handlerMethod, List<String> directUrls, String mappingName) {
Assert.notNull(mapping);
Assert.notNull(handlerMethod);
Assert.notNull(mapping, "Mapping must not be null");
Assert.notNull(handlerMethod, "HandlerMethod must not be null");
this.mapping = mapping;
this.handlerMethod = handlerMethod;
this.directUrls = (directUrls != null ? directUrls : Collections.<String>emptyList());
@@ -747,7 +747,7 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private static class EmptyHandler {
public void handle() {
throw new UnsupportedOperationException("not implemented");
throw new UnsupportedOperationException("Not implemented");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -170,6 +170,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
validateHandler(handler, request);
return buildPathExposingHandler(handler, urlPath, urlPath, null);
}
// Pattern match?
List<String> matchingPatterns = new ArrayList<String>();
for (String registeredPattern : this.handlerMap.keySet()) {
@@ -182,20 +183,26 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
}
}
}
String bestPatternMatch = null;
String bestMatch = null;
Comparator<String> patternComparator = getPathMatcher().getPatternComparator(urlPath);
if (!matchingPatterns.isEmpty()) {
Collections.sort(matchingPatterns, patternComparator);
if (logger.isDebugEnabled()) {
logger.debug("Matching patterns for request [" + urlPath + "] are " + matchingPatterns);
}
bestPatternMatch = matchingPatterns.get(0);
bestMatch = matchingPatterns.get(0);
}
if (bestPatternMatch != null) {
handler = this.handlerMap.get(bestPatternMatch);
if (bestMatch != null) {
handler = this.handlerMap.get(bestMatch);
if (handler == null) {
Assert.isTrue(bestPatternMatch.endsWith("/"));
handler = this.handlerMap.get(bestPatternMatch.substring(0, bestPatternMatch.length() - 1));
if (bestMatch.endsWith("/")) {
handler = this.handlerMap.get(bestMatch.substring(0, bestMatch.length() - 1));
}
if (handler == null) {
throw new IllegalStateException(
"Could not find handler for best pattern match [" + bestMatch + "]");
}
}
// Bean name or resolved handler?
if (handler instanceof String) {
@@ -203,13 +210,13 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
handler = getApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPatternMatch, urlPath);
String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestMatch, urlPath);
// There might be multiple 'best patterns', let's make sure we have the correct URI template variables
// for all of them
Map<String, String> uriTemplateVariables = new LinkedHashMap<String, String>();
for (String matchingPattern : matchingPatterns) {
if (patternComparator.compare(bestPatternMatch, matchingPattern) == 0) {
if (patternComparator.compare(bestMatch, matchingPattern) == 0) {
Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath);
Map<String, String> decodedVars = getUrlPathHelper().decodePathVariables(request, vars);
uriTemplateVariables.putAll(decodedVars);
@@ -218,8 +225,9 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
if (logger.isDebugEnabled()) {
logger.debug("URI Template variables for request [" + urlPath + "] are " + uriTemplateVariables);
}
return buildPathExposingHandler(handler, bestPatternMatch, pathWithinMapping, uriTemplateVariables);
return buildPathExposingHandler(handler, bestMatch, pathWithinMapping, uriTemplateVariables);
}
// No handler found...
return null;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -96,7 +96,10 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho
}
DeferredResultAdapter adapter = getAdapterFor(returnValue.getClass());
Assert.notNull(adapter);
if (adapter == null) {
throw new IllegalStateException(
"Could not find DeferredResultAdapter for return value type: " + returnValue.getClass());
}
DeferredResult<?> result = adapter.adaptToDeferredResult(returnValue);
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer);
}
@@ -109,7 +112,7 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho
@Override
public DeferredResult<?> adaptToDeferredResult(Object returnValue) {
Assert.isInstanceOf(DeferredResult.class, returnValue);
Assert.isInstanceOf(DeferredResult.class, returnValue, "DeferredResult expected");
return (DeferredResult<?>) returnValue;
}
}
@@ -122,7 +125,7 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho
@Override
public DeferredResult<?> adaptToDeferredResult(Object returnValue) {
Assert.isInstanceOf(ListenableFuture.class, returnValue);
Assert.isInstanceOf(ListenableFuture.class, returnValue, "ListenableFuture expected");
final DeferredResult<Object> result = new DeferredResult<Object>();
((ListenableFuture<?>) returnValue).addCallback(new ListenableFutureCallback<Object>() {
@Override
@@ -147,7 +150,7 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho
@Override
public DeferredResult<?> adaptToDeferredResult(Object returnValue) {
Assert.isInstanceOf(CompletionStage.class, returnValue);
Assert.isInstanceOf(CompletionStage.class, returnValue, "CompletionStage expected");
final DeferredResult<Object> result = new DeferredResult<Object>();
@SuppressWarnings("unchecked")
CompletionStage<?> future = (CompletionStage<?>) returnValue;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 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.
@@ -46,7 +46,7 @@ public class HttpHeadersReturnValueHandler implements HandlerMethodReturnValueHa
mavContainer.setRequestHandled(true);
Assert.isInstanceOf(HttpHeaders.class, returnValue);
Assert.isInstanceOf(HttpHeaders.class, returnValue, "HttpHeaders expected");
HttpHeaders headers = (HttpHeaders) returnValue;
if (!headers.isEmpty()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -240,7 +240,7 @@ public class MvcUriComponentsBuilder {
* @return a UriComponents instance
*/
public static UriComponentsBuilder fromMethodCall(Object info) {
Assert.isInstanceOf(MethodInvocationInfo.class, info);
Assert.isInstanceOf(MethodInvocationInfo.class, info, "MethodInvocationInfo required");
MethodInvocationInfo invocationInfo = (MethodInvocationInfo) info;
Class<?> controllerType = invocationInfo.getControllerType();
Method method = invocationInfo.getControllerMethod();
@@ -260,7 +260,7 @@ public class MvcUriComponentsBuilder {
* @return a UriComponents instance
*/
public static UriComponentsBuilder fromMethodCall(UriComponentsBuilder builder, Object info) {
Assert.isInstanceOf(MethodInvocationInfo.class, info);
Assert.isInstanceOf(MethodInvocationInfo.class, info, "MethodInvocationInfo required");
MethodInvocationInfo invocationInfo = (MethodInvocationInfo) info;
Class<?> controllerType = invocationInfo.getControllerType();
Method method = invocationInfo.getControllerMethod();
@@ -533,18 +533,13 @@ public class MvcUriComponentsBuilder {
private static WebApplicationContext getWebApplicationContext() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
logger.debug("No request bound to the current thread: is DispatcherSerlvet used?");
logger.debug("No request bound to the current thread: not in a DispatcherServlet request?");
return null;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
if (request == null) {
logger.debug("Request bound to current thread is not an HttpServletRequest");
return null;
}
String attributeName = DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext wac = (WebApplicationContext) request.getAttribute(attributeName);
WebApplicationContext wac = (WebApplicationContext)
request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (wac == null) {
logger.debug("No WebApplicationContext found: not in a DispatcherServlet request?");
return null;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -396,7 +396,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
* @param interceptors the interceptors to register
*/
public void setCallableInterceptors(List<CallableProcessingInterceptor> interceptors) {
Assert.notNull(interceptors);
Assert.notNull(interceptors, "CallableProcessingInterceptor List must not be null");
this.callableInterceptors = interceptors.toArray(new CallableProcessingInterceptor[interceptors.size()]);
}
@@ -405,7 +405,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
* @param interceptors the interceptors to register
*/
public void setDeferredResultInterceptors(List<DeferredResultProcessingInterceptor> interceptors) {
Assert.notNull(interceptors);
Assert.notNull(interceptors, "DeferredResultProcessingInterceptor List must not be null");
this.deferredResultInterceptors = interceptors.toArray(new DeferredResultProcessingInterceptor[interceptors.size()]);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -63,9 +63,9 @@ public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethod
public ResponseBodyEmitterReturnValueHandler(List<HttpMessageConverter<?>> messageConverters) {
Assert.notEmpty(messageConverters, "'messageConverters' must not be empty");
Assert.notEmpty(messageConverters, "HttpMessageConverter List must not be empty");
this.messageConverters = messageConverters;
this.adapterMap = new HashMap<Class<?>, ResponseBodyEmitterAdapter>(3);
this.adapterMap = new HashMap<Class<?>, ResponseBodyEmitterAdapter>(4);
this.adapterMap.put(ResponseBodyEmitter.class, new SimpleResponseBodyEmitterAdapter());
}
@@ -146,7 +146,10 @@ public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethod
ShallowEtagHeaderFilter.disableContentCaching(request);
ResponseBodyEmitterAdapter adapter = getAdapterFor(returnValue.getClass());
Assert.notNull(adapter);
if (adapter == null) {
throw new IllegalStateException(
"Could not find ResponseBodyEmitterAdapter for return value type: " + returnValue.getClass());
}
ResponseBodyEmitter emitter = adapter.adaptToEmitter(returnValue, outputMessage);
emitter.extendResponse(outputMessage);
@@ -170,7 +173,7 @@ public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethod
@Override
public ResponseBodyEmitter adaptToEmitter(Object returnValue, ServerHttpResponse response) {
Assert.isInstanceOf(ResponseBodyEmitter.class, returnValue);
Assert.isInstanceOf(ResponseBodyEmitter.class, returnValue, "ResponseBodyEmitter expected");
return (ResponseBodyEmitter) returnValue;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -82,7 +82,7 @@ public class StreamingResponseBodyReturnValueHandler implements HandlerMethodRet
ServletRequest request = webRequest.getNativeRequest(ServletRequest.class);
ShallowEtagHeaderFilter.disableContentCaching(request);
Assert.isInstanceOf(StreamingResponseBody.class, returnValue);
Assert.isInstanceOf(StreamingResponseBody.class, returnValue, "StreamingResponseBody expected");
StreamingResponseBody streamingBody = (StreamingResponseBody) returnValue;
Callable<Void> callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -186,12 +186,9 @@ public class ServletUriComponentsBuilder extends UriComponentsBuilder {
* Obtain current request through {@link RequestContextHolder}.
*/
protected static HttpServletRequest getCurrentRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
return servletRequest;
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
return ((ServletRequestAttributes) attrs).getRequest();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@@ -214,7 +214,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
if (requestedMediaTypes != null) {
List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@@ -121,7 +121,7 @@ public class ScriptTemplateView extends AbstractUrlBasedView {
* See {@link ScriptTemplateConfigurer#setEngine(ScriptEngine)} documentation.
*/
public void setEngine(ScriptEngine engine) {
Assert.isInstanceOf(Invocable.class, engine);
Assert.isInstanceOf(Invocable.class, engine, "ScriptEngine must implement Invocable");
this.engine = engine;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@@ -22,14 +22,12 @@ import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import static org.junit.Assert.fail;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for {@link ResponseBodyEmitter}.
@@ -166,7 +164,7 @@ public class ResponseBodyEmitterTests {
verify(this.handler).onTimeout(captor.capture());
verify(this.handler).onCompletion(any());
Assert.notNull(captor.getValue());
assertNotNull(captor.getValue());
captor.getValue().run();
verify(runnable).run();
}
@@ -182,7 +180,7 @@ public class ResponseBodyEmitterTests {
Runnable runnable = mock(Runnable.class);
this.emitter.onTimeout(runnable);
Assert.notNull(captor.getValue());
assertNotNull(captor.getValue());
captor.getValue().run();
verify(runnable).run();
}
@@ -197,7 +195,7 @@ public class ResponseBodyEmitterTests {
verify(this.handler).onTimeout(any());
verify(this.handler).onCompletion(captor.capture());
Assert.notNull(captor.getValue());
assertNotNull(captor.getValue());
captor.getValue().run();
verify(runnable).run();
}
@@ -213,7 +211,7 @@ public class ResponseBodyEmitterTests {
Runnable runnable = mock(Runnable.class);
this.emitter.onCompletion(runnable);
Assert.notNull(captor.getValue());
assertNotNull(captor.getValue());
captor.getValue().run();
verify(runnable).run();
}