From 1b2dc3638f90508dbc98dcd8a518153fb0db62d0 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 30 Jan 2017 22:15:53 +0100 Subject: [PATCH] Revisit Assert to avoid single-arg assert methods (with refined messages) Issue: SPR-15196 --- .../aop/aspectj/TypePatternClassFilter.java | 22 +- .../AbstractAdvisorAutoProxyCreator.java | 5 +- .../AutowiredAnnotationBeanPostProcessor.java | 4 +- .../factory/config/CustomScopeConfigurer.java | 6 +- .../factory/support/AbstractBeanFactory.java | 4 +- .../DefaultCacheInvocationContext.java | 21 +- .../interceptor/JCacheAspectSupport.java | 16 +- .../quartz/SchedulerFactoryBean.java | 5 +- .../CacheResolverAdapterTests.java | 17 +- .../cache/interceptor/CacheOperation.java | 18 +- .../ComponentScanAnnotationParser.java | 6 +- .../support/DefaultLifecycleProcessor.java | 8 +- .../standard/DateTimeFormatterFactory.java | 4 +- .../weblogic/WebLogicClassLoaderAdapter.java | 17 +- .../ClassWithComplexConstructor.java | 7 +- .../ConfigurationClassPostProcessorTests.java | 8 +- .../context/support/Service.java | 5 +- .../standard/DateTimeFormattingTests.java | 3 +- .../SpringValidatorAdapterTests.java | 2 +- .../org/springframework/core/Constants.java | 2 +- .../core/ParameterizedTypeReference.java | 6 +- .../core/SerializableTypeWrapper.java | 7 +- .../env/JOptCommandLinePropertySource.java | 13 +- .../java/org/springframework/util/Assert.java | 209 ++++-------------- .../util/ConcurrentReferenceHashMap.java | 4 +- .../org/springframework/util/AssertTests.java | 129 ++++++----- .../expression/spel/ast/OpDec.java | 4 +- .../expression/spel/ast/OpInc.java | 4 +- .../expression/spel/ast/OpPlus.java | 4 +- .../expression/spel/ast/Operator.java | 4 +- .../InternalSpelExpressionParser.java | 28 +-- .../expression/spel/standard/Tokenizer.java | 9 +- .../jdbc/core/ParameterDisposer.java | 16 +- ...dlerMethodReturnValueHandlerComposite.java | 11 +- .../messaging/simp/SimpMessagingTemplate.java | 14 +- .../SimpAnnotationMethodMessageHandler.java | 4 +- .../broker/SimpleBrokerMessageHandler.java | 7 +- .../AbstractMessageBrokerConfiguration.java | 6 +- .../simp/config/MessageBrokerRegistry.java | 6 +- .../simp/stomp/DefaultStompSession.java | 4 +- .../simp/stomp/StompClientSupport.java | 4 +- ...AbstractMonoToListenableFutureAdapter.java | 11 +- .../ReactorNettyTcpStompClientTests.java | 5 +- ...erRelayMessageHandlerIntegrationTests.java | 7 +- .../orm/hibernate5/SessionFactoryUtils.java | 4 +- .../jpa/AbstractEntityManagerFactoryBean.java | 5 +- .../jpa/support/SharedEntityManagerBean.java | 3 +- .../orm/jpa/vendor/HibernateJpaDialect.java | 4 +- .../oxm/xstream/XStreamMarshaller.java | 19 +- .../mock/web/MockAsyncContext.java | 6 +- .../mock/web/MockPageContext.java | 6 +- .../SimpleRequestExpectationManager.java | 4 +- .../standalone/FrameworkExtensionTests.java | 18 +- .../support/ResourceAdapterFactoryBean.java | 8 +- .../UrlBasedViewResolverRegistration.java | 5 +- .../reactive/config/ViewResolverRegistry.java | 10 +- .../handler/AbstractHandlerMapping.java | 23 +- .../handler/AbstractUrlHandlerMapping.java | 15 +- .../method/AbstractHandlerMethodMapping.java | 15 +- .../method/SyncInvocableHandlerMethod.java | 4 +- .../ResponseEntityResultHandler.java | 6 +- .../view/script/ScriptTemplateView.java | 4 +- .../socket/adapter/JettyWebSocketSession.java | 11 +- .../upgrade/JettyRequestUpgradeStrategy.java | 8 +- .../upgrade/TomcatRequestUpgradeStrategy.java | 22 +- .../UndertowRequestUpgradeStrategy.java | 15 +- .../reactive/FlushingIntegrationTests.java | 10 +- .../web/reactive/result/ResolvableMethod.java | 29 ++- ...lAttributeMethodArgumentResolverTests.java | 20 +- .../http/ContentDisposition.java | 5 +- .../springframework/http/ResponseCookie.java | 23 +- .../SimpleClientHttpRequestFactory.java | 6 +- .../reactive/AbstractClientHttpRequest.java | 10 +- ...ppingJackson2CborHttpMessageConverter.java | 9 +- ...pingJackson2SmileHttpMessageConverter.java | 9 +- ...appingJackson2XmlHttpMessageConverter.java | 9 +- .../http/server/ServletServerHttpRequest.java | 6 +- .../AbstractListenerReadPublisher.java | 9 +- .../AbstractListenerWriteFlushProcessor.java | 24 +- .../AbstractListenerWriteProcessor.java | 24 +- .../reactive/AbstractServerHttpResponse.java | 4 +- .../reactive/HttpHandlerAdapterSupport.java | 18 +- .../reactive/ServletHttpHandlerAdapter.java | 39 ++-- .../reactive/ServletServerHttpResponse.java | 11 +- .../reactive/UndertowServerHttpResponse.java | 15 +- .../server/reactive/WriteResultPublisher.java | 13 +- ...thExtensionContentNegotiationStrategy.java | 8 +- ...sfiedServletRequestParameterException.java | 4 +- .../web/context/ContextLoader.java | 6 +- .../web/util/HierarchicalUriComponents.java | 2 +- .../HttpHandlerAdapterSupportTests.java | 16 +- .../bootstrap/AbstractHttpServer.java | 16 +- .../server/reactive/bootstrap/HttpServer.java | 3 +- .../reactive/bootstrap/TomcatHttpServer.java | 4 +- .../mock/web/test/MockAsyncContext.java | 10 +- .../mock/web/test/MockPageContext.java | 6 +- .../util/DefaultUriTemplateHandlerTests.java | 6 +- .../web/servlet/HttpServletBean.java | 4 +- .../handler/AbstractHandlerMethodMapping.java | 8 +- .../handler/AbstractUrlHandlerMapping.java | 28 ++- ...eferredResultMethodReturnValueHandler.java | 13 +- .../HttpHeadersReturnValueHandler.java | 4 +- .../annotation/MvcUriComponentsBuilder.java | 17 +- .../RequestMappingHandlerAdapter.java | 4 +- ...ResponseBodyEmitterReturnValueHandler.java | 9 +- ...reamingResponseBodyReturnValueHandler.java | 4 +- .../support/ServletUriComponentsBuilder.java | 11 +- .../view/ContentNegotiatingViewResolver.java | 4 +- .../view/script/ScriptTemplateView.java | 4 +- .../annotation/ResponseBodyEmitterTests.java | 16 +- .../AbstractWebSocketHandlerRegistration.java | 20 +- .../messaging/DefaultSimpUserRegistry.java | 65 +++--- .../jetty/JettyRequestUpgradeStrategy.java | 6 +- .../AbstractStandardUpgradeStrategy.java | 10 +- .../client/RestTemplateXhrTransport.java | 4 +- .../sockjs/client/WebSocketTransport.java | 12 +- .../session/AbstractSockJsSession.java | 4 +- .../session/StreamingSockJsSession.java | 4 +- 118 files changed, 708 insertions(+), 828 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/TypePatternClassFilter.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/TypePatternClassFilter.java index 9d2bc141c6f..d075741490f 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/TypePatternClassFilter.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/TypePatternClassFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 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. @@ -27,6 +27,7 @@ import org.springframework.util.StringUtils; * Spring AOP {@link ClassFilter} implementation using AspectJ type matching. * * @author Rod Johnson + * @author Juergen Hoeller * @since 2.0 */ public class TypePatternClassFilter implements ClassFilter { @@ -76,17 +77,21 @@ public class TypePatternClassFilter implements ClassFilter { * or is recognized as invalid */ public void setTypePattern(String typePattern) { - Assert.notNull(typePattern); + Assert.notNull(typePattern, "Type pattern must not be null"); this.typePattern = typePattern; this.aspectJTypePatternMatcher = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution(). parseTypePattern(replaceBooleanOperators(typePattern)); } + /** + * Return the AspectJ type pattern to match. + */ public String getTypePattern() { - return typePattern; + return this.typePattern; } + /** * Should the pointcut apply to the given interface or target class? * @param clazz candidate target class @@ -95,9 +100,7 @@ public class TypePatternClassFilter implements ClassFilter { */ @Override public boolean matches(Class clazz) { - if (this.aspectJTypePatternMatcher == null) { - throw new IllegalStateException("No 'typePattern' has been set via ctor/setter."); - } + Assert.state(this.aspectJTypePatternMatcher != null, "No type pattern has been set"); return this.aspectJTypePatternMatcher.matches(clazz); } @@ -108,9 +111,8 @@ public class TypePatternClassFilter implements ClassFilter { *

This method converts back to {@code &&} for the AspectJ pointcut parser. */ private String replaceBooleanOperators(String pcExpr) { - pcExpr = StringUtils.replace(pcExpr," and "," && "); - pcExpr = StringUtils.replace(pcExpr, " or ", " || "); - pcExpr = StringUtils.replace(pcExpr, " not ", " ! "); - return pcExpr; + String result = StringUtils.replace(pcExpr," and "," && "); + result = StringUtils.replace(result, " or ", " || "); + return StringUtils.replace(result, " not ", " ! "); } } diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java index 92fc174bea6..d7a8d1168b7 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java @@ -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. @@ -54,7 +54,8 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC public void setBeanFactory(BeanFactory beanFactory) { super.setBeanFactory(beanFactory); if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { - throw new IllegalStateException("Cannot use AdvisorAutoProxyCreator without a ConfigurableListableBeanFactory"); + throw new IllegalArgumentException( + "AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory); } initBeanFactory((ConfigurableListableBeanFactory) beanFactory); } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index daf57d11aaf..de10ab87264 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -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. @@ -219,7 +219,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean public void setBeanFactory(BeanFactory beanFactory) { if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( - "AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory"); + "AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory); } this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java index aab69b17506..02141ce0985 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomScopeConfigurer.java @@ -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. @@ -102,12 +102,12 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas } else if (value instanceof Class) { Class scopeClass = (Class) value; - Assert.isAssignable(Scope.class, scopeClass); + Assert.isAssignable(Scope.class, scopeClass, "Invalid scope class"); beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass)); } else if (value instanceof String) { Class scopeClass = ClassUtils.resolveClassName((String) value, this.beanClassLoader); - Assert.isAssignable(Scope.class, scopeClass); + Assert.isAssignable(Scope.class, scopeClass, "Invalid scope class"); beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass)); } else { diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index 94839bdb3f7..3e320f8515a 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -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. @@ -762,7 +762,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp @Override public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { Assert.notNull(requiredType, "Required type must not be null"); - Assert.isAssignable(PropertyEditor.class, propertyEditorClass); + Assert.notNull(propertyEditorClass, "PropertyEditor class must not be null"); this.customEditors.put(requiredType, propertyEditorClass); } diff --git a/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheInvocationContext.java b/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheInvocationContext.java index 64d4d2c2ee2..a54429203ba 100644 --- a/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheInvocationContext.java +++ b/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/DefaultCacheInvocationContext.java @@ -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. @@ -44,14 +44,15 @@ class DefaultCacheInvocationContext private final CacheInvocationParameter[] allParameters; - public DefaultCacheInvocationContext(JCacheOperation operation, - Object target, Object[] args) { + + public DefaultCacheInvocationContext(JCacheOperation operation, Object target, Object[] args) { this.operation = operation; this.target = target; this.args = args; this.allParameters = operation.getAllParameters(args); } + @Override public JCacheOperation getOperation() { return this.operation; @@ -94,17 +95,19 @@ class DefaultCacheInvocationContext @Override public T unwrap(Class cls) { - throw new IllegalArgumentException("Could not unwrap to '" + cls.getName() + "'"); + throw new IllegalArgumentException("Cannot unwrap to " + cls); } + @Override public String toString() { - final StringBuilder sb = new StringBuilder("CacheInvocationContext{"); - sb.append("operation=").append(operation); - sb.append(", target=").append(target); - sb.append(", args=").append(Arrays.toString(args)); - sb.append(", allParameters=").append(Arrays.toString(allParameters)); + StringBuilder sb = new StringBuilder("CacheInvocationContext{"); + sb.append("operation=").append(this.operation); + sb.append(", target=").append(this.target); + sb.append(", args=").append(Arrays.toString(this.args)); + sb.append(", allParameters=").append(Arrays.toString(this.allParameters)); sb.append('}'); return sb.toString(); } + } diff --git a/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheAspectSupport.java b/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheAspectSupport.java index 8ea51aaebc2..14ee5d53630 100644 --- a/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheAspectSupport.java +++ b/spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheAspectSupport.java @@ -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. @@ -66,7 +66,7 @@ public class JCacheAspectSupport extends AbstractCacheInvoker implements Initial public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) { - Assert.notNull(cacheOperationSource); + Assert.notNull(cacheOperationSource, "JCacheOperationSource must not be null"); this.cacheOperationSource = cacheOperationSource; } @@ -80,7 +80,7 @@ public class JCacheAspectSupport extends AbstractCacheInvoker implements Initial public void afterPropertiesSet() { Assert.state(getCacheOperationSource() != null, "The 'cacheOperationSource' property is required: " + "If there are no cacheable methods, then don't use a cache aspect."); - Assert.state(getErrorHandler() != null, "The 'errorHandler' is required"); + Assert.state(getErrorHandler() != null, "The 'errorHandler' property is required"); this.cacheResultInterceptor = new CacheResultInterceptor(getErrorHandler()); this.cachePutInterceptor = new CachePutInterceptor(getErrorHandler()); @@ -128,23 +128,23 @@ public class JCacheAspectSupport extends AbstractCacheInvoker implements Initial BasicOperation operation = context.getOperation(); if (operation instanceof CacheResultOperation) { - return cacheResultInterceptor.invoke( + return this.cacheResultInterceptor.invoke( (CacheOperationInvocationContext) context, adapter); } else if (operation instanceof CachePutOperation) { - return cachePutInterceptor.invoke( + return this.cachePutInterceptor.invoke( (CacheOperationInvocationContext) context, adapter); } else if (operation instanceof CacheRemoveOperation) { - return cacheRemoveEntryInterceptor.invoke( + return this.cacheRemoveEntryInterceptor.invoke( (CacheOperationInvocationContext) context, adapter); } else if (operation instanceof CacheRemoveAllOperation) { - return cacheRemoveAllInterceptor.invoke( + return this.cacheRemoveAllInterceptor.invoke( (CacheOperationInvocationContext) context, adapter); } else { - throw new IllegalArgumentException("Could not handle " + operation); + throw new IllegalArgumentException("Cannot handle " + operation); } } diff --git a/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java b/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java index d3d7e64347f..5d5da85fb81 100644 --- a/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java +++ b/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java @@ -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. @@ -43,7 +43,6 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.scheduling.SchedulingException; -import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** @@ -105,6 +104,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe private static final ThreadLocal configTimeNonTransactionalDataSourceHolder = new ThreadLocal<>(); + /** * Return the ResourceLoader for the currently configured Quartz Scheduler, * to be used by ResourceLoaderClassLoadHelper. @@ -210,7 +210,6 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe * @see #setQuartzProperties */ public void setSchedulerFactoryClass(Class schedulerFactoryClass) { - Assert.isAssignable(SchedulerFactory.class, schedulerFactoryClass); this.schedulerFactoryClass = schedulerFactoryClass; } diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResolverAdapterTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResolverAdapterTests.java index 8f9031c811f..56fc64be855 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResolverAdapterTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResolverAdapterTests.java @@ -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. @@ -30,8 +30,6 @@ import org.junit.rules.ExpectedException; import org.springframework.cache.Cache; import org.springframework.cache.jcache.AbstractJCacheTests; -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; @@ -46,7 +44,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests { @Test - public void resolveSimpleCache() { + public void resolveSimpleCache() throws Exception { DefaultCacheInvocationContext dummyContext = createDummyContext(); CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, "testCache")); Collection caches = adapter.resolveCaches(dummyContext); @@ -56,7 +54,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests { } @Test - public void resolveUnknownCache() { + public void resolveUnknownCache() throws Exception { DefaultCacheInvocationContext dummyContext = createDummyContext(); CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, null)); @@ -66,7 +64,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests { protected CacheResolver getCacheResolver(CacheInvocationContext context, String cacheName) { CacheResolver cacheResolver = mock(CacheResolver.class); - final javax.cache.Cache cache; + javax.cache.Cache cache; if (cacheName == null) { cache = null; } @@ -78,9 +76,8 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests { return cacheResolver; } - protected DefaultCacheInvocationContext createDummyContext() { - Method method = ReflectionUtils.findMethod(Sample.class, "get", String.class); - Assert.notNull(method); + protected DefaultCacheInvocationContext createDummyContext() throws Exception { + Method method = Sample.class.getMethod("get", String.class); CacheResult cacheAnnotation = method.getAnnotation(CacheResult.class); CacheMethodDetails methodDetails = new DefaultCacheMethodDetails<>(method, cacheAnnotation, "test"); @@ -93,7 +90,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests { static class Sample { @CacheResult - private Object get(String id) { + public Object get(String id) { return null; } } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java index dca82086670..6898fa35d5b 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java @@ -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. @@ -145,19 +145,19 @@ public abstract class CacheOperation implements BasicOperation { private String condition = ""; public void setName(String name) { - Assert.hasText(name); + Assert.hasText(name, "Name must not be empty"); this.name = name; } public void setCacheName(String cacheName) { - Assert.hasText(cacheName); + Assert.hasText(cacheName, "Cache name must not be empty"); this.cacheNames = Collections.singleton(cacheName); } public void setCacheNames(String... cacheNames) { this.cacheNames = new LinkedHashSet<>(cacheNames.length); for (String cacheName : cacheNames) { - Assert.hasText(cacheName, "Cache name must be non-null if specified"); + Assert.hasText(cacheName, "Cache name must be non-empty if specified"); this.cacheNames.add(cacheName); } } @@ -167,7 +167,7 @@ public abstract class CacheOperation implements BasicOperation { } public void setKey(String key) { - Assert.notNull(key); + Assert.notNull(key, "Key must not be null"); this.key = key; } @@ -188,22 +188,22 @@ public abstract class CacheOperation implements BasicOperation { } public void setKeyGenerator(String keyGenerator) { - Assert.notNull(keyGenerator); + Assert.notNull(keyGenerator, "KeyGenerator name must not be null"); this.keyGenerator = keyGenerator; } public void setCacheManager(String cacheManager) { - Assert.notNull(cacheManager); + Assert.notNull(cacheManager, "CacheManager name must not be null"); this.cacheManager = cacheManager; } public void setCacheResolver(String cacheResolver) { - Assert.notNull(this.cacheManager); + Assert.notNull(cacheResolver, "CacheResolver name must not be null"); this.cacheResolver = cacheResolver; } public void setCondition(String condition) { - Assert.notNull(condition); + Assert.notNull(condition, "Condition must not be null"); this.condition = condition; } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java b/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java index fc095c9a078..07628c50a50 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java @@ -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. @@ -143,7 +143,7 @@ class ComponentScanAnnotationParser { switch (filterType) { case ANNOTATION: Assert.isAssignable(Annotation.class, filterClass, - "An error occurred while processing a @ComponentScan ANNOTATION type filter: "); + "@ComponentScan ANNOTATION type filter requires an annotation type"); @SuppressWarnings("unchecked") Class annotationType = (Class) filterClass; typeFilters.add(new AnnotationTypeFilter(annotationType)); @@ -153,7 +153,7 @@ class ComponentScanAnnotationParser { break; case CUSTOM: Assert.isAssignable(TypeFilter.class, filterClass, - "An error occurred while processing a @ComponentScan CUSTOM type filter: "); + "@ComponentScan CUSTOM type filter requires a TypeFilter implementation"); TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class); ParserStrategyUtils.invokeAwareMethods( filter, this.environment, this.resourceLoader, this.registry); diff --git a/spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java b/spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java index 3c99a43dcc5..0af556507c3 100644 --- a/spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java @@ -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. @@ -39,7 +39,6 @@ import org.springframework.context.Lifecycle; import org.springframework.context.LifecycleProcessor; import org.springframework.context.Phased; import org.springframework.context.SmartLifecycle; -import org.springframework.util.Assert; /** * Default implementation of the {@link LifecycleProcessor} strategy. @@ -70,7 +69,10 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor @Override public void setBeanFactory(BeanFactory beanFactory) { - Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory); + if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { + throw new IllegalArgumentException( + "DefaultLifecycleProcessor requires a ConfigurableListableBeanFactory: " + beanFactory); + } this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } diff --git a/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java b/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java index 70cb9acf0eb..18f10bdfada 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java @@ -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. @@ -126,7 +126,7 @@ public class DateTimeFormatterFactory { * @param style two characters from the set {"S", "M", "L", "F", "-"} */ public void setStylePattern(String style) { - Assert.isTrue(style != null && style.length() == 2); + Assert.isTrue(style != null && style.length() == 2, "Style pattern must consist of two characters"); this.dateStyle = convertStyleCharacter(style.charAt(0)); this.timeStyle = convertStyleCharacter(style.charAt(1)); } diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java index 2f741205909..7a2a74afda5 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 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. @@ -55,7 +55,7 @@ class WebLogicClassLoaderAdapter { public WebLogicClassLoaderAdapter(ClassLoader classLoader) { - Class wlGenericClassLoaderClass = null; + Class wlGenericClassLoaderClass; try { wlGenericClassLoaderClass = classLoader.loadClass(GENERIC_CLASS_LOADER_NAME); this.wlPreProcessorClass = classLoader.loadClass(CLASS_PRE_PROCESSOR_NAME); @@ -66,12 +66,14 @@ class WebLogicClassLoaderAdapter { this.wlGenericClassLoaderConstructor = wlGenericClassLoaderClass.getConstructor( this.getClassFinderMethod.getReturnType(), ClassLoader.class); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException( "Could not initialize WebLogic LoadTimeWeaver because WebLogic 10 API classes are not available", ex); } - Assert.isInstanceOf(wlGenericClassLoaderClass, classLoader, - "ClassLoader must be instance of [" + wlGenericClassLoaderClass.getName() + "]"); + if (!wlGenericClassLoaderClass.isInstance(classLoader)) { + throw new IllegalArgumentException( + "ClassLoader must be an instance of [" + wlGenericClassLoaderClass.getName() + "]: " + classLoader); + } this.classLoader = classLoader; } @@ -87,7 +89,7 @@ class WebLogicClassLoaderAdapter { catch (InvocationTargetException ex) { throw new IllegalStateException("WebLogic addInstanceClassPreProcessor method threw exception", ex.getCause()); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException("Could not invoke WebLogic addInstanceClassPreProcessor method", ex); } } @@ -106,8 +108,9 @@ class WebLogicClassLoaderAdapter { catch (InvocationTargetException ex) { throw new IllegalStateException("WebLogic GenericClassLoader constructor failed", ex.getCause()); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException("Could not construct WebLogic GenericClassLoader", ex); } } + } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ClassWithComplexConstructor.java b/spring-context/src/test/java/org/springframework/aop/framework/ClassWithComplexConstructor.java index 19bb244bff0..2d17df795b3 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ClassWithComplexConstructor.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/ClassWithComplexConstructor.java @@ -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. @@ -33,7 +33,7 @@ public class ClassWithComplexConstructor { @Autowired public ClassWithComplexConstructor(Dependency dependency) { - Assert.notNull(dependency); + Assert.notNull(dependency, "No Dependency bean injected"); this.dependency = dependency; } @@ -42,7 +42,8 @@ public class ClassWithComplexConstructor { } public void method() { - Assert.isTrue(this.selfReference != this && AopUtils.isCglibProxy(this.selfReference)); + Assert.state(this.selfReference != this && AopUtils.isCglibProxy(this.selfReference), + "Self reference must be a CGLIB proxy"); this.dependency.method(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java index 25da88cf3fb..a8eec500df2 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java @@ -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. @@ -1250,7 +1250,7 @@ public class ConfigurationClassPostProcessorTests { @PostConstruct public void validate() { - Assert.notNull(provider); + Assert.notNull(provider, "No ServiceBeanProvider injected"); } } @@ -1291,7 +1291,7 @@ public class ConfigurationClassPostProcessorTests { @PostConstruct public void validate() { - Assert.notNull(provider); + Assert.notNull(provider, "No ServiceBeanProvider injected"); } } @@ -1403,7 +1403,7 @@ public class ConfigurationClassPostProcessorTests { static class DependingFoo { DependingFoo(BarArgument bar) { - Assert.notNull(bar); + Assert.notNull(bar, "No BarArgument injected"); } } diff --git a/spring-context/src/test/java/org/springframework/context/support/Service.java b/spring-context/src/test/java/org/springframework/context/support/Service.java index ee9d5095d74..dd9fcd3182f 100644 --- a/spring-context/src/test/java/org/springframework/context/support/Service.java +++ b/spring-context/src/test/java/org/springframework/context/support/Service.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 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. @@ -72,7 +72,8 @@ public class Service implements ApplicationContextAware, MessageSourceAware, Dis Thread thread = new Thread() { @Override public void run() { - Assert.isTrue(applicationContext.getBean("messageSource") instanceof StaticMessageSource); + Assert.state(applicationContext.getBean("messageSource") instanceof StaticMessageSource, + "Invalid MessageSource bean"); try { applicationContext.getBean("service2"); // Should have thrown BeanCreationNotAllowedException diff --git a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java index 2eda9eddd89..75e6515a69c 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java @@ -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. @@ -355,6 +355,7 @@ public class DateTimeFormattingTests { } @Test + @SuppressWarnings("deprecation") public void testBindInstantFromJavaUtilDate() throws Exception { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("instant", new Date(109, 9, 31, 12, 0)); diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java index de7bc833a1d..5cd539f971b 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java @@ -240,7 +240,7 @@ public class SpringValidatorAdapterTests { else { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(message) - .addNode(field) + .addPropertyNode(field) .addConstraintViolation(); return false; } diff --git a/spring-core/src/main/java/org/springframework/core/Constants.java b/spring-core/src/main/java/org/springframework/core/Constants.java index 4b9d6936c6f..5045d09a523 100644 --- a/spring-core/src/main/java/org/springframework/core/Constants.java +++ b/spring-core/src/main/java/org/springframework/core/Constants.java @@ -59,7 +59,7 @@ public class Constants { * @throws IllegalArgumentException if the supplied {@code clazz} is {@code null} */ public Constants(Class clazz) { - Assert.notNull(clazz); + Assert.notNull(clazz, "Class must not be null"); this.className = clazz.getName(); Field[] fields = clazz.getFields(); for (Field field : fields) { diff --git a/spring-core/src/main/java/org/springframework/core/ParameterizedTypeReference.java b/spring-core/src/main/java/org/springframework/core/ParameterizedTypeReference.java index f3d516702fd..dcb9c29591b 100644 --- a/spring-core/src/main/java/org/springframework/core/ParameterizedTypeReference.java +++ b/spring-core/src/main/java/org/springframework/core/ParameterizedTypeReference.java @@ -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. @@ -47,9 +47,9 @@ public abstract class ParameterizedTypeReference { protected ParameterizedTypeReference() { Class parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(getClass()); Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass(); - Assert.isInstanceOf(ParameterizedType.class, type); + Assert.isInstanceOf(ParameterizedType.class, type, "Type must be a parameterized type"); ParameterizedType parameterizedType = (ParameterizedType) type; - Assert.isTrue(parameterizedType.getActualTypeArguments().length == 1); + Assert.isTrue(parameterizedType.getActualTypeArguments().length == 1, "Number of type arguments must be 1"); this.type = parameterizedType.getActualTypeArguments()[0]; } diff --git a/spring-core/src/main/java/org/springframework/core/SerializableTypeWrapper.java b/spring-core/src/main/java/org/springframework/core/SerializableTypeWrapper.java index e91b6a6394f..8980236f63b 100644 --- a/spring-core/src/main/java/org/springframework/core/SerializableTypeWrapper.java +++ b/spring-core/src/main/java/org/springframework/core/SerializableTypeWrapper.java @@ -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. @@ -408,7 +408,10 @@ abstract class SerializableTypeWrapper { private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { inputStream.defaultReadObject(); this.method = ReflectionUtils.findMethod(this.declaringClass, this.methodName); - Assert.state(Type.class == this.method.getReturnType() || Type[].class == this.method.getReturnType()); + if (this.method.getReturnType() != Type.class && this.method.getReturnType() != Type[].class) { + throw new IllegalStateException( + "Invalid return type on deserialized method - needs to be Type or Type[]: " + this.method); + } } } diff --git a/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java b/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java index 9b3fa2668c2..19733690e5d 100644 --- a/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java @@ -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. @@ -23,15 +23,15 @@ import java.util.List; import joptsimple.OptionSet; import joptsimple.OptionSpec; -import org.springframework.util.Assert; - /** * {@link CommandLinePropertySource} implementation backed by a JOpt {@link OptionSet}. * *

Typical usage

+ * * Configure and execute an {@code OptionParser} against the {@code String[]} of arguments * supplied to the {@code main} method, and create a {@link JOptCommandLinePropertySource} * using the resulting {@code OptionSet} object: + * *
  * public static void main(String[] args) {
  *     OptionParser parser = new OptionParser();
@@ -44,7 +44,7 @@ import org.springframework.util.Assert;
  *
  * See {@link CommandLinePropertySource} for complete general usage examples.
  *
- * 

Requires JOpt version 4.3 or higher. Tested against JOpt up until 4.6. + *

Requires JOpt Simple version 4.3 or higher. Tested against JOpt up until 5.0. * * @author Chris Beams * @author Juergen Hoeller @@ -98,7 +98,7 @@ public class JOptCommandLinePropertySource extends CommandLinePropertySource argValues = this.source.valuesOf(name); List stringArgValues = new ArrayList<>(); for (Object argValue : argValues) { - stringArgValues.add(argValue instanceof String ? (String) argValue : argValue.toString()); + stringArgValues.add(argValue.toString()); } if (stringArgValues.isEmpty()) { return (this.source.has(name) ? Collections.emptyList() : null); @@ -111,8 +111,7 @@ public class JOptCommandLinePropertySource extends CommandLinePropertySource argValues = this.source.nonOptionArguments(); List stringArgValues = new ArrayList<>(); for (Object argValue : argValues) { - Assert.isInstanceOf(String.class, argValue, "Argument values must be of type String"); - stringArgValues.add((String) argValue); + stringArgValues.add(argValue.toString()); } return (stringArgValues.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(stringArgValues)); diff --git a/spring-core/src/main/java/org/springframework/util/Assert.java b/spring-core/src/main/java/org/springframework/util/Assert.java index 24d54d1fb4f..581f9e93d11 100644 --- a/spring-core/src/main/java/org/springframework/util/Assert.java +++ b/spring-core/src/main/java/org/springframework/util/Assert.java @@ -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. @@ -49,9 +49,9 @@ import java.util.function.Supplier; * * @author Keith Donald * @author Juergen Hoeller + * @author Sam Brannen * @author Colin Sampaleanu * @author Rob Harrop - * @author Sam Brannen * @since 1.1.2 */ public abstract class Assert { @@ -66,6 +66,7 @@ public abstract class Assert { * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalArgumentException if {@code expression} is {@code false} + * @since 5.0 */ public static void isTrue(boolean expression, Supplier messageSupplier) { if (!expression) { @@ -87,17 +88,6 @@ public abstract class Assert { } } - /** - * Assert a boolean expression, throwing an {@code IllegalArgumentException} - * if the expression evaluates to {@code false}. - *

Assert.isTrue(i > 0);
- * @param expression a boolean expression - * @throws IllegalArgumentException if {@code expression} is {@code false} - */ - public static void isTrue(boolean expression) { - isTrue(expression, "[Assertion failed] - this expression must be true"); - } - /** * Assert that an object is {@code null}. *
@@ -107,6 +97,7 @@ public abstract class Assert {
 	 * @param messageSupplier a supplier for the exception message to use if the
 	 * assertion fails
 	 * @throws IllegalArgumentException if the object is not {@code null}
+	 * @since 5.0
 	 */
 	public static void isNull(Object object, Supplier messageSupplier) {
 		if (object != null) {
@@ -127,16 +118,6 @@ public abstract class Assert {
 		}
 	}
 
-	/**
-	 * Assert that an object is {@code null}.
-	 * 
Assert.isNull(value);
- * @param object the object to check - * @throws IllegalArgumentException if the object is not {@code null} - */ - public static void isNull(Object object) { - isNull(object, "[Assertion failed] - the object argument must be null"); - } - /** * Assert that an object is not {@code null}. *
@@ -146,6 +127,7 @@ public abstract class Assert {
 	 * @param messageSupplier a supplier for the exception message to use if the
 	 * assertion fails
 	 * @throws IllegalArgumentException if the object is {@code null}
+	 * @since 5.0
 	 */
 	public static void notNull(Object object, Supplier messageSupplier) {
 		if (object == null) {
@@ -166,16 +148,6 @@ public abstract class Assert {
 		}
 	}
 
-	/**
-	 * Assert that an object is not {@code null}.
-	 * 
Assert.notNull(clazz);
- * @param object the object to check - * @throws IllegalArgumentException if the object is {@code null} - */ - public static void notNull(Object object) { - notNull(object, "[Assertion failed] - this argument is required; it must not be null"); - } - /** * Assert that the given String is not empty; that is, * it must not be {@code null} and not the empty String. @@ -187,6 +159,7 @@ public abstract class Assert { * assertion fails * @see StringUtils#hasLength * @throws IllegalArgumentException if the text is empty + * @since 5.0 */ public static void hasLength(String text, Supplier messageSupplier) { if (!StringUtils.hasLength(text)) { @@ -209,19 +182,6 @@ public abstract class Assert { } } - /** - * Assert that the given String is not empty; that is, - * it must not be {@code null} and not the empty String. - *
Assert.hasLength(name);
- * @param text the String to check - * @see StringUtils#hasLength - * @throws IllegalArgumentException if the text is empty - */ - public static void hasLength(String text) { - hasLength(text, - "[Assertion failed] - this String argument must have length; it must not be null or empty"); - } - /** * Assert that the given String contains valid text content; that is, it must not * be {@code null} and must contain at least one non-whitespace character. @@ -233,6 +193,7 @@ public abstract class Assert { * assertion fails * @see StringUtils#hasText * @throws IllegalArgumentException if the text does not contain valid text content + * @since 5.0 */ public static void hasText(String text, Supplier messageSupplier) { if (!StringUtils.hasText(text)) { @@ -255,19 +216,6 @@ public abstract class Assert { } } - /** - * Assert that the given String contains valid text content; that is, it must not - * be {@code null} and must contain at least one non-whitespace character. - *
Assert.hasText(name, "'name' must not be empty");
- * @param text the String to check - * @see StringUtils#hasText - * @throws IllegalArgumentException if the text does not contain valid text content - */ - public static void hasText(String text) { - hasText(text, - "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"); - } - /** * Assert that the given text does not contain the given substring. *
@@ -278,6 +226,7 @@ public abstract class Assert {
 	 * @param messageSupplier a supplier for the exception message to use if the
 	 * assertion fails
 	 * @throws IllegalArgumentException if the text contains the substring
+	 * @since 5.0
 	 */
 	public static void doesNotContain(String textToSearch, String substring, Supplier messageSupplier) {
 		if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) &&
@@ -301,18 +250,6 @@ public abstract class Assert {
 		}
 	}
 
-	/**
-	 * Assert that the given text does not contain the given substring.
-	 * 
Assert.doesNotContain(name, "rod");
- * @param textToSearch the text to search - * @param substring the substring to find within the text - * @throws IllegalArgumentException if the text contains the substring - */ - public static void doesNotContain(String textToSearch, String substring) { - doesNotContain(textToSearch, substring, - () -> "[Assertion failed] - this String argument must not contain the substring [" + substring + "]"); - } - /** * Assert that an array contains elements; that is, it must not be * {@code null} and must contain at least one element. @@ -323,6 +260,7 @@ public abstract class Assert { * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalArgumentException if the object array is {@code null} or contains no elements + * @since 5.0 */ public static void notEmpty(Object[] array, Supplier messageSupplier) { if (ObjectUtils.isEmpty(array)) { @@ -344,18 +282,6 @@ public abstract class Assert { } } - /** - * Assert that an array contains elements; that is, it must not be - * {@code null} and must contain at least one element. - *
Assert.notEmpty(array);
- * @param array the array to check - * @throws IllegalArgumentException if the object array is {@code null} or - * contains no elements - */ - public static void notEmpty(Object[] array) { - notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element"); - } - /** * Assert that an array contains no {@code null} elements. *

Note: Does not complain if the array is empty! @@ -366,6 +292,7 @@ public abstract class Assert { * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalArgumentException if the object array contains a {@code null} element + * @since 5.0 */ public static void noNullElements(Object[] array, Supplier messageSupplier) { if (array != null) { @@ -395,17 +322,6 @@ public abstract class Assert { } } - /** - * Assert that an array contains no {@code null} elements. - *

Note: Does not complain if the array is empty! - *

Assert.noNullElements(array);
- * @param array the array to check - * @throws IllegalArgumentException if the object array contains a {@code null} element - */ - public static void noNullElements(Object[] array) { - noNullElements(array, "[Assertion failed] - this array must not contain any null elements"); - } - /** * Assert that a collection contains elements; that is, it must not be * {@code null} and must contain at least one element. @@ -417,6 +333,7 @@ public abstract class Assert { * assertion fails * @throws IllegalArgumentException if the collection is {@code null} or * contains no elements + * @since 5.0 */ public static void notEmpty(Collection collection, Supplier messageSupplier) { if (CollectionUtils.isEmpty(collection)) { @@ -439,19 +356,6 @@ public abstract class Assert { } } - /** - * Assert that a collection contains elements; that is, it must not be - * {@code null} and must contain at least one element. - *
Assert.notEmpty(collection, "Collection must contain elements");
- * @param collection the collection to check - * @throws IllegalArgumentException if the collection is {@code null} or - * contains no elements - */ - public static void notEmpty(Collection collection) { - notEmpty(collection, - "[Assertion failed] - this collection must not be empty: it must contain at least 1 element"); - } - /** * Assert that a Map contains entries; that is, it must not be {@code null} * and must contain at least one entry. @@ -462,6 +366,7 @@ public abstract class Assert { * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalArgumentException if the map is {@code null} or contains no entries + * @since 5.0 */ public static void notEmpty(Map map, Supplier messageSupplier) { if (CollectionUtils.isEmpty(map)) { @@ -483,29 +388,6 @@ public abstract class Assert { } } - /** - * Assert that a Map contains entries; that is, it must not be {@code null} - * and must contain at least one entry. - *
Assert.notEmpty(map);
- * @param map the map to check - * @throws IllegalArgumentException if the map is {@code null} or contains no entries - */ - public static void notEmpty(Map map) { - notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry"); - } - - /** - * Assert that the provided object is an instance of the provided class. - *
Assert.instanceOf(Foo.class, foo);
- * @param type the type to check against - * @param obj the object to check - * @throws IllegalArgumentException if the object is not an instance of type - * @see Class#isInstance - */ - public static void isInstanceOf(Class type, Object obj) { - isInstanceOf(type, obj, ""); - } - /** * Assert that the provided object is an instance of the provided class. *
@@ -519,11 +401,12 @@ public abstract class Assert {
 	 * in ":" or "." so that the generated message looks OK when appended to it.
 	 * @throws IllegalArgumentException if the object is not an instance of type
 	 * @see Class#isInstance
+	 * @since 5.0
 	 */
 	public static void isInstanceOf(Class type, Object obj, Supplier messageSupplier) {
 		notNull(type, "Type to check against must not be null");
 		if (!type.isInstance(obj)) {
-			isInstanceCheckFailed(type, obj, nullSafeGet(messageSupplier));
+			instanceCheckFailed(type, obj, nullSafeGet(messageSupplier));
 		}
 	}
 
@@ -541,26 +424,26 @@ public abstract class Assert {
 	public static void isInstanceOf(Class type, Object obj, String message) {
 		notNull(type, "Type to check against must not be null");
 		if (!type.isInstance(obj)) {
-			isInstanceCheckFailed(type, obj, message);
+			instanceCheckFailed(type, obj, message);
 		}
 	}
 
-	private static void isInstanceCheckFailed(Class type, Object obj, String message) {
-		throw new IllegalArgumentException(
-				(StringUtils.hasLength(message) ? message + " " : "") +
-				"Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
-				"] must be an instance of " + type);
-	}
-
 	/**
-	 * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}.
-	 * 
Assert.isAssignable(Number.class, myClass);
- * @param superType the super type to check - * @param subType the sub type to check - * @throws IllegalArgumentException if the classes are not assignable + * Assert that the provided object is an instance of the provided class. + *
Assert.instanceOf(Foo.class, foo);
+ * @param type the type to check against + * @param obj the object to check + * @throws IllegalArgumentException if the object is not an instance of type + * @see Class#isInstance */ - public static void isAssignable(Class superType, Class subType) { - isAssignable(superType, subType, ""); + public static void isInstanceOf(Class type, Object obj) { + isInstanceOf(type, obj, ""); + } + + private static void instanceCheckFailed(Class type, Object obj, String message) { + String className = (obj != null ? obj.getClass().getName() : "null"); + throw new IllegalArgumentException(StringUtils.hasLength(message) ? message + ": " + className : + "Object of class [" + className + "] must be an instance of " + type); } /** @@ -575,11 +458,12 @@ public abstract class Assert { * by this method in order to provide further context. It should normally end * in ":" or "." so that the generated message looks OK when appended to it. * @throws IllegalArgumentException if the classes are not assignable + * @since 5.0 */ public static void isAssignable(Class superType, Class subType, Supplier messageSupplier) { notNull(superType, "Super type to check against must not be null"); if (subType == null || !superType.isAssignableFrom(subType)) { - isAssignableCheckFailed(superType, subType, nullSafeGet(messageSupplier)); + assignableCheckFailed(superType, subType, nullSafeGet(messageSupplier)); } } @@ -596,12 +480,23 @@ public abstract class Assert { public static void isAssignable(Class superType, Class subType, String message) { notNull(superType, "Super type to check against must not be null"); if (subType == null || !superType.isAssignableFrom(subType)) { - isAssignableCheckFailed(superType, subType, message); + assignableCheckFailed(superType, subType, message); } } - private static void isAssignableCheckFailed(Class superType, Class subType, String message) { - throw new IllegalArgumentException((StringUtils.hasLength(message) ? message + " " : "") + + /** + * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}. + *
Assert.isAssignable(Number.class, myClass);
+ * @param superType the super type to check + * @param subType the sub type to check + * @throws IllegalArgumentException if the classes are not assignable + */ + public static void isAssignable(Class superType, Class subType) { + isAssignable(superType, subType, ""); + } + + private static void assignableCheckFailed(Class superType, Class subType, String message) { + throw new IllegalArgumentException(StringUtils.hasLength(message) ? message + ": " + subType : subType + " is not assignable to " + superType); } @@ -618,6 +513,7 @@ public abstract class Assert { * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalStateException if {@code expression} is {@code false} + * @since 5.0 */ public static void state(boolean expression, Supplier messageSupplier) { if (!expression) { @@ -641,19 +537,6 @@ public abstract class Assert { } } - /** - * Assert a boolean expression, throwing an {@link IllegalStateException} - * if the expression evaluates to {@code false}. - *

Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException} - * on an assertion failure. - *

Assert.state(id == null);
- * @param expression a boolean expression - * @throws IllegalStateException if {@code expression} is {@code false} - */ - public static void state(boolean expression) { - state(expression, "[Assertion failed] - this state invariant must be true"); - } - private static String nullSafeGet(Supplier messageSupplier) { return (messageSupplier != null ? messageSupplier.get() : null); } diff --git a/spring-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java b/spring-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java index af1e5baedb3..b394d90b3e5 100644 --- a/spring-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java +++ b/spring-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java @@ -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. @@ -903,7 +903,7 @@ public class ConcurrentReferenceHashMap extends AbstractMap implemen @Override public void remove() { - Assert.state(this.last != null); + Assert.state(this.last != null, "No element to remove"); ConcurrentReferenceHashMap.this.remove(this.last.getKey()); } } diff --git a/spring-core/src/test/java/org/springframework/util/AssertTests.java b/spring-core/src/test/java/org/springframework/util/AssertTests.java index 8da0f6a2536..079e4c4c30f 100644 --- a/spring-core/src/test/java/org/springframework/util/AssertTests.java +++ b/spring-core/src/test/java/org/springframework/util/AssertTests.java @@ -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. @@ -35,6 +35,7 @@ import static org.hamcrest.CoreMatchers.*; * @author Rick Evans * @author Arjen Poutsma * @author Sam Brannen + * @author Juergen Hoeller */ public class AssertTests { @@ -43,14 +44,15 @@ public class AssertTests { @Test - public void isTrue() { - Assert.isTrue(true); + public void isTrueWithMessage() { + Assert.isTrue(true, "enigma"); } @Test - public void isTrueWithFalseExpression() { + public void isTrueWithFalse() { thrown.expect(IllegalArgumentException.class); - Assert.isTrue(false); + thrown.expectMessage("enigma"); + Assert.isTrue(false, "enigma"); } @Test @@ -72,22 +74,11 @@ public class AssertTests { Assert.isTrue(false, (Supplier) null); } - @Test - public void isNull() { - Assert.isNull(null); - } - @Test public void isNullWithMessage() { Assert.isNull(null, "Bla"); } - @Test - public void isNullWithNonNullObject() { - thrown.expect(IllegalArgumentException.class); - Assert.isNull(new Object()); - } - @Test public void isNullWithMessageSupplier() { Assert.isNull(null, () -> "enigma"); @@ -108,8 +99,8 @@ public class AssertTests { } @Test - public void notNull() { - Assert.notNull("foo"); + public void notNullWithMessage() { + Assert.notNull("foo", "enigma"); } @Test @@ -133,24 +124,26 @@ public class AssertTests { @Test public void hasLength() { - Assert.hasLength("I Heart ..."); + Assert.hasLength("I Heart ...", "enigma"); } @Test public void hasLengthWithWhitespaceOnly() { - Assert.hasLength("\t "); + Assert.hasLength("\t ", "enigma"); } @Test public void hasLengthWithEmptyString() { thrown.expect(IllegalArgumentException.class); - Assert.hasLength(""); + thrown.expectMessage("enigma"); + Assert.hasLength("", "enigma"); } @Test public void hasLengthWithNull() { thrown.expect(IllegalArgumentException.class); - Assert.hasLength(null); + thrown.expectMessage("enigma"); + Assert.hasLength(null, "enigma"); } @Test @@ -186,7 +179,7 @@ public class AssertTests { @Test public void hasText() { - Assert.hasText("foo"); + Assert.hasText("foo", "enigma"); } @Test @@ -204,7 +197,7 @@ public class AssertTests { } @Test - public void hasTextWithNullAndMessage() { + public void hasTextWithNull() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("enigma"); Assert.hasText(null, "enigma"); @@ -245,21 +238,21 @@ public class AssertTests { @Test public void doesNotContainWithNullSearchString() { - Assert.doesNotContain(null, "rod"); + Assert.doesNotContain(null, "rod", "enigma"); } @Test public void doesNotContainWithNullSubstring() { - Assert.doesNotContain("A cool chick's name is Brod.", null); + Assert.doesNotContain("A cool chick's name is Brod.", null, "enigma"); } @Test public void doesNotContainWithEmptySubstring() { - Assert.doesNotContain("A cool chick's name is Brod.", ""); + Assert.doesNotContain("A cool chick's name is Brod.", "", "enigma"); } @Test - public void doesNotContainWithNullSearchStringAndNullSubstringAndMessage() { + public void doesNotContainWithNullSearchStringAndNullSubstring() { Assert.doesNotContain(null, null, "enigma"); } @@ -299,12 +292,26 @@ public class AssertTests { @Test public void notEmptyArray() { - Assert.notEmpty(new String[] { "1234" }); + Assert.notEmpty(new String[] {"1234"}, "enigma"); + } + + @Test + public void notEmptyArrayWithEmptyArray() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.notEmpty(new String[] {}, "enigma"); + } + + @Test + public void notEmptyArrayWithNullArray() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.notEmpty((Object[]) null, "enigma"); } @Test public void notEmptyArrayWithMessageSupplier() { - Assert.notEmpty(new String[] { "1234" }, () -> "enigma"); + Assert.notEmpty(new String[] {"1234"}, () -> "enigma"); } @Test @@ -369,19 +376,21 @@ public class AssertTests { @Test public void notEmptyCollection() { - Assert.notEmpty(singletonList("foo")); + Assert.notEmpty(singletonList("foo"), "enigma"); } @Test public void notEmptyCollectionWithEmptyCollection() { thrown.expect(IllegalArgumentException.class); - Assert.notEmpty(emptyList()); + thrown.expectMessage("enigma"); + Assert.notEmpty(emptyList(), "enigma"); } @Test public void notEmptyCollectionWithNullCollection() { thrown.expect(IllegalArgumentException.class); - Assert.notEmpty((Collection) null); + thrown.expectMessage("enigma"); + Assert.notEmpty((Collection) null, "enigma"); } @Test @@ -412,19 +421,21 @@ public class AssertTests { @Test public void notEmptyMap() { - Assert.notEmpty(singletonMap("foo", "bar")); + Assert.notEmpty(singletonMap("foo", "bar"), "enigma"); } @Test public void notEmptyMapWithNullMap() { thrown.expect(IllegalArgumentException.class); - Assert.notEmpty((Map) null); + thrown.expectMessage("enigma"); + Assert.notEmpty((Map) null, "enigma"); } @Test public void notEmptyMapWithEmptyMap() { thrown.expect(IllegalArgumentException.class); - Assert.notEmpty(emptyMap()); + thrown.expectMessage("enigma"); + Assert.notEmpty(emptyMap(), "enigma"); } @Test @@ -455,21 +466,21 @@ public class AssertTests { @Test public void isInstanceOf() { - Assert.isInstanceOf(String.class, "foo"); + Assert.isInstanceOf(String.class, "foo", "enigma"); } @Test public void isInstanceOfWithNullType() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Type to check against must not be null"); - Assert.isInstanceOf(null, "foo"); + Assert.isInstanceOf(null, "foo", "enigma"); } @Test public void isInstanceOfWithNullInstance() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Object of class [null] must be an instance of class java.lang.String"); - Assert.isInstanceOf(String.class, null); + thrown.expectMessage("enigma: null"); + Assert.isInstanceOf(String.class, null, "enigma"); } @Test @@ -482,9 +493,8 @@ public class AssertTests { @Test public void isInstanceOfWithTypeMismatchAndCustomMessage() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Custom message. Object of class [java.lang.Long] must be an instance of class java.lang.String"); - Assert.isInstanceOf(String.class, 42L, "Custom message."); + thrown.expectMessage("Custom message: java.lang.Long"); + Assert.isInstanceOf(String.class, 42L, "Custom message"); } @Test @@ -502,8 +512,8 @@ public class AssertTests { @Test public void isInstanceOfWithNullInstanceAndMessageSupplier() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("enigma: Object of class [null] must be an instance of class java.lang.String"); - Assert.isInstanceOf(String.class, null, () -> "enigma:"); + thrown.expectMessage("enigma: null"); + Assert.isInstanceOf(String.class, null, () -> "enigma"); } @Test @@ -516,27 +526,27 @@ public class AssertTests { @Test public void isInstanceOfWithTypeMismatchAndMessageSupplier() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("enigma: Object of class [java.lang.Long] must be an instance of class java.lang.String"); - Assert.isInstanceOf(String.class, 42L, () -> "enigma:"); + thrown.expectMessage("enigma: java.lang.Long"); + Assert.isInstanceOf(String.class, 42L, () -> "enigma"); } @Test public void isAssignable() { - Assert.isAssignable(Number.class, Integer.class); + Assert.isAssignable(Number.class, Integer.class, "enigma"); } @Test public void isAssignableWithNullSupertype() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Super type to check against must not be null"); - Assert.isAssignable(null, Integer.class); + Assert.isAssignable(null, Integer.class, "enigma"); } @Test public void isAssignableWithNullSubtype() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("null is not assignable to class java.lang.Integer"); - Assert.isAssignable(Integer.class, null); + thrown.expectMessage("enigma: null"); + Assert.isAssignable(Integer.class, null, "enigma"); } @Test @@ -549,8 +559,8 @@ public class AssertTests { @Test public void isAssignableWithTypeMismatchAndCustomMessage() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("enigma: class java.lang.Integer is not assignable to class java.lang.String"); - Assert.isAssignable(String.class, Integer.class, "enigma:"); + thrown.expectMessage("enigma: class java.lang.Integer"); + Assert.isAssignable(String.class, Integer.class, "enigma"); } @Test @@ -568,8 +578,8 @@ public class AssertTests { @Test public void isAssignableWithNullSubtypeAndMessageSupplier() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("enigma: null is not assignable to class java.lang.Integer"); - Assert.isAssignable(Integer.class, null, () -> "enigma:"); + thrown.expectMessage("enigma: null"); + Assert.isAssignable(Integer.class, null, () -> "enigma"); } @Test @@ -582,19 +592,20 @@ public class AssertTests { @Test public void isAssignableWithTypeMismatchAndMessageSupplier() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("enigma: class java.lang.Integer is not assignable to class java.lang.String"); - Assert.isAssignable(String.class, Integer.class, () -> "enigma:"); + thrown.expectMessage("enigma: class java.lang.Integer"); + Assert.isAssignable(String.class, Integer.class, () -> "enigma"); } @Test public void state() { - Assert.state(true); + Assert.state(true, "enigma"); } @Test public void stateWithFalseExpression() { thrown.expect(IllegalStateException.class); - Assert.state(false); + thrown.expectMessage("enigma"); + Assert.state(false, "enigma"); } @Test diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDec.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDec.java index 18026780422..206c382b20e 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDec.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDec.java @@ -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. @@ -43,8 +43,8 @@ public class OpDec extends Operator { public OpDec(int pos, boolean postfix, SpelNodeImpl... operands) { super("--", pos, operands); - Assert.notEmpty(operands); this.postfix = postfix; + Assert.notEmpty(operands, "Operands must not be empty"); } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpInc.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpInc.java index f7ec295e901..ab75f7b55a7 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpInc.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpInc.java @@ -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. @@ -43,8 +43,8 @@ public class OpInc extends Operator { public OpInc(int pos, boolean postfix, SpelNodeImpl... operands) { super("++", pos, operands); - Assert.notEmpty(operands); this.postfix = postfix; + Assert.notEmpty(operands, "Operands must not be empty"); } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java index eeefe40ffb7..1fc99b21280 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java @@ -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. @@ -51,7 +51,7 @@ public class OpPlus extends Operator { public OpPlus(int pos, SpelNodeImpl... operands) { super("+", pos, operands); - Assert.notEmpty(operands); + Assert.notEmpty(operands, "Operands must not be empty"); } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java index a47b9a103c7..f033519e5af 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java @@ -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. @@ -51,7 +51,7 @@ public abstract class Operator extends SpelNodeImpl { protected String rightActualDescriptor; - public Operator(String payload,int pos,SpelNodeImpl... operands) { + public Operator(String payload, int pos, SpelNodeImpl... operands) { super(pos, operands); this.operatorName = payload; } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java index 1257501d6c8..378da194861 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java @@ -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. @@ -79,6 +79,7 @@ import org.springframework.util.StringUtils; * Hand written SpEL parser. Instances are reusable but are not thread-safe. * * @author Andy Clement + * @author Juergen Hoeller * @author Phillip Webb * @since 3.0 */ @@ -128,7 +129,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { if (moreTokens()) { throw new SpelParseException(peekToken().startPos, SpelMessage.MORE_INPUT, toString(nextToken())); } - Assert.isTrue(this.constructedNodes.isEmpty()); + Assert.isTrue(this.constructedNodes.isEmpty(), "At least one node expected"); return new SpelExpression(expressionString, ast, this.configuration); } catch (InternalParseException ex) { @@ -232,7 +233,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { if (tk == TokenKind.EQ) { return new OpEQ(pos, expr, rhExpr); } - Assert.isTrue(tk == TokenKind.NE); + Assert.isTrue(tk == TokenKind.NE, "Not-equals token expected"); return new OpNE(pos, expr, rhExpr); } @@ -244,7 +245,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { return new OperatorMatches(toPos(t), expr, rhExpr); } - Assert.isTrue(tk == TokenKind.BETWEEN); + Assert.isTrue(tk == TokenKind.BETWEEN, "Between token expected"); return new OperatorBetween(toPos(t), expr, rhExpr); } return expr; @@ -281,7 +282,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { expr = new OpDivide(toPos(t), expr, rhExpr); } else { - Assert.isTrue(t.kind == TokenKind.MOD); + Assert.isTrue(t.kind == TokenKind.MOD, "Mod token expected"); expr = new OpModulus(toPos(t), expr, rhExpr); } } @@ -298,7 +299,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { return new OperatorPower(toPos(t), expr, rhExpr); } - if (expr != null && peekToken(TokenKind.INC,TokenKind.DEC)) { + if (expr != null && peekToken(TokenKind.INC, TokenKind.DEC)) { Token t = nextToken(); //consume INC/DEC if (t.getKind() == TokenKind.INC) { return new OpInc(toPos(t), true, expr); @@ -321,7 +322,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { if (t.kind == TokenKind.PLUS) { return new OpPlus(toPos(t), expr); } - Assert.isTrue(t.kind == TokenKind.MINUS); + Assert.isTrue(t.kind == TokenKind.MINUS, "Minus token expected"); return new OpMinus(toPos(t), expr); } @@ -356,7 +357,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { // node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+; private boolean maybeEatNode() { SpelNodeImpl expr = null; - if (peekToken(TokenKind.DOT,TokenKind.SAFE_NAVI)) { + if (peekToken(TokenKind.DOT, TokenKind.SAFE_NAVI)) { expr = eatDottedNode(); } else { @@ -940,7 +941,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { return false; } - private boolean peekToken(TokenKind possible1,TokenKind possible2) { + private boolean peekToken(TokenKind possible1, TokenKind possible2) { if (!moreTokens()) { return false; } @@ -948,12 +949,12 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { return (t.kind == possible1 || t.kind == possible2); } - private boolean peekToken(TokenKind possible1,TokenKind possible2, TokenKind possible3) { + private boolean peekToken(TokenKind possible1, TokenKind possible2, TokenKind possible3) { if (!moreTokens()) { return false; } Token t = peekToken(); - return t.kind == possible1 || t.kind == possible2 || t.kind == possible3; + return (t.kind == possible1 || t.kind == possible2 || t.kind == possible3); } private boolean peekIdentifierToken(String identifierString) { @@ -961,7 +962,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { return false; } Token t = peekToken(); - return t.kind == TokenKind.IDENTIFIER && t.stringValue().equalsIgnoreCase(identifierString); + return (t.kind == TokenKind.IDENTIFIER && t.stringValue().equalsIgnoreCase(identifierString)); } private boolean peekSelectToken() { @@ -969,8 +970,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { return false; } Token t = peekToken(); - return t.kind == TokenKind.SELECT || t.kind == TokenKind.SELECT_FIRST - || t.kind == TokenKind.SELECT_LAST; + return (t.kind == TokenKind.SELECT || t.kind == TokenKind.SELECT_FIRST || t.kind == TokenKind.SELECT_LAST); } private boolean moreTokens() { diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java index ce227875ac9..a4c8b8ab5b8 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java @@ -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. @@ -23,7 +23,6 @@ import java.util.List; import org.springframework.expression.spel.InternalParseException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.SpelParseException; -import org.springframework.util.Assert; /** * Lex some input data into a stream of tokens that can then be parsed. @@ -522,9 +521,9 @@ class Tokenizer { * Check if this might be a two character token. */ private boolean isTwoCharToken(TokenKind kind) { - Assert.isTrue(kind.tokenChars.length == 2); - Assert.isTrue(this.toProcess[this.pos] == kind.tokenChars[0]); - return this.toProcess[this.pos + 1] == kind.tokenChars[1]; + return (kind.tokenChars.length == 2 && + this.toProcess[this.pos] == kind.tokenChars[0] && + this.toProcess[this.pos + 1] == kind.tokenChars[1]); } /** diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/ParameterDisposer.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/ParameterDisposer.java index 6687ec16884..cfa205b2679 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/ParameterDisposer.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/ParameterDisposer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 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. @@ -18,11 +18,11 @@ package org.springframework.jdbc.core; /** * Interface to be implemented by objects that can close resources - * allocated by parameters like SqlLobValues. + * allocated by parameters like {@code SqlLobValue} objects. * - *

Typically implemented by PreparedStatementCreators and - * PreparedStatementSetters that support DisposableSqlTypeValue - * objects (e.g. SqlLobValue) as parameters. + *

Typically implemented by {@code PreparedStatementCreators} and + * {@code PreparedStatementSetters} that support {@link DisposableSqlTypeValue} + * objects (e.g. {@code SqlLobValue}) as parameters. * * @author Thomas Risberg * @author Juergen Hoeller @@ -38,9 +38,9 @@ public interface ParameterDisposer { * Close the resources allocated by parameters that the implementing * object holds, for example in case of a DisposableSqlTypeValue * (like a SqlLobValue). - * @see DisposableSqlTypeValue#cleanup - * @see org.springframework.jdbc.core.support.SqlLobValue#cleanup + * @see DisposableSqlTypeValue#cleanup() + * @see org.springframework.jdbc.core.support.SqlLobValue#cleanup() */ - public void cleanupParameters(); + void cleanupParameters(); } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/HandlerMethodReturnValueHandlerComposite.java b/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/HandlerMethodReturnValueHandlerComposite.java index bc2d01d5bcb..99ff814643d 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/HandlerMethodReturnValueHandlerComposite.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/HandlerMethodReturnValueHandlerComposite.java @@ -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. @@ -94,7 +94,9 @@ public class HandlerMethodReturnValueHandlerComposite implements AsyncHandlerMet throws Exception { HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType); - Assert.notNull(handler, "No handler for return value type [" + returnType.getParameterType().getName() + "]"); + if (handler == null) { + throw new IllegalStateException("No handler for return value type: " + returnType.getParameterType()); + } if (logger.isTraceEnabled()) { logger.trace("Processing return value with " + handler); } @@ -104,14 +106,15 @@ public class HandlerMethodReturnValueHandlerComposite implements AsyncHandlerMet @Override public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType); - return (handler != null && handler instanceof AsyncHandlerMethodReturnValueHandler && + return (handler instanceof AsyncHandlerMethodReturnValueHandler && ((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(returnValue, returnType)); } @Override public ListenableFuture toListenableFuture(Object returnValue, MethodParameter returnType) { HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType); - Assert.isTrue(handler != null && handler instanceof AsyncHandlerMethodReturnValueHandler); + Assert.state(handler instanceof AsyncHandlerMethodReturnValueHandler, + "AsyncHandlerMethodReturnValueHandler required"); return ((AsyncHandlerMethodReturnValueHandler) handler).toListenableFuture(returnValue, returnType); } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java index 493f1224b21..0088adb7d84 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessagingTemplate.java @@ -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. @@ -58,10 +58,10 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate message) { - Assert.notNull(message, "'message' is required"); + Assert.notNull(message, "Message is required"); String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders()); if (destination != null) { sendInternal(message); @@ -178,7 +178,7 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate message) { String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders()); - Assert.notNull(destination); + Assert.notNull(destination, "Destination header required"); long timeout = this.sendTimeout; boolean sent = (timeout >= 0 ? this.messageChannel.send(message, timeout) : this.messageChannel.send(message)); diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java index 83ef7bf4856..7d52150ea89 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java @@ -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. @@ -480,7 +480,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan Map vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination); if (!CollectionUtils.isEmpty(vars)) { MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class); - Assert.state(mha != null && mha.isMutable()); + Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required"); mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars); } } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java index 2c9c8f52e6b..290ee6dffe7 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandler.java @@ -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. @@ -17,6 +17,7 @@ package org.springframework.messaging.simp.broker; import java.security.Principal; +import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -174,7 +175,9 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler { * @since 4.2 */ public void setHeartbeatValue(long[] heartbeat) { - Assert.notNull(heartbeat); + if (heartbeat == null || heartbeat.length != 2 || heartbeat[0] < 0 || heartbeat[1] < 0) { + throw new IllegalArgumentException("Invalid heart-beat: " + Arrays.toString(heartbeat)); + } this.heartbeatValue = heartbeat; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java index bace1fc4f73..95c483c66d2 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java @@ -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. @@ -317,14 +317,14 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC return new NoOpMessageHandler(); } SimpUserRegistry userRegistry = userRegistry(); - Assert.isInstanceOf(MultiServerUserRegistry.class, userRegistry); + Assert.isInstanceOf(MultiServerUserRegistry.class, userRegistry, "MultiServerUserRegistry required"); return new UserRegistryMessageHandler((MultiServerUserRegistry) userRegistry, brokerMessagingTemplate(), getBrokerRegistry().getUserRegistryBroadcast(), messageBrokerTaskScheduler()); } // Expose alias for 4.1 compatibility - @Bean(name={"messageBrokerTaskScheduler", "messageBrokerSockJsTaskScheduler"}) + @Bean(name = {"messageBrokerTaskScheduler", "messageBrokerSockJsTaskScheduler"}) public ThreadPoolTaskScheduler messageBrokerTaskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadNamePrefix("MessageBroker-"); diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/MessageBrokerRegistry.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/MessageBrokerRegistry.java index 3c8dd759d22..5267b0ffffa 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/MessageBrokerRegistry.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/MessageBrokerRegistry.java @@ -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. @@ -55,8 +55,8 @@ public class MessageBrokerRegistry { public MessageBrokerRegistry(SubscribableChannel clientInboundChannel, MessageChannel clientOutboundChannel) { - Assert.notNull(clientInboundChannel); - Assert.notNull(clientOutboundChannel); + Assert.notNull(clientInboundChannel, "Inbound channel must not be null"); + Assert.notNull(clientOutboundChannel, "Outbound channel must not be null"); this.clientInboundChannel = clientInboundChannel; this.clientOutboundChannel = clientOutboundChannel; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java index ddba2d794b8..7cb3b6557c2 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompSession.java @@ -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. @@ -175,7 +175,7 @@ public class DefaultStompSession implements ConnectionHandlingStompSession { *

By default set to 15,000 (15 seconds). */ public void setReceiptTimeLimit(long receiptTimeLimit) { - Assert.isTrue(receiptTimeLimit > 0); + Assert.isTrue(receiptTimeLimit > 0, "Receipt time limit must be larger than zero"); this.receiptTimeLimit = receiptTimeLimit; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompClientSupport.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompClientSupport.java index 708f277b9cc..ea51cb93393 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompClientSupport.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompClientSupport.java @@ -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. @@ -126,7 +126,7 @@ public abstract class StompClientSupport { *

By default set to 15,000 (15 seconds). */ public void setReceiptTimeLimit(long receiptTimeLimit) { - Assert.isTrue(receiptTimeLimit > 0); + Assert.isTrue(receiptTimeLimit > 0, "Receipt time limit must be larger than zero"); this.receiptTimeLimit = receiptTimeLimit; } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/AbstractMonoToListenableFutureAdapter.java b/spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/AbstractMonoToListenableFutureAdapter.java index 8b6cf5bcf74..cfd259b5d3a 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/AbstractMonoToListenableFutureAdapter.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/AbstractMonoToListenableFutureAdapter.java @@ -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. @@ -48,7 +48,7 @@ abstract class AbstractMonoToListenableFutureAdapter implements Listenable protected AbstractMonoToListenableFutureAdapter(Mono mono) { - Assert.notNull(mono, "'mono' must not be null"); + Assert.notNull(mono, "Mono must not be null"); this.monoProcessor = mono .doOnSuccess(result -> { T adapted; @@ -73,10 +73,8 @@ abstract class AbstractMonoToListenableFutureAdapter implements Listenable } @Override - public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - - Assert.notNull(unit); + public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + Assert.notNull(unit, "TimeUnit must not be null"); Duration duration = Duration.ofMillis(TimeUnit.MILLISECONDS.convert(timeout, unit)); S result = this.monoProcessor.block(duration); return adapt(result); @@ -112,6 +110,7 @@ abstract class AbstractMonoToListenableFutureAdapter implements Listenable this.registry.addFailureCallback(failureCallback); } + protected abstract T adapt(S result); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java index bdfe762af13..df9ea9a7b5c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java @@ -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. @@ -159,7 +159,7 @@ public class ReactorNettyTcpStompClientTests { private final List received = new ArrayList<>(); public ConsumingHandler(String... topics) { - Assert.notEmpty(topics); + Assert.notEmpty(topics, "Topics must not be empty"); this.topics = Arrays.asList(topics); this.subscriptionLatch = new CountDownLatch(this.topics.size()); } @@ -168,7 +168,6 @@ public class ReactorNettyTcpStompClientTests { return this.received; } - @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { for (String topic : this.topics) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java index feba05c29f0..2fa8335ae0a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java @@ -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. @@ -399,7 +399,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { } public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) { - StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); headers.setSessionId(sessionId); headers.setReceipt(receiptId); @@ -411,7 +410,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { } public MessageExchangeBuilder andExpectMessage(String sessionId, String subscriptionId) { - Assert.isTrue(SimpMessageType.MESSAGE.equals(headers.getMessageType())); + Assert.state(SimpMessageType.MESSAGE.equals(this.headers.getMessageType()), "MESSAGE type expected"); String destination = this.headers.getDestination(); Object payload = this.message.getPayload(); this.expected.add(new StompMessageFrameMessageMatcher(sessionId, subscriptionId, destination, payload)); @@ -420,7 +419,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { public MessageExchangeBuilder andExpectError() { String sessionId = this.headers.getSessionId(); - Assert.notNull(sessionId, "No sessionId to match the ERROR frame to"); + Assert.state(sessionId != null, "No sessionId to match the ERROR frame to"); return andExpectError(sessionId); } diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java b/spring-orm/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java index 7f3d2e28a78..fafa3f6b784 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java @@ -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. @@ -110,7 +110,7 @@ public abstract class SessionFactoryUtils { } } // Check that it is the Hibernate FlushMode type, not JPA's... - Assert.state(FlushMode.class == getFlushMode.getReturnType()); + Assert.state(FlushMode.class == getFlushMode.getReturnType(), "Could not find Hibernate getFlushMode method"); } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java b/spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java index 64648b559f2..4a898b37108 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java @@ -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. @@ -135,7 +135,6 @@ public abstract class AbstractEntityManagerFactoryBean implements * @see javax.persistence.Persistence */ public void setPersistenceProviderClass(Class persistenceProviderClass) { - Assert.isAssignable(PersistenceProvider.class, persistenceProviderClass); this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass); } @@ -217,7 +216,6 @@ public abstract class AbstractEntityManagerFactoryBean implements * @see JpaVendorAdapter#getEntityManagerFactoryInterface() */ public void setEntityManagerFactoryInterface(Class emfInterface) { - Assert.isAssignable(EntityManagerFactory.class, emfInterface); this.entityManagerFactoryInterface = emfInterface; } @@ -231,7 +229,6 @@ public abstract class AbstractEntityManagerFactoryBean implements * @see EntityManagerFactoryInfo#getEntityManagerInterface() */ public void setEntityManagerInterface(Class emInterface) { - Assert.isAssignable(EntityManager.class, emInterface); this.entityManagerInterface = emInterface; } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/SharedEntityManagerBean.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/SharedEntityManagerBean.java index c6595279de5..4c5b44592d0 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/SharedEntityManagerBean.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/SharedEntityManagerBean.java @@ -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. @@ -68,7 +68,6 @@ public class SharedEntityManagerBean extends EntityManagerFactoryAccessor */ public void setEntityManagerInterface(Class entityManagerInterface) { Assert.notNull(entityManagerInterface, "'entityManagerInterface' must not be null"); - Assert.isAssignable(EntityManager.class, entityManagerInterface); this.entityManagerInterface = entityManagerInterface; } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java b/spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java index 8428f094715..93458e7bdd3 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java @@ -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. @@ -100,7 +100,7 @@ public class HibernateJpaDialect extends DefaultJpaDialect { } } // Check that it is the Hibernate FlushMode type, not JPA's... - Assert.state(FlushMode.class == getFlushMode.getReturnType()); + Assert.state(FlushMode.class == getFlushMode.getReturnType(), "Could not find Hibernate getFlushMode method"); } diff --git a/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java index 740dfe535e5..c5f09841f70 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java @@ -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. @@ -79,7 +79,6 @@ import org.springframework.oxm.UncategorizedMappingException; import org.springframework.oxm.UnmarshallingFailureException; import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.support.AbstractMarshaller; -import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -114,7 +113,7 @@ import org.springframework.util.xml.StaxUtils; * @author Juergen Hoeller * @since 3.0 */ -public class XStreamMarshaller extends AbstractMarshaller implements InitializingBean, BeanClassLoaderAware { +public class XStreamMarshaller extends AbstractMarshaller implements BeanClassLoaderAware, InitializingBean { /** * The default encoding used for stream access: UTF-8. @@ -130,7 +129,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin private Mapper mapper; - private Class[] mapperWrappers; + private Class[] mapperWrappers; private ConverterLookup converterLookup = new DefaultConverterLookup(); @@ -210,7 +209,8 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin * of type {@link Mapper} or {@link MapperWrapper}. * @since 4.0 */ - public void setMapperWrappers(Class... mapperWrappers) { + @SuppressWarnings("unchecked") + public void setMapperWrappers(Class... mapperWrappers) { this.mapperWrappers = mapperWrappers; } @@ -413,9 +413,8 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin protected MapperWrapper wrapMapper(MapperWrapper next) { MapperWrapper mapperToWrap = next; if (mapperWrappers != null) { - for (Class mapperWrapper : mapperWrappers) { - Assert.isAssignable(MapperWrapper.class, mapperWrapper); - Constructor ctor; + for (Class mapperWrapper : mapperWrappers) { + Constructor ctor; try { ctor = mapperWrapper.getConstructor(Mapper.class); } @@ -428,9 +427,9 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin } } try { - mapperToWrap = (MapperWrapper) ctor.newInstance(mapperToWrap); + mapperToWrap = ctor.newInstance(mapperToWrap); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException("Failed to construct MapperWrapper: " + mapperWrapper); } } diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockAsyncContext.java b/spring-test/src/main/java/org/springframework/mock/web/MockAsyncContext.java index f8d6e4cddca..c13ca8ffa8c 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockAsyncContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockAsyncContext.java @@ -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. @@ -61,7 +61,7 @@ public class MockAsyncContext implements AsyncContext { public void addDispatchHandler(Runnable handler) { - Assert.notNull(handler); + Assert.notNull(handler, "Dispatch handler must not be null"); this.dispatchHandlers.add(handler); } @@ -77,7 +77,7 @@ public class MockAsyncContext implements AsyncContext { @Override public boolean hasOriginalRequestAndResponse() { - return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse); + return (this.request instanceof MockHttpServletRequest && this.response instanceof MockHttpServletResponse); } @Override diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java b/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java index 02dc7465e46..667741742cf 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java @@ -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. @@ -356,12 +356,12 @@ public class MockPageContext extends PageContext { } public byte[] getContentAsByteArray() { - Assert.isTrue(this.response instanceof MockHttpServletResponse); + Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required"); return ((MockHttpServletResponse) this.response).getContentAsByteArray(); } public String getContentAsString() throws UnsupportedEncodingException { - Assert.isTrue(this.response instanceof MockHttpServletResponse); + Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required"); return ((MockHttpServletResponse) this.response).getContentAsString(); } diff --git a/spring-test/src/main/java/org/springframework/test/web/client/SimpleRequestExpectationManager.java b/spring-test/src/main/java/org/springframework/test/web/client/SimpleRequestExpectationManager.java index dbcf3852de4..89d91f1e62a 100644 --- a/spring-test/src/main/java/org/springframework/test/web/client/SimpleRequestExpectationManager.java +++ b/spring-test/src/main/java/org/springframework/test/web/client/SimpleRequestExpectationManager.java @@ -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. @@ -43,7 +43,7 @@ public class SimpleRequestExpectationManager extends AbstractRequestExpectationM @Override protected void afterExpectationsDeclared() { - Assert.state(this.expectationIterator == null); + Assert.state(this.expectationIterator == null, "Expectations already declared"); this.expectationIterator = getExpectations().iterator(); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/FrameworkExtensionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/FrameworkExtensionTests.java index f194c41a45b..62a9ad65883 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/FrameworkExtensionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/FrameworkExtensionTests.java @@ -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. @@ -41,10 +41,10 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; /** * Demonstrates use of SPI extension points: *

    - *
  • {@link org.springframework.test.web.servlet.request.RequestPostProcessor} - * for extending request building with custom methods. - *
  • {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer - * MockMvcConfigurer} for extending MockMvc building with some automatic setup. + *
  • {@link org.springframework.test.web.servlet.request.RequestPostProcessor} + * for extending request building with custom methods. + *
  • {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer + * MockMvcConfigurer} for extending MockMvc building with some automatic setup. *
* * @author Rossen Stoyanchev @@ -106,6 +106,7 @@ public class FrameworkExtensionTests { } } + /** * Test {@code MockMvcConfigurer}. */ @@ -126,6 +127,7 @@ public class FrameworkExtensionTests { } } + @Controller @RequestMapping("/") private static class SampleController { @@ -133,16 +135,16 @@ public class FrameworkExtensionTests { @RequestMapping(headers = "Foo") @ResponseBody public String handleFoo(Principal principal) { - Assert.isTrue(principal != null); + Assert.notNull(principal, "Principal must not be null"); return "Foo"; } @RequestMapping(headers = "Bar") @ResponseBody public String handleBar(Principal principal) { - Assert.isTrue(principal != null); + Assert.notNull(principal, "Principal must not be null"); return "Bar"; } } -} \ No newline at end of file +} diff --git a/spring-tx/src/main/java/org/springframework/jca/support/ResourceAdapterFactoryBean.java b/spring-tx/src/main/java/org/springframework/jca/support/ResourceAdapterFactoryBean.java index 7e7ff1eda5d..d4b7d3084e5 100644 --- a/spring-tx/src/main/java/org/springframework/jca/support/ResourceAdapterFactoryBean.java +++ b/spring-tx/src/main/java/org/springframework/jca/support/ResourceAdapterFactoryBean.java @@ -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. @@ -26,7 +26,6 @@ import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; -import org.springframework.util.Assert; /** * {@link org.springframework.beans.factory.FactoryBean} that bootstraps @@ -66,9 +65,8 @@ public class ResourceAdapterFactoryBean implements FactoryBean, * through the "resourceAdapter" property. * @see #setResourceAdapter */ - public void setResourceAdapterClass(Class resourceAdapterClass) { - Assert.isAssignable(ResourceAdapter.class, resourceAdapterClass); - this.resourceAdapter = (ResourceAdapter) BeanUtils.instantiateClass(resourceAdapterClass); + public void setResourceAdapterClass(Class resourceAdapterClass) { + this.resourceAdapter = BeanUtils.instantiateClass(resourceAdapterClass); } /** diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/UrlBasedViewResolverRegistration.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/UrlBasedViewResolverRegistration.java index 3da533a38dc..553bc9503ab 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/UrlBasedViewResolverRegistration.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/UrlBasedViewResolverRegistration.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.reactive.config; import org.springframework.util.Assert; @@ -30,7 +31,7 @@ public class UrlBasedViewResolverRegistration { public UrlBasedViewResolverRegistration(UrlBasedViewResolver viewResolver) { - Assert.notNull(viewResolver); + Assert.notNull(viewResolver, "ViewResolver must not be null"); this.viewResolver = viewResolver; } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/ViewResolverRegistry.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/ViewResolverRegistry.java index 9c083e2d6d5..a6e1a4558bb 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/ViewResolverRegistry.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/ViewResolverRegistry.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.reactive.config; import java.util.ArrayList; @@ -32,7 +33,6 @@ import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver; - /** * Assist with the configuration of a chain of {@link ViewResolver}'s supporting * different template mechanisms. @@ -46,17 +46,17 @@ import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewRes */ public class ViewResolverRegistry { + private final ApplicationContext applicationContext; + private final List viewResolvers = new ArrayList<>(4); private final List defaultViews = new ArrayList<>(4); private Integer order; - private final ApplicationContext applicationContext; - public ViewResolverRegistry(ApplicationContext applicationContext) { - Assert.notNull(applicationContext); + Assert.notNull(applicationContext, "ApplicationContext must not be null"); this.applicationContext = applicationContext; } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractHandlerMapping.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractHandlerMapping.java index 7de183cc0b5..55893778d84 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractHandlerMapping.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractHandlerMapping.java @@ -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. @@ -41,10 +41,13 @@ import org.springframework.web.server.support.HttpRequestPathHelper; * implementations. * * @author Rossen Stoyanchev + * @author Juergen Hoeller * @since 5.0 */ -public abstract class AbstractHandlerMapping extends ApplicationObjectSupport - implements HandlerMapping, Ordered { +public abstract class AbstractHandlerMapping extends ApplicationObjectSupport implements HandlerMapping, Ordered { + + private static final WebHandler REQUEST_HANDLED_HANDLER = exchange -> Mono.empty(); + private int order = Integer.MAX_VALUE; // default: same as non-Ordered @@ -158,7 +161,6 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport CorsConfiguration configA = this.globalCorsConfigSource.getCorsConfiguration(exchange); CorsConfiguration configB = getCorsConfiguration(handler, exchange); CorsConfiguration config = (configA != null ? configA.combine(configB) : configB); - if (!getCorsProcessor().processRequest(config, exchange) || CorsUtils.isPreFlightRequest(exchange.getRequest())) { return REQUEST_HANDLED_HANDLER; @@ -171,13 +173,11 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport /** * Look up a handler for the given request, returning an empty {@code Mono} * if no specific one is found. This method is called by {@link #getHandler}. - * *

On CORS pre-flight requests this method should return a match not for * the pre-flight request but for the expected actual request based on the URL * path, the HTTP methods from the "Access-Control-Request-Method" header, and * the headers from the "Access-Control-Request-Headers" header thus allowing * the CORS configuration to be obtained via {@link #getCorsConfigurations}, - * * @param exchange current exchange * @return {@code Mono} for the matching handler, if any */ @@ -185,18 +185,15 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport /** * Retrieve the CORS configuration for the given handler. - * @param handler the handler to check (never {@code null}). + * @param handler the handler to check (never {@code null}) * @param exchange the current exchange - * @return the CORS configuration for the handler or {@code null}. + * @return the CORS configuration for the handler, or {@code null} if none */ protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) { - if (handler != null && handler instanceof CorsConfigurationSource) { + if (handler instanceof CorsConfigurationSource) { return ((CorsConfigurationSource) handler).getCorsConfiguration(exchange); } return null; } - - private static final WebHandler REQUEST_HANDLED_HANDLER = exchange -> Mono.empty(); - -} \ No newline at end of file +} diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java index a937fb8a7b1..57122fd8aae 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/AbstractUrlHandlerMapping.java @@ -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. @@ -44,6 +44,7 @@ import org.springframework.web.server.ServerWebExchange; * path pattern that matches the current request path. * * @author Rossen Stoyanchev + * @author Juergen Hoeller * @since 5.0 */ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { @@ -137,6 +138,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { if (handler != null) { return handleMatch(handler, urlPath, urlPath, exchange); } + // Pattern match? List matches = new ArrayList<>(); for (String pattern : this.handlerMap.keySet()) { @@ -149,6 +151,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { } } } + String bestMatch = null; Comparator comparator = getPathMatcher().getPatternComparator(urlPath); if (!matches.isEmpty()) { @@ -161,12 +164,18 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { if (bestMatch != null) { handler = this.handlerMap.get(bestMatch); if (handler == null) { - Assert.isTrue(bestMatch.endsWith("/")); - handler = this.handlerMap.get(bestMatch.substring(0, bestMatch.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 + "]"); + } } String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestMatch, urlPath); return handleMatch(handler, bestMatch, pathWithinMapping, exchange); } + // No handler found... return null; } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java index 28694baab4a..325fd55acd2 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/AbstractHandlerMethodMapping.java @@ -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. @@ -52,11 +52,10 @@ import org.springframework.web.server.ServerWebExchange; *

For each registered handler method, a unique mapping is maintained with * subclasses defining the details of the mapping type {@code }. * - * @param The mapping for a {@link HandlerMethod} containing the conditions - * needed to match the handler method to incoming request. - * * @author Rossen Stoyanchev * @since 5.0 + * @param The mapping for a {@link HandlerMethod} containing the conditions + * needed to match the handler method to incoming request. */ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMapping implements InitializingBean { @@ -570,10 +569,9 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap private final List directUrls; - public MappingRegistration(T mapping, HandlerMethod handlerMethod, List directUrls) { - 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.emptyList()); @@ -629,10 +627,11 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap } } + private static class PreFlightAmbiguousMatchHandler { public void handle() { - throw new UnsupportedOperationException("not implemented"); + throw new UnsupportedOperationException("Not implemented"); } } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/SyncInvocableHandlerMethod.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/SyncInvocableHandlerMethod.java index ddecf58e125..cc020ddf170 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/SyncInvocableHandlerMethod.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/SyncInvocableHandlerMethod.java @@ -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. @@ -55,7 +55,7 @@ public class SyncInvocableHandlerMethod extends InvocableHandlerMethod { public void setArgumentResolvers(List resolvers) { resolvers.forEach(resolver -> Assert.isInstanceOf(SyncHandlerMethodArgumentResolver.class, resolver, - "Expected sync argument resolver: " + resolver.getClass().getName())); + "SyncHandlerMethodArgumentResolver requires SyncHandlerMethodArgumentResolver")); super.setArgumentResolvers(resolvers); } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java index 64d97e95812..ed8b4818b26 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java @@ -106,7 +106,6 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand @Override public Mono handleResult(ServerWebExchange exchange, HandlerResult result) { - ResolvableType returnType = result.getReturnType(); MethodParameter bodyType; @@ -117,7 +116,7 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand ReactiveAdapter adapter = getAdapterRegistry().getAdapter(rawClass, optionalValue); if (adapter != null) { - Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported."); + Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported"); returnValueMono = Mono.from(adapter.toPublisher(optionalValue)); bodyType = new MethodParameter(result.getReturnTypeSource()); bodyType.increaseNestingLevel(); @@ -130,8 +129,7 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand } return returnValueMono.then(returnValue -> { - - Assert.isInstanceOf(HttpEntity.class, returnValue); + Assert.isInstanceOf(HttpEntity.class, returnValue, "HttpEntity expected"); HttpEntity httpEntity = (HttpEntity) returnValue; if (httpEntity instanceof ResponseEntity) { diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/script/ScriptTemplateView.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/script/ScriptTemplateView.java index b50c708288b..0046be875a6 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/script/ScriptTemplateView.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/script/ScriptTemplateView.java @@ -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. @@ -111,7 +111,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; } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketSession.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketSession.java index 8beb4cd290c..ae95e9fc0e1 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketSession.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketSession.java @@ -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. @@ -44,7 +44,7 @@ import org.springframework.web.reactive.socket.WebSocketSession; */ public class JettyWebSocketSession extends AbstractListenerWebSocketSession { - private SuspendToken suspendToken; + private volatile SuspendToken suspendToken; public JettyWebSocketSession(Session session, HandshakeInfo info, DataBufferFactory factory) { @@ -65,14 +65,15 @@ public class JettyWebSocketSession extends AbstractListenerWebSocketSession protocol; - public WebSocketHandlerContainer(JettyWebSocketHandlerAdapter adapter, Optional protocol) { this.adapter = adapter; this.protocol = protocol; @@ -194,4 +193,5 @@ public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Life return this.protocol; } } + } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java index 7bfcce57b09..266982db8af 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java @@ -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. @@ -20,7 +20,6 @@ import java.io.IOException; import java.security.Principal; import java.util.Collections; import java.util.Optional; -import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -35,8 +34,8 @@ import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.http.server.reactive.ServletServerHttpRequest; import org.springframework.http.server.reactive.ServletServerHttpResponse; import org.springframework.util.Assert; -import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.HandshakeInfo; +import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter; import org.springframework.web.reactive.socket.adapter.StandardWebSocketSession; import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; @@ -55,9 +54,7 @@ public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy { @Override - public Mono upgrade(ServerWebExchange exchange, WebSocketHandler handler, - Optional subProtocol){ - + public Mono upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional subProtocol){ ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); @@ -87,12 +84,12 @@ public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy { } private HttpServletRequest getHttpServletRequest(ServerHttpRequest request) { - Assert.isTrue(request instanceof ServletServerHttpRequest); + Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required"); return ((ServletServerHttpRequest) request).getServletRequest(); } private HttpServletResponse getHttpServletResponse(ServerHttpResponse response) { - Assert.isTrue(response instanceof ServletServerHttpResponse); + Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required"); return ((ServletServerHttpResponse) response).getServletResponse(); } @@ -103,12 +100,9 @@ public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy { } private WsServerContainer getContainer(HttpServletRequest request) { - ServletContext servletContext = request.getServletContext(); - Object container = servletContext.getAttribute(SERVER_CONTAINER_ATTR); - Assert.notNull(container, - "No 'javax.websocket.server.ServerContainer' ServletContext attribute. " + - "Are you running in a Servlet container that supports JSR-356?"); - Assert.isTrue(container instanceof WsServerContainer); + Object container = request.getServletContext().getAttribute(SERVER_CONTAINER_ATTR); + Assert.state(container instanceof WsServerContainer, + "No 'javax.websocket.server.ServerContainer' ServletContext attribute in a Tomcat container"); return (WsServerContainer) container; } diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java index a0d5e77bb29..52d228753a5 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java @@ -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. @@ -53,13 +53,10 @@ import org.springframework.web.server.ServerWebExchange; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy { - @Override - public Mono upgrade(ServerWebExchange exchange, WebSocketHandler handler, - Optional subProtocol) { - + public Mono upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional subProtocol) { ServerHttpRequest request = exchange.getRequest(); - Assert.isTrue(request instanceof UndertowServerHttpRequest); + Assert.isInstanceOf(UndertowServerHttpRequest.class, request, "UndertowServerHttpRequest required"); HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange(); Set protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet()); @@ -92,10 +89,7 @@ public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy { private final DataBufferFactory bufferFactory; - - public DefaultCallback(HandshakeInfo handshakeInfo, WebSocketHandler handler, - DataBufferFactory bufferFactory) { - + public DefaultCallback(HandshakeInfo handshakeInfo, WebSocketHandler handler, DataBufferFactory bufferFactory) { this.handshakeInfo = handshakeInfo; this.handler = handler; this.bufferFactory = bufferFactory; @@ -103,7 +97,6 @@ public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy { @Override public void onConnect(WebSocketHttpExchange httpExchange, WebSocketChannel channel) { - UndertowWebSocketSession session = createSession(channel); UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session); diff --git a/spring-web-reactive/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java b/spring-web-reactive/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java index 5e72bcea6d1..18810cfd575 100644 --- a/spring-web-reactive/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java +++ b/spring-web-reactive/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java @@ -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. @@ -35,13 +35,14 @@ import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.http.server.reactive.bootstrap.RxNettyHttpServer; -import org.springframework.util.Assert; import org.springframework.web.reactive.function.BodyExtractors; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClientOperations; import org.springframework.web.util.DefaultUriBuilderFactory; import org.springframework.web.util.UriBuilderFactory; +import static org.junit.Assert.*; + /** * @author Sebastien Deleuze */ @@ -52,8 +53,7 @@ public class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTest @Before public void setup() throws Exception { - - // TODO: fix failing tests + // TODO: fix failing RxNetty tests Assume.assumeFalse(this.server instanceof RxNettyHttpServer); super.setup(); @@ -88,7 +88,7 @@ public class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTest .reduce((s1, s2) -> s1 + s2); StepVerifier.create(result) - .consumeNextWith(value -> Assert.isTrue(value.length() == 200000)) + .consumeNextWith(value -> assertTrue(value.length() == 200000)) .expectComplete() .verify(Duration.ofSeconds(10L)); } diff --git a/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/ResolvableMethod.java b/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/ResolvableMethod.java index 0b572755bc9..ca5105f24ab 100644 --- a/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/ResolvableMethod.java +++ b/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/ResolvableMethod.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.reactive.result; import java.lang.annotation.Annotation; @@ -70,7 +71,6 @@ public class ResolvableMethod { private final Object object; - private String methodName; private Class[] argumentTypes; @@ -84,13 +84,13 @@ public class ResolvableMethod { private ResolvableMethod(Class objectClass) { - Assert.notNull(objectClass); + Assert.notNull(objectClass, "Class must not be null"); this.objectClass = objectClass; this.object = null; } private ResolvableMethod(Object object) { - Assert.notNull(object); + Assert.notNull(object, "Object must not be null"); this.object = object; this.objectClass = object.getClass(); } @@ -136,6 +136,7 @@ public class ResolvableMethod { return this; } + // Resolve methods public Method resolve() { @@ -168,18 +169,17 @@ public class ResolvableMethod { return true; }); - Assert.isTrue(!methods.isEmpty(), "No matching method: " + this); - Assert.isTrue(methods.size() == 1, "Multiple matching methods: " + this); - + Assert.state(!methods.isEmpty(), () -> "No matching method: " + this); + Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this); return methods.iterator().next(); } private String getReturnType() { - return this.returnType != null ? this.returnType.toString() : null; + return (this.returnType != null ? this.returnType.toString() : null); } public InvocableHandlerMethod resolveHandlerMethod() { - Assert.notNull(this.object); + Assert.state(this.object != null, "Object must not be null"); return new InvocableHandlerMethod(this.object, resolve()); } @@ -194,9 +194,7 @@ public class ResolvableMethod { } @SafeVarargs - public final MethodParameter resolveParam(ResolvableType type, - Predicate... predicates) { - + public final MethodParameter resolveParam(ResolvableType type, Predicate... predicates) { List matches = new ArrayList<>(); Method method = resolve(); @@ -215,9 +213,8 @@ public class ResolvableMethod { matches.add(param); } - Assert.isTrue(!matches.isEmpty(), "No matching arg on " + method.toString()); - Assert.isTrue(matches.size() == 1, "Multiple matching args: " + matches + " on " + method.toString()); - + Assert.state(!matches.isEmpty(), () -> "No matching arg on " + method.toString()); + Assert.state(matches.size() == 1, () -> "Multiple matching args: " + matches + " on " + method.toString()); return matches.get(0); } @@ -238,4 +235,4 @@ public class ResolvableMethod { return new ResolvableMethod(object); } -} \ No newline at end of file +} diff --git a/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java b/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java index 50989f74f1e..8387cc975dd 100644 --- a/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java +++ b/spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.reactive.result.method.annotation; import java.net.URISyntaxException; @@ -43,18 +44,12 @@ import org.springframework.web.reactive.result.ResolvableMethod; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange; -import static junit.framework.TestCase.assertNotNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.springframework.core.ResolvableType.forClass; -import static org.springframework.core.ResolvableType.forClassWithGenerics; -import static org.springframework.util.Assert.isTrue; - +import static org.junit.Assert.*; +import static org.springframework.core.ResolvableType.*; /** * Unit tests for {@link ModelAttributeMethodArgumentResolver}. + * * @author Rossen Stoyanchev */ public class ModelAttributeMethodArgumentResolverTests { @@ -208,7 +203,7 @@ public class ModelAttributeMethodArgumentResolverTests { resolvedArgumentMono -> { Object value = resolvedArgumentMono.blockMillis(5000); assertNotNull(value); - isTrue(value instanceof Mono); + assertTrue(value instanceof Mono); return (Mono) value; }); } @@ -220,14 +215,13 @@ public class ModelAttributeMethodArgumentResolverTests { resolvedArgumentMono -> { Object value = resolvedArgumentMono.blockMillis(5000); assertNotNull(value); - isTrue(value instanceof Single); + assertTrue(value instanceof Single); return Mono.from(RxReactiveStreams.toPublisher((Single) value)); }); } private void testBindFoo(ResolvableType type, Function valueExtractor) throws Exception { - Object value = createResolver() .resolveArgument(parameter(type), this.bindContext, exchange("name=Robert&age=25")) .blockMillis(0); diff --git a/spring-web/src/main/java/org/springframework/http/ContentDisposition.java b/spring-web/src/main/java/org/springframework/http/ContentDisposition.java index a7ab9da5639..a2dd5baece3 100644 --- a/spring-web/src/main/java/org/springframework/http/ContentDisposition.java +++ b/spring-web/src/main/java/org/springframework/http/ContentDisposition.java @@ -23,8 +23,7 @@ import java.nio.charset.StandardCharsets; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static java.nio.charset.StandardCharsets.UTF_8; +import static java.nio.charset.StandardCharsets.*; /** * Represent the content disposition type and parameters as defined in RFC 2183. @@ -121,7 +120,7 @@ public class ContentDisposition { */ public static ContentDisposition parse(String contentDisposition) { String[] parts = StringUtils.tokenizeToStringArray(contentDisposition, ";"); - Assert.isTrue(parts.length >= 1); + Assert.isTrue(parts.length >= 1, "Content-Disposition header must not be empty"); String type = parts[0]; String name = null; String filename = null; diff --git a/spring-web/src/main/java/org/springframework/http/ResponseCookie.java b/spring-web/src/main/java/org/springframework/http/ResponseCookie.java index 524a82a42ac..decc77a0cff 100644 --- a/spring-web/src/main/java/org/springframework/http/ResponseCookie.java +++ b/spring-web/src/main/java/org/springframework/http/ResponseCookie.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.http; import java.time.Duration; @@ -50,7 +51,7 @@ public final class ResponseCookie extends HttpCookie { String path, boolean secure, boolean httpOnly) { super(name, value); - Assert.notNull(maxAge); + Assert.notNull(maxAge, "Max age must not be null"); this.maxAge = maxAge; this.domain = Optional.ofNullable(domain); this.path = Optional.ofNullable(path); @@ -61,7 +62,6 @@ public final class ResponseCookie extends HttpCookie { /** * Return the cookie "Max-Age" attribute in seconds. - * *

A positive value indicates when the cookie expires relative to the * current time. A value of 0 means the cookie should expire immediately. * A negative value means no "Max-Age" attribute in which case the cookie @@ -100,13 +100,6 @@ public final class ResponseCookie extends HttpCookie { return this.httpOnly; } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + ObjectUtils.nullSafeHashCode(this.domain); - result = 31 * result + ObjectUtils.nullSafeHashCode(this.path); - return result; - } @Override public boolean equals(Object other) { @@ -122,6 +115,14 @@ public final class ResponseCookie extends HttpCookie { ObjectUtils.nullSafeEquals(this.domain, otherCookie.getDomain())); } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + ObjectUtils.nullSafeHashCode(this.domain); + result = 31 * result + ObjectUtils.nullSafeHashCode(this.path); + return result; + } + /** * Factory method to obtain a builder for a server-defined cookie that starts @@ -144,7 +145,6 @@ public final class ResponseCookie extends HttpCookie { private boolean httpOnly; - @Override public ResponseCookieBuilder maxAge(Duration maxAge) { this.maxAge = maxAge; @@ -189,6 +189,7 @@ public final class ResponseCookie extends HttpCookie { }; } + /** * A builder for a server-defined HttpCookie with attributes. */ diff --git a/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java b/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java index bf982d6e240..3aff0c92213 100644 --- a/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java +++ b/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java @@ -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. @@ -177,7 +177,9 @@ public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory, */ protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException { URLConnection urlConnection = (proxy != null ? url.openConnection(proxy) : url.openConnection()); - Assert.isInstanceOf(HttpURLConnection.class, urlConnection); + if (!HttpURLConnection.class.isInstance(urlConnection)) { + throw new IllegalStateException("HttpURLConnection required for [" + url + "] but got: " + urlConnection); + } return (HttpURLConnection) urlConnection; } diff --git a/spring-web/src/main/java/org/springframework/http/client/reactive/AbstractClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/reactive/AbstractClientHttpRequest.java index 3c0d5c4813b..c76d0bc786e 100644 --- a/spring-web/src/main/java/org/springframework/http/client/reactive/AbstractClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/reactive/AbstractClientHttpRequest.java @@ -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. @@ -49,6 +49,7 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest { */ private enum State {NEW, COMMITTING, COMMITTED} + private final HttpHeaders headers; private final MultiValueMap cookies; @@ -63,7 +64,7 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest { } public AbstractClientHttpRequest(HttpHeaders headers) { - Assert.notNull(headers); + Assert.notNull(headers, "HttpHeaders must not be null"); this.headers = headers; this.cookies = new LinkedMultiValueMap<>(); } @@ -124,7 +125,7 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest { @Override public void beforeCommit(Supplier> action) { - Assert.notNull(action); + Assert.notNull(action, "Action must not be null"); this.commitActions.add(action); } @@ -140,5 +141,4 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest { */ protected abstract void applyCookies(); - -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/http/converter/cbor/MappingJackson2CborHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/cbor/MappingJackson2CborHttpMessageConverter.java index 4a3dcb5e284..b08f59dd464 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/cbor/MappingJackson2CborHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/cbor/MappingJackson2CborHttpMessageConverter.java @@ -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. @@ -58,16 +58,17 @@ public class MappingJackson2CborHttpMessageConverter extends AbstractJackson2Htt */ public MappingJackson2CborHttpMessageConverter(ObjectMapper objectMapper) { super(objectMapper, new MediaType("application", "cbor")); - Assert.isAssignable(CBORFactory.class, objectMapper.getFactory().getClass()); + Assert.isInstanceOf(CBORFactory.class, objectMapper.getFactory(), "CBORFactory required"); } + /** * {@inheritDoc} - * The {@code objectMapper} parameter must be configured with a {@code CBORFactory} instance. + * The {@code ObjectMapper} must be configured with a {@code CBORFactory} instance. */ @Override public void setObjectMapper(ObjectMapper objectMapper) { - Assert.isAssignable(CBORFactory.class, objectMapper.getFactory().getClass()); + Assert.isInstanceOf(CBORFactory.class, objectMapper.getFactory(), "CBORFactory required"); super.setObjectMapper(objectMapper); } diff --git a/spring-web/src/main/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverter.java index 5d5040b85e7..e70694d4061 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverter.java @@ -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. @@ -58,16 +58,17 @@ public class MappingJackson2SmileHttpMessageConverter extends AbstractJackson2Ht */ public MappingJackson2SmileHttpMessageConverter(ObjectMapper objectMapper) { super(objectMapper, new MediaType("application", "x-jackson-smile")); - Assert.isAssignable(SmileFactory.class, objectMapper.getFactory().getClass()); + Assert.isInstanceOf(SmileFactory.class, objectMapper.getFactory(), "SmileFactory required"); } + /** * {@inheritDoc} - * The {@code objectMapper} parameter must be configured with a {@code SmileFactory} instance. + * The {@code ObjectMapper} must be configured with a {@code SmileFactory} instance. */ @Override public void setObjectMapper(ObjectMapper objectMapper) { - Assert.isAssignable(SmileFactory.class, objectMapper.getFactory().getClass()); + Assert.isInstanceOf(SmileFactory.class, objectMapper.getFactory(), "SmileFactory required"); super.setObjectMapper(objectMapper); } diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.java index 39eb13ef676..a829385634f 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.java @@ -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. @@ -60,16 +60,17 @@ public class MappingJackson2XmlHttpMessageConverter extends AbstractJackson2Http super(objectMapper, new MediaType("application", "xml"), new MediaType("text", "xml"), new MediaType("application", "*+xml")); - Assert.isAssignable(XmlMapper.class, objectMapper.getClass()); + Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required"); } + /** * {@inheritDoc} - * The {@code objectMapper} parameter must be a {@link XmlMapper} instance. + * The {@code ObjectMapper} parameter must be a {@link XmlMapper} instance. */ @Override public void setObjectMapper(ObjectMapper objectMapper) { - Assert.isAssignable(XmlMapper.class, objectMapper.getClass()); + Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required"); super.setObjectMapper(objectMapper); } diff --git a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java index c8e1ecb86b0..26cdc9f37e4 100644 --- a/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/server/ServletServerHttpRequest.java @@ -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. @@ -181,7 +181,9 @@ public class ServletServerHttpRequest implements ServerHttpRequest { @Override public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response) { if (this.asyncRequestControl == null) { - Assert.isInstanceOf(ServletServerHttpResponse.class, response); + if (!ServletServerHttpResponse.class.isInstance(response)) { + throw new IllegalArgumentException("Response must be a ServletServerHttpResponse: " + response.getClass()); + } ServletServerHttpResponse servletServerResponse = (ServletServerHttpResponse) response; this.asyncRequestControl = new ServletServerHttpAsyncRequestControl(this, servletServerResponse); } diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java index 2b9c682cee2..fe4f0a6f564 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java @@ -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. @@ -17,7 +17,6 @@ package org.springframework.http.server.reactive; import java.io.IOException; -import java.util.Objects; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.atomic.AtomicReference; @@ -28,6 +27,8 @@ import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.publisher.Operators; +import org.springframework.util.Assert; + /** * Abstract base class for {@code Publisher} implementations that bridge between * event-listener read APIs and Reactive Streams. @@ -48,6 +49,7 @@ public abstract class AbstractListenerReadPublisher implements Publisher { private final AtomicReference state = new AtomicReference<>(State.UNSUBSCRIBED); + @SuppressWarnings("unused") private volatile long demand; @SuppressWarnings("rawtypes") @@ -196,7 +198,8 @@ public abstract class AbstractListenerReadPublisher implements Publisher { UNSUBSCRIBED { @Override void subscribe(AbstractListenerReadPublisher publisher, Subscriber subscriber) { - Objects.requireNonNull(subscriber); + Assert.notNull(publisher, "Publisher must not be null"); + Assert.notNull(subscriber, "Subscriber must not be null"); if (publisher.changeState(this, NO_DEMAND)) { Subscription subscription = new ReadSubscription(publisher); publisher.subscriber = subscriber; diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteFlushProcessor.java b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteFlushProcessor.java index 4053fd30100..42797152a6e 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteFlushProcessor.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteFlushProcessor.java @@ -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. @@ -17,7 +17,6 @@ package org.springframework.http.server.reactive; import java.io.IOException; -import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; @@ -27,6 +26,8 @@ import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; +import org.springframework.util.Assert; + /** * An alternative to {@link AbstractListenerWriteProcessor} but instead writing * a {@code Publisher>} with flush boundaries enforces after @@ -127,10 +128,9 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo private enum State { UNSUBSCRIBED { - @Override public void onSubscribe(AbstractListenerWriteFlushProcessor processor, Subscription subscription) { - Objects.requireNonNull(subscription, "Subscription cannot be null"); + Assert.notNull(subscription, "Subscription must not be null"); if (processor.changeState(this, REQUESTED)) { processor.subscription = subscription; subscription.request(1); @@ -140,8 +140,8 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo } } }, - REQUESTED { + REQUESTED { @Override public void onNext(AbstractListenerWriteFlushProcessor processor, Publisher chunk) { if (processor.changeState(this, RECEIVED)) { @@ -150,7 +150,6 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo chunkProcessor.subscribe(new WriteSubscriber(processor)); } } - @Override public void onComplete(AbstractListenerWriteFlushProcessor processor) { if (processor.changeState(this, COMPLETED)) { @@ -158,8 +157,8 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo } } }, - RECEIVED { + RECEIVED { @Override public void writeComplete(AbstractListenerWriteFlushProcessor processor) { try { @@ -169,7 +168,6 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo processor.cancel(); processor.onError(ex); } - if (processor.subscriberCompleted) { if (processor.changeState(this, COMPLETED)) { processor.resultPublisher.publishComplete(); @@ -181,26 +179,21 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo } } } - @Override public void onComplete(AbstractListenerWriteFlushProcessor processor) { processor.subscriberCompleted = true; } }, - COMPLETED { + COMPLETED { @Override - public void onNext(AbstractListenerWriteFlushProcessor processor, - Publisher publisher) { + public void onNext(AbstractListenerWriteFlushProcessor processor, Publisher publisher) { // ignore - } - @Override public void onError(AbstractListenerWriteFlushProcessor processor, Throwable t) { // ignore } - @Override public void onComplete(AbstractListenerWriteFlushProcessor processor) { // ignore @@ -234,7 +227,6 @@ public abstract class AbstractListenerWriteFlushProcessor implements Processo private final AbstractListenerWriteFlushProcessor processor; - public WriteSubscriber(AbstractListenerWriteFlushProcessor processor) { this.processor = processor; } diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java index 55ea82967a4..eb1bbccd8bf 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java @@ -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. @@ -17,7 +17,6 @@ package org.springframework.http.server.reactive; import java.io.IOException; -import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; @@ -120,7 +119,9 @@ public abstract class AbstractListenerWriteProcessor implements Processor implements Processor void onSubscribe(AbstractListenerWriteProcessor processor, Subscription subscription) { - Objects.requireNonNull(subscription, "Subscription cannot be null"); + Assert.notNull(subscription, "Subscription must not be null"); if (processor.changeState(this, REQUESTED)) { processor.subscription = subscription; subscription.request(1); @@ -198,6 +198,7 @@ public abstract class AbstractListenerWriteProcessor implements Processor implements Processor void onNext(AbstractListenerWriteProcessor processor, T data) { if (processor.isDataEmpty(data)) { @@ -218,7 +218,6 @@ public abstract class AbstractListenerWriteProcessor implements Processor void onComplete(AbstractListenerWriteProcessor processor) { if (processor.changeState(this, COMPLETED)) { @@ -226,6 +225,7 @@ public abstract class AbstractListenerWriteProcessor implements Processor implements Processor void onWritePossible(AbstractListenerWriteProcessor processor) { if (processor.changeState(this, WRITING)) { @@ -265,38 +264,35 @@ public abstract class AbstractListenerWriteProcessor implements Processor void onComplete(AbstractListenerWriteProcessor processor) { processor.subscriberCompleted = true; } }, + /** * State that gets entered after a writing of the current data has been * {@code onWritePossible started}. */ WRITING { - @Override public void onComplete(AbstractListenerWriteProcessor processor) { processor.subscriberCompleted = true; } }, + /** * The terminal completed state. Does not respond to any events. */ COMPLETED { - @Override public void onNext(AbstractListenerWriteProcessor processor, T data) { // ignore } - @Override public void onError(AbstractListenerWriteProcessor processor, Throwable ex) { // ignore } - @Override public void onComplete(AbstractListenerWriteProcessor processor) { // ignore diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java index ac871739204..91e6d7dd79c 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java @@ -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. @@ -89,7 +89,7 @@ public abstract class AbstractServerHttpResponse implements ServerHttpResponse { @Override public boolean setStatusCode(HttpStatus statusCode) { - Assert.notNull(statusCode); + Assert.notNull(statusCode, "Status code must not be null"); if (this.state.get() == State.COMMITTED) { if (logger.isDebugEnabled()) { logger.debug("Can't set the status " + statusCode.toString() + diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupport.java b/spring-web/src/main/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupport.java index 16c535cc187..bac06a1635d 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupport.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupport.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.http.server.reactive; import java.util.LinkedHashMap; @@ -57,11 +58,9 @@ public abstract class HttpHandlerAdapterSupport { /** * Constructor with {@code HttpHandler}s mapped to distinct context paths. * Context paths must start but not end with "/" and must be encoded. - * *

At request time context paths are compared against the "raw" path of * the request URI in the order in which they are provided. The first one * to match is chosen. If none match the response status is set to 404. - * * @param handlerMap map with context paths and {@code HttpHandler}s. * @see ServerHttpRequest#getContextPath() */ @@ -85,9 +84,8 @@ public abstract class HttpHandlerAdapterSupport { private final Map handlerMap; - public CompositeHttpHandler(Map handlerMap) { - Assert.notEmpty(handlerMap); + Assert.notEmpty(handlerMap, "Handler map must not be empty"); this.handlerMap = initHandlerMap(handlerMap); } @@ -97,10 +95,10 @@ public abstract class HttpHandlerAdapterSupport { } private static void validateContextPath(String contextPath) { - Assert.hasText(contextPath, "contextPath must not be empty"); + Assert.hasText(contextPath, "Context path must not be empty"); if (!contextPath.equals("/")) { - Assert.isTrue(contextPath.startsWith("/"), "contextPath must begin with '/'"); - Assert.isTrue(!contextPath.endsWith("/"), "contextPath must not end with '/'"); + Assert.isTrue(contextPath.startsWith("/"), "Context path must begin with '/'"); + Assert.isTrue(!contextPath.endsWith("/"), "Context path must not end with '/'"); } } @@ -124,7 +122,9 @@ public abstract class HttpHandlerAdapterSupport { }); } - /** Strip the context path from native request if any */ + /** + * Strip the context path from the native request, if any. + */ private String getPathToUse(ServerHttpRequest request) { String path = request.getURI().getRawPath(); String contextPath = request.getContextPath(); diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java b/spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java index d46918aa726..ed5a4a4746d 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java @@ -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. @@ -50,12 +50,12 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme private static final int DEFAULT_BUFFER_SIZE = 8192; + private int bufferSize = DEFAULT_BUFFER_SIZE; + // Servlet is based on blocking I/O, hence the usage of non-direct, heap-based buffers // (i.e. 'false' as constructor argument) private DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(false); - private int bufferSize = DEFAULT_BUFFER_SIZE; - public ServletHttpHandlerAdapter(HttpHandler httpHandler) { super(httpHandler); @@ -66,21 +66,12 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme } - public void setDataBufferFactory(DataBufferFactory dataBufferFactory) { - Assert.notNull(dataBufferFactory, "'dataBufferFactory' must not be null"); - this.dataBufferFactory = dataBufferFactory; - } - - public DataBufferFactory getDataBufferFactory() { - return this.dataBufferFactory; - } - /** * Set the size of the input buffer used for reading in bytes. *

By default this is set to 8192. */ public void setBufferSize(int bufferSize) { - Assert.isTrue(bufferSize > 0); + Assert.isTrue(bufferSize > 0, "Buffer size must be larger than zero"); this.bufferSize = bufferSize; } @@ -91,10 +82,20 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme return this.bufferSize; } + public void setDataBufferFactory(DataBufferFactory dataBufferFactory) { + Assert.notNull(dataBufferFactory, "DataBufferFactory must not be null"); + this.dataBufferFactory = dataBufferFactory; + } + + public DataBufferFactory getDataBufferFactory() { + return this.dataBufferFactory; + } + + + // The Servlet.service method @Override public void service(ServletRequest request, ServletResponse response) throws IOException { - // Start async before Read/WriteListener registration AsyncContext asyncContext = request.startAsync(); @@ -105,18 +106,15 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme getHttpHandler().handle(httpRequest, httpResponse).subscribe(subscriber); } - protected ServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context) - throws IOException { - + protected ServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context) throws IOException { return new ServletServerHttpRequest(request, context, getDataBufferFactory(), getBufferSize()); } - protected ServerHttpResponse createResponse(HttpServletResponse response, AsyncContext context) - throws IOException { - + protected ServerHttpResponse createResponse(HttpServletResponse response, AsyncContext context) throws IOException { return new ServletServerHttpResponse(response, context, getDataBufferFactory(), getBufferSize()); } + // Other Servlet methods... @Override @@ -142,7 +140,6 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme private final AsyncContext asyncContext; - public HandlerResultSubscriber(AsyncContext asyncContext) { this.asyncContext = asyncContext; } diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java index c07c3840faf..63854ef3dc3 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java @@ -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. @@ -43,6 +43,7 @@ import org.springframework.util.Assert; /** * Adapt {@link ServerHttpResponse} to the Servlet {@link HttpServletResponse}. + * * @author Rossen Stoyanchev * @since 5.0 */ @@ -66,7 +67,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons Assert.notNull(response, "HttpServletResponse must not be null"); Assert.notNull(bufferFactory, "DataBufferFactory must not be null"); - Assert.isTrue(bufferSize > 0, "'bufferSize' must be greater than 0"); + Assert.isTrue(bufferSize > 0, "Buffer size must be greater than 0"); this.response = response; this.bufferSize = bufferSize; @@ -210,6 +211,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons } } + private class ResponseBodyWriteListener implements WriteListener { @Override @@ -228,6 +230,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons } } + private class ResponseBodyFlushProcessor extends AbstractListenerWriteFlushProcessor { @Override @@ -251,11 +254,11 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons } } + private class ResponseBodyProcessor extends AbstractListenerWriteProcessor { private final ServletOutputStream outputStream; - public ResponseBodyProcessor(ServletOutputStream outputStream) { this.outputStream = outputStream; } @@ -268,7 +271,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons @Override protected void releaseData() { if (logger.isTraceEnabled()) { - logger.trace("releaseBuffer: " + this.currentData); + logger.trace("releaseData: " + this.currentData); } DataBufferUtils.release(this.currentData); this.currentData = null; diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java index d43c4cb2665..bd16c86b810 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java @@ -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. @@ -30,7 +30,6 @@ import io.undertow.server.handlers.CookieImpl; import io.undertow.util.HttpString; import org.reactivestreams.Processor; import org.reactivestreams.Publisher; -import org.xnio.ChannelListener; import org.xnio.channels.StreamSinkChannel; import reactor.core.publisher.Mono; @@ -60,7 +59,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon public UndertowServerHttpResponse(HttpServerExchange exchange, DataBufferFactory bufferFactory) { super(bufferFactory); - Assert.notNull(exchange, "'exchange' is required."); + Assert.notNull(exchange, "HttpServerExchange is required"); this.exchange = exchange; } @@ -69,6 +68,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon return this.exchange; } + @Override protected void applyStatusCode() { HttpStatus statusCode = this.getStatusCode(); @@ -145,15 +145,13 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon private volatile ByteBuffer byteBuffer; - public ResponseBodyProcessor(StreamSinkChannel channel) { Assert.notNull(channel, "StreamSinkChannel must not be null"); this.channel = channel; } - public void registerListener() { - this.channel.getWriteSetter().set((ChannelListener) c -> onWritePossible()); + this.channel.getWriteSetter().set(c -> onWritePossible()); this.channel.resumeWrites(); } @@ -199,7 +197,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon @Override protected void releaseData() { if (logger.isTraceEnabled()) { - logger.trace("releaseBuffer: " + this.currentData); + logger.trace("releaseData: " + this.currentData); } DataBufferUtils.release(this.currentData); this.currentData = null; @@ -209,10 +207,11 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon @Override protected boolean isDataEmpty(DataBuffer dataBuffer) { - return dataBuffer.readableByteCount() == 0; + return (dataBuffer.readableByteCount() == 0); } } + private class ResponseBodyFlushProcessor extends AbstractListenerWriteFlushProcessor { @Override diff --git a/spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java b/spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java index f239b9426b2..ed9e0a030bf 100644 --- a/spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java +++ b/spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java @@ -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. @@ -16,7 +16,6 @@ package org.springframework.http.server.reactive; -import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; @@ -26,6 +25,8 @@ import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.publisher.Operators; +import org.springframework.util.Assert; + /** * Publisher returned from {@link ServerHttpResponse#writeWith(Publisher)}. * @@ -113,12 +114,10 @@ class WriteResultPublisher implements Publisher { UNSUBSCRIBED { @Override - void subscribe(WriteResultPublisher publisher, - Subscriber subscriber) { - Objects.requireNonNull(subscriber); + void subscribe(WriteResultPublisher publisher, Subscriber subscriber) { + Assert.notNull(subscriber, "Subscriber must not be null"); if (publisher.changeState(this, SUBSCRIBED)) { - Subscription subscription = - new ResponseBodyWriteResultSubscription(publisher); + Subscription subscription = new ResponseBodyWriteResultSubscription(publisher); publisher.subscriber = subscriber; subscriber.onSubscribe(subscription); if (publisher.publisherCompleted) { diff --git a/spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java b/spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java index 23bcc9c712d..438027a37de 100644 --- a/spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java +++ b/spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java @@ -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. @@ -136,15 +136,15 @@ public class PathExtensionContentNegotiationStrategy extends AbstractMappingCont /** * A public method exposing the knowledge of the path extension strategy to - * resolve file extensions to a MediaType in this case for a given + * resolve file extensions to a {@link MediaType} in this case for a given * {@link Resource}. The method first looks up any explicitly registered * file extensions first and then falls back on JAF if available. * @param resource the resource to look up - * @return the MediaType for the extension or {@code null}. + * @return the MediaType for the extension, or {@code null} if none found * @since 4.3 */ public MediaType getMediaTypeForResource(Resource resource) { - Assert.notNull(resource); + Assert.notNull(resource, "Resource must not be null"); MediaType mediaType = null; String filename = resource.getFilename(); String extension = StringUtils.getFilenameExtension(filename); diff --git a/spring-web/src/main/java/org/springframework/web/bind/UnsatisfiedServletRequestParameterException.java b/spring-web/src/main/java/org/springframework/web/bind/UnsatisfiedServletRequestParameterException.java index cb274152e44..9b4c91add0c 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/UnsatisfiedServletRequestParameterException.java +++ b/spring-web/src/main/java/org/springframework/web/bind/UnsatisfiedServletRequestParameterException.java @@ -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. @@ -64,7 +64,7 @@ public class UnsatisfiedServletRequestParameterException extends ServletRequestB Map actualParams) { super(""); - Assert.isTrue(!CollectionUtils.isEmpty(paramConditions)); + Assert.notEmpty(paramConditions, "Parameter conditions must not be empty"); this.paramConditions = paramConditions; this.actualParams = actualParams; } diff --git a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java index 25cf45afdb8..85204e96b42 100644 --- a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java +++ b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java @@ -37,7 +37,6 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; -import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -480,7 +479,10 @@ public class ContextLoader { private Class> loadInitializerClass(String className) { try { Class clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); - Assert.isAssignable(ApplicationContextInitializer.class, clazz); + if (!ApplicationContextInitializer.class.isAssignableFrom(clazz)) { + throw new ApplicationContextException( + "Initializer class does not implement ApplicationContextInitializer interface: " + clazz); + } return (Class>) clazz; } catch (ClassNotFoundException ex) { diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index 98c9a7cdd15..86bd732c409 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -816,7 +816,7 @@ final class HierarchicalUriComponents extends UriComponents { private final List pathComponents; public PathComponentComposite(List pathComponents) { - Assert.notNull(pathComponents); + Assert.notNull(pathComponents, "PathComponent List must not be null"); this.pathComponents = pathComponents; } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupportTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupportTests.java index 8f358fae7e6..896745e09a2 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupportTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHandlerAdapterSupportTests.java @@ -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. @@ -41,10 +41,10 @@ import static org.junit.Assert.fail; public class HttpHandlerAdapterSupportTests { @Test - public void invalidContextPath() throws Exception { - testInvalidContextPath(" ", "contextPath must not be empty"); - testInvalidContextPath("path", "contextPath must begin with '/'"); - testInvalidContextPath("/path/", "contextPath must not end with '/'"); + public void invalidContextPath() { + testInvalidContextPath(" ", "Context path must not be empty"); + testInvalidContextPath("path", "Context path must begin with '/'"); + testInvalidContextPath("/path/", "Context path must not end with '/'"); } private void testInvalidContextPath(String contextPath, String errorMessage) { @@ -58,7 +58,7 @@ public class HttpHandlerAdapterSupportTests { } @Test - public void match() throws Exception { + public void match() { TestHttpHandler handler1 = new TestHttpHandler(); TestHttpHandler handler2 = new TestHttpHandler(); TestHttpHandler handler3 = new TestHttpHandler(); @@ -75,7 +75,7 @@ public class HttpHandlerAdapterSupportTests { } @Test - public void matchWithContextPathEqualToPath() throws Exception { + public void matchWithContextPathEqualToPath() { TestHttpHandler handler1 = new TestHttpHandler(); TestHttpHandler handler2 = new TestHttpHandler(); TestHttpHandler handler3 = new TestHttpHandler(); @@ -92,7 +92,7 @@ public class HttpHandlerAdapterSupportTests { } @Test - public void matchWithNativeContextPath() throws Exception { + public void matchWithNativeContextPath() { MockServerHttpRequest request = MockServerHttpRequest .get("/yet/another/path") .contextPath("/yet") // contextPath in underlying request diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/AbstractHttpServer.java b/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/AbstractHttpServer.java index 7fa86872226..76c3932099c 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/AbstractHttpServer.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/AbstractHttpServer.java @@ -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. @@ -80,12 +80,12 @@ public abstract class AbstractHttpServer implements HttpServer { @Override public final void afterPropertiesSet() throws Exception { - synchronized (this.lifecycleMonitor) { - Assert.isTrue(this.host != null); - Assert.isTrue(this.port != -1); - Assert.isTrue(this.httpHandler != null || this.handlerMap != null); - Assert.isTrue(!this.running); + Assert.notNull(this.host, "Host must not be null"); + Assert.isTrue(this.port >= 0, "Port must not be a negative number"); + Assert.isTrue(this.httpHandler != null || this.handlerMap != null, "No HttpHandler configured"); + Assert.state(!this.running, "Cannot reconfigure while running"); + synchronized (this.lifecycleMonitor) { initServer(); } } @@ -110,7 +110,7 @@ public abstract class AbstractHttpServer implements HttpServer { try { startInternal(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException(ex); } } @@ -128,7 +128,7 @@ public abstract class AbstractHttpServer implements HttpServer { try { stopInternal(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException(ex); } finally { diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/HttpServer.java b/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/HttpServer.java index 8bc8ae12d4e..2116ad05225 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/HttpServer.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/HttpServer.java @@ -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. @@ -16,7 +16,6 @@ package org.springframework.http.server.reactive.bootstrap; - import org.springframework.beans.factory.InitializingBean; import org.springframework.context.Lifecycle; import org.springframework.http.server.reactive.HttpHandler; diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/TomcatHttpServer.java b/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/TomcatHttpServer.java index fc41b355723..508810fd6b4 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/TomcatHttpServer.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/bootstrap/TomcatHttpServer.java @@ -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. @@ -43,7 +43,7 @@ public class TomcatHttpServer extends AbstractHttpServer { } public TomcatHttpServer(String baseDir, Class wsListener) { - Assert.notNull(baseDir); + Assert.notNull(baseDir, "Base dir must not be null"); this.baseDir = baseDir; this.wsListener = wsListener; } diff --git a/spring-web/src/test/java/org/springframework/mock/web/test/MockAsyncContext.java b/spring-web/src/test/java/org/springframework/mock/web/test/MockAsyncContext.java index 1a04889667b..f16e1f6b40b 100644 --- a/spring-web/src/test/java/org/springframework/mock/web/test/MockAsyncContext.java +++ b/spring-web/src/test/java/org/springframework/mock/web/test/MockAsyncContext.java @@ -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. @@ -61,7 +61,7 @@ public class MockAsyncContext implements AsyncContext { public void addDispatchHandler(Runnable handler) { - Assert.notNull(handler); + Assert.notNull(handler, "Dispatch handler must not be null"); this.dispatchHandlers.add(handler); } @@ -77,7 +77,7 @@ public class MockAsyncContext implements AsyncContext { @Override public boolean hasOriginalRequestAndResponse() { - return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse); + return (this.request instanceof MockHttpServletRequest && this.response instanceof MockHttpServletResponse); } @Override @@ -112,8 +112,8 @@ public class MockAsyncContext implements AsyncContext { try { listener.onComplete(new AsyncEvent(this, this.request, this.response)); } - catch (IOException e) { - throw new IllegalStateException("AsyncListener failure", e); + catch (IOException ex) { + throw new IllegalStateException("AsyncListener failure", ex); } } } diff --git a/spring-web/src/test/java/org/springframework/mock/web/test/MockPageContext.java b/spring-web/src/test/java/org/springframework/mock/web/test/MockPageContext.java index 020d57866c7..b60acba5efe 100644 --- a/spring-web/src/test/java/org/springframework/mock/web/test/MockPageContext.java +++ b/spring-web/src/test/java/org/springframework/mock/web/test/MockPageContext.java @@ -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. @@ -356,12 +356,12 @@ public class MockPageContext extends PageContext { } public byte[] getContentAsByteArray() { - Assert.isTrue(this.response instanceof MockHttpServletResponse); + Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required"); return ((MockHttpServletResponse) this.response).getContentAsByteArray(); } public String getContentAsString() throws UnsupportedEncodingException { - Assert.isTrue(this.response instanceof MockHttpServletResponse); + Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required"); return ((MockHttpServletResponse) this.response).getContentAsString(); } diff --git a/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java b/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java index 09f3700a3cb..aa30b5cac1f 100644 --- a/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java @@ -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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.util; import java.net.URI; @@ -21,13 +22,14 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; /** * Unit tests for {@link DefaultUriTemplateHandler}. * * @author Rossen Stoyanchev */ +@SuppressWarnings("deprecation") public class DefaultUriTemplateHandlerTests { private final DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler(); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java index c5f3146939b..d3b91a754dd 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java @@ -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. @@ -190,7 +190,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; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java index 671b2d323af..df5257e1f07 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java @@ -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. @@ -679,8 +679,8 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap private final String mappingName; public MappingRegistration(T mapping, HandlerMethod handlerMethod, List 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.emptyList()); @@ -745,7 +745,7 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap private static class EmptyHandler { public void handle() { - throw new UnsupportedOperationException("not implemented"); + throw new UnsupportedOperationException("Not implemented"); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java index 71b82a74181..2b05738c89d 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java @@ -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 matchingPatterns = new ArrayList<>(); for (String registeredPattern : this.handlerMap.keySet()) { @@ -182,20 +183,26 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i } } } - String bestPatternMatch = null; + + String bestMatch = null; Comparator 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 uriTemplateVariables = new LinkedHashMap<>(); for (String matchingPattern : matchingPatterns) { - if (patternComparator.compare(bestPatternMatch, matchingPattern) == 0) { + if (patternComparator.compare(bestMatch, matchingPattern) == 0) { Map vars = getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath); Map 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; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultMethodReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultMethodReturnValueHandler.java index 87ef76c8aea..7337ef980ba 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultMethodReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultMethodReturnValueHandler.java @@ -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. @@ -92,7 +92,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); } @@ -105,7 +108,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; } } @@ -118,7 +121,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 result = new DeferredResult<>(); ((ListenableFuture) returnValue).addCallback(new ListenableFutureCallback() { @Override @@ -142,7 +145,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 result = new DeferredResult<>(); @SuppressWarnings("unchecked") CompletionStage future = (CompletionStage) returnValue; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpHeadersReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpHeadersReturnValueHandler.java index e3dd91d2add..b195f353a8a 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpHeadersReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpHeadersReturnValueHandler.java @@ -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()) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java index e2031f67e1b..547829507cf 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java @@ -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(); @@ -522,18 +522,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; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java index aa1f8976cb1..d15025470d7 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java @@ -395,7 +395,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter * @param interceptors the interceptors to register */ public void setCallableInterceptors(List interceptors) { - Assert.notNull(interceptors); + Assert.notNull(interceptors, "CallableProcessingInterceptor List must not be null"); this.callableInterceptors = interceptors.toArray(new CallableProcessingInterceptor[interceptors.size()]); } @@ -404,7 +404,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter * @param interceptors the interceptors to register */ public void setDeferredResultInterceptors(List interceptors) { - Assert.notNull(interceptors); + Assert.notNull(interceptors, "DeferredResultProcessingInterceptor List must not be null"); this.deferredResultInterceptors = interceptors.toArray(new DeferredResultProcessingInterceptor[interceptors.size()]); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java index a7e391c0516..e70e16c8494 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java @@ -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. @@ -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; } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandler.java index a3b646125c6..cbbd1e62a90 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandler.java @@ -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 callable = new StreamingResponseBodyTask(outputMessage.getBody(), streamingBody); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java index 367aed85033..f39c12a45bc 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java @@ -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(); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java index e2e45cc927c..71a47d3b5ec 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java @@ -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. @@ -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 requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest()); if (requestedMediaTypes != null) { List candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java index fe4a1688968..823f17b3f3d 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java @@ -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. @@ -125,7 +125,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; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java index 44a22bb6cab..3709a5e8ed5 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java @@ -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(); } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/AbstractWebSocketHandlerRegistration.java b/spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/AbstractWebSocketHandlerRegistration.java index 20db2a831fa..8b9fb9512c8 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/AbstractWebSocketHandlerRegistration.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/AbstractWebSocketHandlerRegistration.java @@ -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. @@ -28,8 +28,8 @@ import org.springframework.util.ObjectUtils; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.HandshakeHandler; import org.springframework.web.socket.server.HandshakeInterceptor; -import org.springframework.web.socket.server.support.OriginHandshakeInterceptor; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; +import org.springframework.web.socket.server.support.OriginHandshakeInterceptor; import org.springframework.web.socket.sockjs.SockJsService; import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler; @@ -45,7 +45,7 @@ public abstract class AbstractWebSocketHandlerRegistration implements WebSock private final TaskScheduler sockJsTaskScheduler; - private MultiValueMap handlerMap = new LinkedMultiValueMap<>(); + private final MultiValueMap handlerMap = new LinkedMultiValueMap<>(); private HandshakeHandler handshakeHandler; @@ -63,8 +63,8 @@ public abstract class AbstractWebSocketHandlerRegistration implements WebSock @Override public WebSocketHandlerRegistration addHandler(WebSocketHandler handler, String... paths) { - Assert.notNull(handler); - Assert.notEmpty(paths); + Assert.notNull(handler, "WebSocketHandler must not be null"); + Assert.notEmpty(paths, "Paths must not be empty"); this.handlerMap.put(handler, Arrays.asList(paths)); return this; } @@ -108,13 +108,14 @@ public abstract class AbstractWebSocketHandlerRegistration implements WebSock this.sockJsServiceRegistration.setTransportHandlerOverrides(transportHandler); } if (!this.allowedOrigins.isEmpty()) { - this.sockJsServiceRegistration.setAllowedOrigins(this.allowedOrigins.toArray(new String[this.allowedOrigins.size()])); + this.sockJsServiceRegistration.setAllowedOrigins( + this.allowedOrigins.toArray(new String[this.allowedOrigins.size()])); } return this.sockJsServiceRegistration; } protected HandshakeInterceptor[] getInterceptors() { - List interceptors = new ArrayList<>(); + List interceptors = new ArrayList<>(this.interceptors.size() + 1); interceptors.addAll(this.interceptors); interceptors.add(new OriginHandshakeInterceptor(this.allowedOrigins)); return interceptors.toArray(new HandshakeInterceptor[interceptors.size()]); @@ -126,7 +127,7 @@ public abstract class AbstractWebSocketHandlerRegistration implements WebSock SockJsService sockJsService = this.sockJsServiceRegistration.getSockJsService(); for (WebSocketHandler wsHandler : this.handlerMap.keySet()) { for (String path : this.handlerMap.get(wsHandler)) { - String pathPattern = path.endsWith("/") ? path + "**" : path + "/**"; + String pathPattern = (path.endsWith("/") ? path + "**" : path + "/**"); addSockJsServiceMapping(mappings, sockJsService, wsHandler, pathPattern); } } @@ -145,9 +146,10 @@ public abstract class AbstractWebSocketHandlerRegistration implements WebSock } private HandshakeHandler getOrCreateHandshakeHandler() { - return (this.handshakeHandler != null) ? this.handshakeHandler : new DefaultHandshakeHandler(); + return (this.handshakeHandler != null ? this.handshakeHandler : new DefaultHandshakeHandler()); } + protected abstract M createMappings(); protected abstract void addSockJsServiceMapping(M mappings, SockJsService sockJsService, diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistry.java b/spring-websocket/src/main/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistry.java index 6889a6fbe30..452a97c5ad4 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistry.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistry.java @@ -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. @@ -60,6 +60,7 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati return Ordered.LOWEST_PRECEDENCE; } + // SmartApplicationListener methods @Override @@ -69,7 +70,6 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati @Override public void onApplicationEvent(ApplicationEvent event) { - AbstractSubProtocolEvent subProtocolEvent = (AbstractSubProtocolEvent) event; Message message = subProtocolEvent.getMessage(); SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); @@ -129,6 +129,7 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati return true; } + // SimpUserRegistry methods @Override @@ -169,12 +170,10 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati private final String name; - private final Map userSessions = - new ConcurrentHashMap<>(1); - + private final Map userSessions = new ConcurrentHashMap<>(1); public LocalSimpUser(String userName) { - Assert.notNull(userName); + Assert.notNull(userName, "User name must not be null"); this.name = userName; } @@ -208,13 +207,8 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati @Override public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof SimpUser)) { - return false; - } - return this.name.equals(((SimpUser) other).getName()); + return (this == other || + (other instanceof SimpUser && this.name.equals(((SimpUser) other).getName()))); } @Override @@ -228,6 +222,7 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati } } + private static class LocalSimpSession implements SimpSession { private final String id; @@ -236,10 +231,9 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati private final Map subscriptions = new ConcurrentHashMap<>(4); - public LocalSimpSession(String id, LocalSimpUser user) { - Assert.notNull(id); - Assert.notNull(user); + Assert.notNull(id, "Id must not be null"); + Assert.notNull(user, "User must not be null"); this.id = id; this.user = user; } @@ -268,19 +262,14 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati } @Override - public int hashCode() { - return this.id.hashCode(); + public boolean equals(Object other) { + return (this == other || + (other instanceof SimpSubscription && this.id.equals(((SimpSubscription) other).getId()))); } @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof SimpSubscription)) { - return false; - } - return this.id.equals(((SimpSubscription) other).getId()); + public int hashCode() { + return this.id.hashCode(); } @Override @@ -289,6 +278,7 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati } } + private static class LocalSimpSubscription implements SimpSubscription { private final String id; @@ -297,11 +287,10 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati private final String destination; - public LocalSimpSubscription(String id, String destination, LocalSimpSession session) { - Assert.notNull(id); - Assert.hasText(destination); - Assert.notNull(session); + Assert.notNull(id, "Id must not be null"); + Assert.hasText(destination, "Destination must not be empty"); + Assert.notNull(session, "Session must not be null"); this.id = id; this.destination = destination; this.session = session; @@ -322,22 +311,22 @@ public class DefaultSimpUserRegistry implements SimpUserRegistry, SmartApplicati return this.destination; } - @Override - public int hashCode() { - return 31 * this.id.hashCode() + getSession().hashCode(); - } - @Override public boolean equals(Object other) { if (this == other) { return true; } - if (other == null || !(other instanceof SimpSubscription)) { + if (!(other instanceof SimpSubscription)) { return false; } SimpSubscription otherSubscription = (SimpSubscription) other; - return (getSession().getId().equals(otherSubscription.getSession().getId()) && - this.id.equals(otherSubscription.getId())); + return (this.id.equals(otherSubscription.getId()) && + getSession().getId().equals(otherSubscription.getSession().getId())); + } + + @Override + public int hashCode() { + return this.id.hashCode() * 31 + getSession().getId().hashCode(); } @Override diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java b/spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java index 9ab8a331796..45963cd830b 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java @@ -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. @@ -174,10 +174,10 @@ public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Serv String selectedProtocol, List selectedExtensions, Principal user, WebSocketHandler wsHandler, Map attributes) throws HandshakeFailureException { - Assert.isInstanceOf(ServletServerHttpRequest.class, request); + Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required"); HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); - Assert.isInstanceOf(ServletServerHttpResponse.class, response); + Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required"); HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse(); Assert.isTrue(this.factoryAdapter.getFactory().isUpgradeRequest(servletRequest, servletResponse), diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/AbstractStandardUpgradeStrategy.java b/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/AbstractStandardUpgradeStrategy.java index e7f2c841633..38a52fdc5cb 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/AbstractStandardUpgradeStrategy.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/server/standard/AbstractStandardUpgradeStrategy.java @@ -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. @@ -71,12 +71,12 @@ public abstract class AbstractStandardUpgradeStrategy implements RequestUpgradeS } protected final HttpServletRequest getHttpServletRequest(ServerHttpRequest request) { - Assert.isTrue(request instanceof ServletServerHttpRequest); + Assert.isTrue(request instanceof ServletServerHttpRequest, "ServletServerHttpRequest required"); return ((ServletServerHttpRequest) request).getServletRequest(); } protected final HttpServletResponse getHttpServletResponse(ServerHttpResponse response) { - Assert.isTrue(response instanceof ServletServerHttpResponse); + Assert.isTrue(response instanceof ServletServerHttpResponse, "ServletServerHttpResponse required"); return ((ServletServerHttpResponse) response).getServletResponse(); } @@ -92,8 +92,8 @@ public abstract class AbstractStandardUpgradeStrategy implements RequestUpgradeS protected List getInstalledExtensions(WebSocketContainer container) { List result = new ArrayList<>(); - for (Extension ext : container.getInstalledExtensions()) { - result.add(new StandardToWebSocketExtensionAdapter(ext)); + for (Extension extension : container.getInstalledExtensions()) { + result.add(new StandardToWebSocketExtensionAdapter(extension)); } return result; } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java index e52c2cae6f3..75e7c514b76 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java @@ -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. @@ -81,7 +81,7 @@ public class RestTemplateXhrTransport extends AbstractXhrTransport { * time the transports connects. */ public void setTaskExecutor(TaskExecutor taskExecutor) { - Assert.notNull(this.taskExecutor); + Assert.notNull(taskExecutor, "TaskExecutor must not be null"); this.taskExecutor = taskExecutor; } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/WebSocketTransport.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/WebSocketTransport.java index 30fbd071c99..227f4fae3c4 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/WebSocketTransport.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/WebSocketTransport.java @@ -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. @@ -19,7 +19,7 @@ package org.springframework.web.socket.sockjs.client; import java.net.URI; import java.util.Collections; import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -82,7 +82,7 @@ public class WebSocketTransport implements Transport, Lifecycle { URI url = request.getTransportUrl(); WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHandshakeHeaders()); if (logger.isDebugEnabled()) { - logger.debug("Starting WebSocket session url=" + url); + logger.debug("Starting WebSocket session on " + url); } this.webSocketClient.doHandshake(handler, headers, url).addCallback( new ListenableFutureCallback() { @@ -144,16 +144,16 @@ public class WebSocketTransport implements Transport, Lifecycle { private final WebSocketClientSockJsSession sockJsSession; - private final AtomicInteger connectCount = new AtomicInteger(0); + private final AtomicBoolean connected = new AtomicBoolean(false); public ClientSockJsWebSocketHandler(WebSocketClientSockJsSession session) { - Assert.notNull(session); + Assert.notNull(session, "Session must not be null"); this.sockJsSession = session; } @Override public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception { - Assert.isTrue(this.connectCount.compareAndSet(0, 1)); + Assert.state(this.connected.compareAndSet(false, true), "Already connected"); this.sockJsSession.initializeDelegateSession(webSocketSession); } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java index 4b00a038f8e..dc89abea2b7 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java @@ -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. @@ -162,7 +162,7 @@ public abstract class AbstractSockJsSession implements SockJsSession { public final void sendMessage(WebSocketMessage message) throws IOException { Assert.state(!isClosed(), "Cannot send a message when session is closed"); - Assert.isInstanceOf(TextMessage.class, message, "SockJS supports text messages only: " + message); + Assert.isInstanceOf(TextMessage.class, message, "SockJS supports text messages only"); sendMessageInternal(((TextMessage) message).getPayload()); } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/StreamingSockJsSession.java b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/StreamingSockJsSession.java index cc308b0ec72..2eda43e60ad 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/StreamingSockJsSession.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/StreamingSockJsSession.java @@ -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. @@ -58,7 +58,7 @@ public abstract class StreamingSockJsSession extends AbstractHttpSockJsSession { boolean initialRequest) throws IOException { byte[] prelude = getPrelude(request); - Assert.notNull(prelude); + Assert.state(prelude != null, "Prelude expected"); response.getBody().write(prelude); response.flush();