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 9d2bc141c6..d075741490 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 92fc174bea..d7a8d1168b 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 f95c57cd70..ac80c0e059 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. @@ -223,7 +223,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 dc1516ab02..a110bc4461 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-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. @@ -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 ab1a92dd68..324deb7ac5 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. @@ -766,7 +766,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 64d4d2c2ee..a54429203b 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 b20f7bbe25..8e960c85e1 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-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. @@ -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 8d93e9884a..f53736e521 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-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,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; /** @@ -210,7 +209,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 b15c215f7e..56fc64be85 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-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. @@ -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,22 +76,21 @@ 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"); CacheResultOperation operation = new CacheResultOperation(methodDetails, defaultCacheResolver, defaultKeyGenerator, defaultExceptionCacheResolver); - return new DefaultCacheInvocationContext(operation, new Sample(), new Object[] {"id"}); + return new DefaultCacheInvocationContext<>(operation, new Sample(), new Object[] {"id"}); } 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/AbstractCacheInvoker.java b/spring-context/src/main/java/org/springframework/cache/interceptor/AbstractCacheInvoker.java index 4d3da40022..81edc06703 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/AbstractCacheInvoker.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/AbstractCacheInvoker.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. @@ -37,7 +37,7 @@ public abstract class AbstractCacheInvoker { } protected AbstractCacheInvoker(CacheErrorHandler errorHandler) { - Assert.notNull("ErrorHandler must not be null"); + Assert.notNull(errorHandler, "ErrorHandler must not be null"); this.errorHandler = errorHandler; } 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 271b59f1e6..952f6c7d68 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 2e7047389f..1fbbd23bfc 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 ec8e6916f0..81268227d7 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 fb4f50b383..edddb0d552 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. @@ -128,7 +128,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 2f74120590..7a2a74afda 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 19bb244bff..2d17df795b 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 25da88cf3f..a8eec500df 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 ee9d5095d7..dd9fcd3182 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 2eda9eddd8..75e6515a69 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-core/src/main/java/org/springframework/core/Constants.java b/spring-core/src/main/java/org/springframework/core/Constants.java index 3f8d9737bc..4310b9a478 100644 --- a/spring-core/src/main/java/org/springframework/core/Constants.java +++ b/spring-core/src/main/java/org/springframework/core/Constants.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. @@ -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 f3d516702f..dcb9c29591 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 eaae658a4d..5ed4db0fa2 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 b34e4b9dc4..a2ebe34719 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-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. @@ -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 76b45186be..fa18e522ca 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. @@ -48,20 +48,20 @@ import java.util.Map; * * @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 { /** - * Assert a boolean expression, throwing {@code IllegalArgumentException} - * if the test result is {@code false}. + * Assert a boolean expression, throwing an {@code IllegalArgumentException} + * if the expression evaluates to {@code false}. *

Assert.isTrue(i > 0, "The value must be greater than zero");
* @param expression a boolean expression * @param message the exception message to use if the assertion fails - * @throws IllegalArgumentException if expression is {@code false} + * @throws IllegalArgumentException if {@code expression} is {@code false} */ public static void isTrue(boolean expression, String message) { if (!expression) { @@ -70,18 +70,15 @@ public abstract class Assert { } /** - * Assert a boolean expression, throwing {@code IllegalArgumentException} - * if the test result is {@code false}. - *
Assert.isTrue(i > 0);
- * @param expression a boolean expression - * @throws IllegalArgumentException if expression is {@code false} + * @deprecated as of 4.3.7, in favor of {@link #isTrue(boolean, String)} */ + @Deprecated public static void isTrue(boolean expression) { isTrue(expression, "[Assertion failed] - this expression must be true"); } /** - * Assert that an object is {@code null} . + * Assert that an object is {@code null}. *
Assert.isNull(value, "The value must be null");
* @param object the object to check * @param message the exception message to use if the assertion fails @@ -94,17 +91,15 @@ 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} + * @deprecated as of 4.3.7, in favor of {@link #isNull(Object, String)} */ + @Deprecated public static void isNull(Object object) { isNull(object, "[Assertion failed] - the object argument must be null"); } /** - * Assert that an object is not {@code null} . + * Assert that an object is not {@code null}. *
Assert.notNull(clazz, "The class must not be null");
* @param object the object to check * @param message the exception message to use if the assertion fails @@ -117,11 +112,9 @@ 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} + * @deprecated as of 4.3.7, in favor of {@link #notNull(Object, String)} */ + @Deprecated public static void notNull(Object object) { notNull(object, "[Assertion failed] - this argument is required; it must not be null"); } @@ -142,20 +135,16 @@ 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 + * @deprecated as of 4.3.7, in favor of {@link #hasLength(String, String)} */ + @Deprecated 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 has valid text content; that is, it must not + * 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 @@ -170,13 +159,9 @@ public abstract class Assert { } /** - * Assert that the given String has 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 + * @deprecated as of 4.3.7, in favor of {@link #hasText(String, String)} */ + @Deprecated public static void hasText(String text) { hasText(text, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"); @@ -198,24 +183,21 @@ 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 + * @deprecated as of 4.3.7, in favor of {@link #doesNotContain(String, String, String)} */ + @Deprecated 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 has elements; that is, it must not be - * {@code null} and must have at least one element. - *
Assert.notEmpty(array, "The array must have elements");
+ * Assert that an array contains elements; that is, it must not be + * {@code null} and must contain at least one element. + *
Assert.notEmpty(array, "The array must contain elements");
* @param array the array to check * @param message the exception message to use if the assertion fails - * @throws IllegalArgumentException if the object array is {@code null} or has no elements + * @throws IllegalArgumentException if the object array is {@code null} or contains no elements */ public static void notEmpty(Object[] array, String message) { if (ObjectUtils.isEmpty(array)) { @@ -224,20 +206,17 @@ public abstract class Assert { } /** - * Assert that an array has elements; that is, it must not be - * {@code null} and must have at least one element. - *
Assert.notEmpty(array);
- * @param array the array to check - * @throws IllegalArgumentException if the object array is {@code null} or has no elements + * @deprecated as of 4.3.7, in favor of {@link #notEmpty(Object[], String)} */ + @Deprecated 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 has no null elements. - * Note: Does not complain if the array is empty! - *
Assert.noNullElements(array, "The array must have non-null elements");
+ * Assert that an array contains no {@code null} elements. + *

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

Assert.noNullElements(array, "The array must contain non-null elements");
* @param array the array to check * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if the object array contains a {@code null} element @@ -253,23 +232,21 @@ public abstract class Assert { } /** - * Assert that an array has no 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 + * @deprecated as of 4.3.7, in favor of {@link #noNullElements(Object[], String)} */ + @Deprecated public static void noNullElements(Object[] array) { noNullElements(array, "[Assertion failed] - this array must not contain any null elements"); } /** - * Assert that a collection has elements; that is, it must not be - * {@code null} and must have at least one element. - *
Assert.notEmpty(collection, "Collection must have elements");
+ * 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 * @param message the exception message to use if the assertion fails - * @throws IllegalArgumentException if the collection is {@code null} or has no elements + * @throws IllegalArgumentException if the collection is {@code null} or + * contains no elements */ public static void notEmpty(Collection collection, String message) { if (CollectionUtils.isEmpty(collection)) { @@ -278,24 +255,21 @@ public abstract class Assert { } /** - * Assert that a collection has elements; that is, it must not be - * {@code null} and must have at least one element. - *
Assert.notEmpty(collection, "Collection must have elements");
- * @param collection the collection to check - * @throws IllegalArgumentException if the collection is {@code null} or has no elements + * @deprecated as of 4.3.7, in favor of {@link #notEmpty(Collection, String)} */ + @Deprecated 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 has entries; that is, it must not be {@code null} - * and must have at least one entry. - *
Assert.notEmpty(map, "Map must have entries");
+ * Assert that a Map contains entries; that is, it must not be {@code null} + * and must contain at least one entry. + *
Assert.notEmpty(map, "Map must contain entries");
* @param map the map to check * @param message the exception message to use if the assertion fails - * @throws IllegalArgumentException if the map is {@code null} or has no entries + * @throws IllegalArgumentException if the map is {@code null} or contains no entries */ public static void notEmpty(Map map, String message) { if (CollectionUtils.isEmpty(map)) { @@ -304,26 +278,31 @@ public abstract class Assert { } /** - * Assert that a Map has entries; that is, it must not be {@code null} - * and must have at least one entry. - *
Assert.notEmpty(map);
- * @param map the map to check - * @throws IllegalArgumentException if the map is {@code null} or has no entries + * @deprecated as of 4.3.7, in favor of {@link #notEmpty(Map, String)} */ + @Deprecated 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 clazz the required class + *
Assert.instanceOf(Foo.class, foo, "Processing Foo:");
+ * @param type the type to check against * @param obj the object to check - * @throws IllegalArgumentException if the object is not an instance of clazz + * @param message a message which will be prepended to the message generated + * 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 object is not an instance of type * @see Class#isInstance */ - public static void isInstanceOf(Class clazz, Object obj) { - isInstanceOf(clazz, obj, ""); + public static void isInstanceOf(Class type, Object obj, String message) { + notNull(type, "Type to check against must not be null"); + if (!type.isInstance(obj)) { + 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); + } } /** @@ -331,20 +310,28 @@ public abstract class Assert { *
Assert.instanceOf(Foo.class, foo);
* @param type the type to check against * @param obj the object to check - * @param message a message which will be prepended to the message produced by - * the function itself, and which may be used to provide context. It should - * normally end in ":" or "." so that the generated message looks OK when - * appended to it. - * @throws IllegalArgumentException if the object is not an instance of clazz + * @throws IllegalArgumentException if the object is not an instance of type * @see Class#isInstance */ - public static void isInstanceOf(Class type, Object obj, String message) { - notNull(type, "Type to check against must not be null"); - if (!type.isInstance(obj)) { - throw new IllegalArgumentException( - (StringUtils.hasLength(message) ? message + " " : "") + - "Object of class [" + (obj != null ? obj.getClass().getName() : "null") + - "] must be an instance of " + type); + public static void isInstanceOf(Class type, Object obj) { + isInstanceOf(type, obj, ""); + } + + /** + * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}. + *
Assert.isAssignable(Number.class, myClass);
+ * @param superType the super type to check against + * @param subType the sub type to check + * @param message a message which will be prepended to the message generated + * 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 + */ + 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)) { + throw new IllegalArgumentException(StringUtils.hasLength(message) ? message + ": " + subType : + subType + " is not assignable to " + superType); } } @@ -360,32 +347,14 @@ public abstract class Assert { } /** - * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}. - *
Assert.isAssignable(Number.class, myClass);
- * @param superType the super type to check against - * @param subType the sub type to check - * @param message a message which will be prepended to the message produced by - * the function itself, and which may be used to provide 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 - */ - public static void isAssignable(Class superType, Class subType, String message) { - notNull(superType, "Type to check against must not be null"); - if (subType == null || !superType.isAssignableFrom(subType)) { - throw new IllegalArgumentException((StringUtils.hasLength(message) ? message + " " : "") + - subType + " is not assignable to " + superType); - } - } - - /** - * Assert a boolean expression, throwing {@code IllegalStateException} - * if the test result is {@code false}. Call isTrue if you wish to - * throw IllegalArgumentException on an assertion failure. + * Assert a boolean expression, throwing an {@code 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, "The id property must not already be initialized");
* @param expression a boolean expression * @param message the exception message to use if the assertion fails - * @throws IllegalStateException if expression is {@code false} + * @throws IllegalStateException if {@code expression} is {@code false} */ public static void state(boolean expression, String message) { if (!expression) { @@ -394,14 +363,9 @@ public abstract class Assert { } /** - * Assert a boolean expression, throwing {@link IllegalStateException} - * if the test result is {@code false}. - *

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

Assert.state(id == null);
- * @param expression a boolean expression - * @throws IllegalStateException if the supplied expression is {@code false} + * @deprecated as of 4.3.7, in favor of {@link #state(boolean, String)} */ + @Deprecated public static void state(boolean expression) { state(expression, "[Assertion failed] - this state invariant must be true"); } 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 7710ed273d..ff2c36717a 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 b3c5d43335..00ee6ef877 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-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,18 +16,15 @@ package org.springframework.util; -import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; import java.util.Map; -import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import static java.util.Collections.*; + /** * Unit tests for the {@link Assert} class. * @@ -36,146 +33,249 @@ import org.junit.rules.ExpectedException; * @author Rick Evans * @author Arjen Poutsma * @author Sam Brannen + * @author Juergen Hoeller */ public class AssertTests { @Rule - public ExpectedException thrown = ExpectedException.none(); + public final ExpectedException thrown = ExpectedException.none(); @Test - public void instanceOf() { - Assert.isInstanceOf(HashSet.class, new HashSet()); - } - - @Test(expected = IllegalArgumentException.class) - public void instanceOfWithTypeMismatch() { - Assert.isInstanceOf(HashMap.class, new HashSet()); + public void isTrueWithMessage() { + Assert.isTrue(true, "enigma"); } @Test - public void instanceOfNoMessage() throws Exception { + public void isTrueWithFalse() { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Object of class [java.lang.Object] must be an instance " + - "of interface java.util.Set"); - Assert.isInstanceOf(Set.class, new Object(), null); + thrown.expectMessage("enigma"); + Assert.isTrue(false, "enigma"); } @Test - public void instanceOfMessage() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Custom message. Object of class [java.lang.Object] must " + - "be an instance of interface java.util.Set"); - Assert.isInstanceOf(Set.class, new Object(), "Custom message."); - } - - @Test - public void isNullDoesNotThrowExceptionIfArgumentIsNullWithMessage() { + public void isNullWithMessage() { Assert.isNull(null, "Bla"); } @Test - public void isNullDoesNotThrowExceptionIfArgumentIsNull() { - Assert.isNull(null); - } - - @Test(expected = IllegalArgumentException.class) - public void isNullThrowsExceptionIfArgumentIsNotNull() { - Assert.isNull(new Object()); - } - - @Test(expected = IllegalArgumentException.class) - public void isTrueWithFalseExpressionThrowsException() throws Exception { - Assert.isTrue(false); + public void notNullWithMessage() { + Assert.notNull("foo", "enigma"); } @Test - public void isTrueWithTrueExpressionSunnyDay() throws Exception { - Assert.isTrue(true); - } - - @Test(expected = IllegalArgumentException.class) - public void testHasLengthWithNullStringThrowsException() throws Exception { - Assert.hasLength(null); - } - - @Test(expected = IllegalArgumentException.class) - public void hasLengthWithEmptyStringThrowsException() throws Exception { - Assert.hasLength(""); + public void hasLength() { + Assert.hasLength("I Heart ...", "enigma"); } @Test - public void hasLengthWithWhitespaceOnlyStringDoesNotThrowException() throws Exception { - Assert.hasLength("\t "); + public void hasLengthWithWhitespaceOnly() { + Assert.hasLength("\t ", "enigma"); } @Test - public void hasLengthSunnyDay() throws Exception { - Assert.hasLength("I Heart ..."); + public void hasLengthWithEmptyString() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.hasLength("", "enigma"); } @Test - public void doesNotContainWithNullSearchStringDoesNotThrowException() throws Exception { - Assert.doesNotContain(null, "rod"); + public void hasLengthWithNull() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.hasLength(null, "enigma"); } @Test - public void doesNotContainWithNullSubstringDoesNotThrowException() throws Exception { - Assert.doesNotContain("A cool chick's name is Brod. ", null); + public void hasText() { + Assert.hasText("foo", "enigma"); } @Test - public void doesNotContainWithEmptySubstringDoesNotThrowException() throws Exception { - Assert.doesNotContain("A cool chick's name is Brod. ", ""); - } - - @Test(expected = IllegalArgumentException.class) - public void assertNotEmptyWithNullCollectionThrowsException() throws Exception { - Assert.notEmpty((Collection) null); - } - - @Test(expected = IllegalArgumentException.class) - public void assertNotEmptyWithEmptyCollectionThrowsException() throws Exception { - Assert.notEmpty(new ArrayList()); + public void hasTextWithWhitespaceOnly() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.hasText("\t ", "enigma"); } @Test - public void assertNotEmptyWithCollectionSunnyDay() throws Exception { - List collection = new ArrayList(); - collection.add(""); - Assert.notEmpty(collection); - } - - @Test(expected = IllegalArgumentException.class) - public void assertNotEmptyWithNullMapThrowsException() throws Exception { - Assert.notEmpty((Map) null); - } - - @Test(expected = IllegalArgumentException.class) - public void assertNotEmptyWithEmptyMapThrowsException() throws Exception { - Assert.notEmpty(new HashMap()); + public void hasTextWithEmptyString() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.hasText("", "enigma"); } @Test - public void assertNotEmptyWithMapSunnyDay() throws Exception { - Map map = new HashMap(); - map.put("", ""); - Assert.notEmpty(map); - } - - @Test(expected = IllegalArgumentException.class) - public void isInstanceofClassWithNullInstanceThrowsException() throws Exception { - Assert.isInstanceOf(String.class, null); - } - - @Test(expected = IllegalStateException.class) - public void stateWithFalseExpressionThrowsException() throws Exception { - Assert.state(false); + public void hasTextWithNull() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.hasText(null, "enigma"); } @Test - public void stateWithTrueExpressionSunnyDay() throws Exception { - Assert.state(true); + public void doesNotContainWithNullSearchString() { + Assert.doesNotContain(null, "rod", "enigma"); + } + + @Test + public void doesNotContainWithNullSubstring() { + Assert.doesNotContain("A cool chick's name is Brod.", null, "enigma"); + } + + @Test + public void doesNotContainWithEmptySubstring() { + Assert.doesNotContain("A cool chick's name is Brod.", "", "enigma"); + } + + @Test + public void doesNotContainWithNullSearchStringAndNullSubstring() { + Assert.doesNotContain(null, null, "enigma"); + } + + @Test + public void notEmptyArray() { + 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 noNullElements() { + Assert.noNullElements(new String[] { "1234" }, "enigma"); + } + + @Test + public void noNullElementsWithEmptyArray() { + Assert.noNullElements(new String[] {}, "enigma"); + } + + @Test + public void notEmptyCollection() { + Assert.notEmpty(singletonList("foo"), "enigma"); + } + + @Test + public void notEmptyCollectionWithEmptyCollection() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.notEmpty(emptyList(), "enigma"); + } + + @Test + public void notEmptyCollectionWithNullCollection() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.notEmpty((Collection) null, "enigma"); + } + + @Test + public void notEmptyMap() { + Assert.notEmpty(singletonMap("foo", "bar"), "enigma"); + } + + @Test + public void notEmptyMapWithNullMap() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.notEmpty((Map) null, "enigma"); + } + + @Test + public void notEmptyMapWithEmptyMap() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma"); + Assert.notEmpty(emptyMap(), "enigma"); + } + + @Test + public void isInstanceOf() { + 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", "enigma"); + } + + @Test + public void isInstanceOfWithNullInstance() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma: null"); + Assert.isInstanceOf(String.class, null, "enigma"); + } + + @Test + public void isInstanceOfWithTypeMismatchAndNullMessage() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Object of class [java.lang.Long] must be an instance of class java.lang.String"); + Assert.isInstanceOf(String.class, 42L, (String) null); + } + + @Test + public void isInstanceOfWithTypeMismatchAndCustomMessage() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Custom message: java.lang.Long"); + Assert.isInstanceOf(String.class, 42L, "Custom message"); + } + + @Test + public void isAssignable() { + 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, "enigma"); + } + + @Test + public void isAssignableWithNullSubtype() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma: null"); + Assert.isAssignable(Integer.class, null, "enigma"); + } + + @Test + public void isAssignableWithTypeMismatchAndNullMessage() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("class java.lang.Integer is not assignable to class java.lang.String"); + Assert.isAssignable(String.class, Integer.class, (String) null); + } + + @Test + public void isAssignableWithTypeMismatchAndCustomMessage() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("enigma: class java.lang.Integer"); + Assert.isAssignable(String.class, Integer.class, "enigma"); + } + + @Test + public void state() { + Assert.state(true, "enigma"); + } + + @Test + public void stateWithFalseExpression() { + thrown.expect(IllegalStateException.class); + thrown.expectMessage("enigma"); + Assert.state(false, "enigma"); } } 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 1802678042..206c382b20 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 f7ec295e90..ab75f7b55a 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 eeefe40ffb..1fc99b2128 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 a47b9a103c..f033519e5a 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 600ffda6b5..5de6b4b14e 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 { @@ -770,7 +771,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { // It looks like a constructor reference but is NEW being used as a map key? if (peekToken(TokenKind.RSQUARE)) { // looks like 'NEW]' (so NEW used as map key) - push(new PropertyOrFieldReference(false,newToken.data,toPos(newToken))); + push(new PropertyOrFieldReference(false, newToken.data ,toPos(newToken))); return true; } SpelNodeImpl possiblyQualifiedConstructorName = eatPossiblyQualifiedId(); @@ -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 e0408f10db..9a62df8912 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 6687ec1688..cfa205b267 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-jms/src/main/java/org/springframework/jms/core/JmsMessagingTemplate.java b/spring-jms/src/main/java/org/springframework/jms/core/JmsMessagingTemplate.java index 7a22c041a1..43fcf0eb36 100644 --- a/spring-jms/src/main/java/org/springframework/jms/core/JmsMessagingTemplate.java +++ b/spring-jms/src/main/java/org/springframework/jms/core/JmsMessagingTemplate.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. @@ -73,7 +73,7 @@ public class JmsMessagingTemplate extends AbstractMessagingTemplate * Create a {@code JmsMessagingTemplate} instance with the {@link JmsTemplate} to use. */ public JmsMessagingTemplate(JmsTemplate jmsTemplate) { - Assert.notNull("JmsTemplate must not be null"); + Assert.notNull(jmsTemplate, "JmsTemplate must not be null"); this.jmsTemplate = jmsTemplate; } 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 a09214e90f..3fb594ebb2 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 @@ -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 493f1224b2..0088adb7d8 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 8116540280..814ab49527 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. @@ -487,7 +487,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 eef8f689b2..c19ac1531d 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 4e08188c43..fa1131db1b 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 3c8dd759d2..5267b0ffff 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 aab003e101..8deeb3f4de 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 bedbeb089e..b1c48da346 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. @@ -131,7 +131,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/test/java/org/springframework/messaging/simp/stomp/Reactor2TcpStompClientTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/Reactor2TcpStompClientTests.java index 94bfce4be3..94f4642e81 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/Reactor2TcpStompClientTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/Reactor2TcpStompClientTests.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 Reactor2TcpStompClientTests { 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 Reactor2TcpStompClientTests { 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 62e0407cb6..38fdb93a15 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. @@ -401,7 +401,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { } public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) { - StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); headers.setSessionId(sessionId); headers.setReceipt(receiptId); @@ -413,7 +412,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)); @@ -422,7 +421,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-hibernate5/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java b/spring-orm-hibernate5/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java index 7f3d2e28a7..fafa3f6b78 100644 --- a/spring-orm-hibernate5/src/main/java/org/springframework/orm/hibernate5/SessionFactoryUtils.java +++ b/spring-orm-hibernate5/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 f4401ae298..f56f3586b3 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 c6595279de..4c5b44592d 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 c089b42561..809923b882 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. @@ -122,7 +122,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 7ce47f58c4..2c738767e7 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 @@ -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 ae4e8b8b43..12a58a77d2 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-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. @@ -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 0e95d460b5..1f7d18c23a 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-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. @@ -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 dbcf3852de..89d91f1e62 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 f194c41a45..62a9ad6588 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 2a81efc182..d4b7d3084e 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-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. @@ -26,15 +26,14 @@ 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 - * the specified JCA 1.5 {@link javax.resource.spi.ResourceAdapter}, + * the specified JCA 1.7 {@link javax.resource.spi.ResourceAdapter}, * starting it with a local {@link javax.resource.spi.BootstrapContext} * and exposing it for bean references. It will also stop the ResourceAdapter * on context shutdown. This corresponds to 'non-managed' bootstrap in a - * local environment, according to the JCA 1.5 specification. + * local environment, according to the JCA 1.7 specification. * *

This is essentially an adapter for bean-style bootstrapping of a * JCA ResourceAdapter, allowing the BootstrapContext or its elements @@ -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/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java b/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java index bf982d6e24..3aff0c9221 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/converter/xml/MappingJackson2XmlHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.java index 39eb13ef67..a829385634 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 660044b8e8..05ba9d94a2 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. @@ -180,7 +180,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/web/accept/PathExtensionContentNegotiationStrategy.java b/spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java index 000b637964..04727bd4de 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. @@ -140,15 +140,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 cb274152e4..9b4c91add0 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 595d2908c0..4a7656f18f 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 @@ -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. @@ -40,7 +40,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; @@ -517,7 +516,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 758266b34c..ce07354272 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 @@ -793,7 +793,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/mock/web/test/MockAsyncContext.java b/spring-web/src/test/java/org/springframework/mock/web/test/MockAsyncContext.java index 7fb4f8ec95..a23f44e8ab 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-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. @@ -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 95acca3f91..76bef2ab2a 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-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. @@ -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 09f3700a3c..aa30b5cac1 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 5460207d1b..8822f36a3b 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-2013 the original author or authors. + * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,6 +41,7 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceEditor; import org.springframework.core.io.ResourceLoader; import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.context.support.ServletContextResourceLoader; import org.springframework.web.context.support.StandardServletEnvironment; @@ -78,8 +79,7 @@ import org.springframework.web.context.support.StandardServletEnvironment; * @see #doPost */ @SuppressWarnings("serial") -public abstract class HttpServletBean extends HttpServlet - implements EnvironmentCapable, EnvironmentAware { +public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); @@ -128,7 +128,9 @@ public abstract class HttpServletBean extends HttpServlet bw.setPropertyValues(pvs, true); } catch (BeansException ex) { - logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex); + if (logger.isErrorEnabled()) { + logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex); + } throw ex; } @@ -190,7 +192,7 @@ public abstract class HttpServletBean extends HttpServlet */ @Override public void setEnvironment(Environment environment) { - Assert.isInstanceOf(ConfigurableEnvironment.class, environment); + Assert.isInstanceOf(ConfigurableEnvironment.class, environment, "ConfigurableEnvironment required"); this.environment = (ConfigurableEnvironment) environment; } @@ -231,12 +233,12 @@ public abstract class HttpServletBean extends HttpServlet public ServletConfigPropertyValues(ServletConfig config, Set requiredProperties) throws ServletException { - Set missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ? - new HashSet(requiredProperties) : null; + Set missingProps = (requiredProperties != null && !requiredProperties.isEmpty() ? + new HashSet(requiredProperties) : null); - Enumeration en = config.getInitParameterNames(); - while (en.hasMoreElements()) { - String property = en.nextElement(); + Enumeration paramNames = config.getInitParameterNames(); + while (paramNames.hasMoreElements()) { + String property = paramNames.nextElement(); Object value = config.getInitParameter(property); addPropertyValue(new PropertyValue(property, value)); if (missingProps != null) { @@ -245,7 +247,7 @@ public abstract class HttpServletBean extends HttpServlet } // Fail if we are still missing properties. - if (missingProps != null && missingProps.size() > 0) { + if (!CollectionUtils.isEmpty(missingProps)) { throw new ServletException( "Initialization from ServletConfig for servlet '" + config.getServletName() + "' failed; the following required properties were missing: " + 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 65a8db2611..f471b36aca 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. @@ -681,8 +681,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()); @@ -747,7 +747,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 51bed445cf..16a120cb4f 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 789606dc63..906495956b 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. @@ -96,7 +96,10 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho } DeferredResultAdapter adapter = getAdapterFor(returnValue.getClass()); - Assert.notNull(adapter); + if (adapter == null) { + throw new IllegalStateException( + "Could not find DeferredResultAdapter for return value type: " + returnValue.getClass()); + } DeferredResult result = adapter.adaptToDeferredResult(returnValue); WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer); } @@ -109,7 +112,7 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho @Override public DeferredResult adaptToDeferredResult(Object returnValue) { - Assert.isInstanceOf(DeferredResult.class, returnValue); + Assert.isInstanceOf(DeferredResult.class, returnValue, "DeferredResult expected"); return (DeferredResult) returnValue; } } @@ -122,7 +125,7 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho @Override public DeferredResult adaptToDeferredResult(Object returnValue) { - Assert.isInstanceOf(ListenableFuture.class, returnValue); + Assert.isInstanceOf(ListenableFuture.class, returnValue, "ListenableFuture expected"); final DeferredResult result = new DeferredResult(); ((ListenableFuture) returnValue).addCallback(new ListenableFutureCallback() { @Override @@ -147,7 +150,7 @@ public class DeferredResultMethodReturnValueHandler implements AsyncHandlerMetho @Override public DeferredResult adaptToDeferredResult(Object returnValue) { - Assert.isInstanceOf(CompletionStage.class, returnValue); + Assert.isInstanceOf(CompletionStage.class, returnValue, "CompletionStage expected"); final DeferredResult 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 e3dd91d2ad..b195f353a8 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 e9e302a533..cfc54188d8 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(); @@ -533,18 +533,13 @@ public class MvcUriComponentsBuilder { private static WebApplicationContext getWebApplicationContext() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes == null) { - logger.debug("No request bound to the current thread: is DispatcherSerlvet used?"); + logger.debug("No request bound to the current thread: not in a DispatcherServlet request?"); return null; } HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); - if (request == null) { - logger.debug("Request bound to current thread is not an HttpServletRequest"); - return null; - } - - String attributeName = DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE; - WebApplicationContext wac = (WebApplicationContext) request.getAttribute(attributeName); + WebApplicationContext wac = (WebApplicationContext) + request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (wac == null) { logger.debug("No WebApplicationContext found: not in a DispatcherServlet request?"); return null; 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 a48efb1b9e..0cc38d3613 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -396,7 +396,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter * @param interceptors the interceptors to register */ public void setCallableInterceptors(List interceptors) { - Assert.notNull(interceptors); + Assert.notNull(interceptors, "CallableProcessingInterceptor List must not be null"); this.callableInterceptors = interceptors.toArray(new CallableProcessingInterceptor[interceptors.size()]); } @@ -405,7 +405,7 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter * @param interceptors the interceptors to register */ public void setDeferredResultInterceptors(List 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 264ca73ce8..3224cfa689 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. @@ -63,9 +63,9 @@ public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethod public ResponseBodyEmitterReturnValueHandler(List> messageConverters) { - Assert.notEmpty(messageConverters, "'messageConverters' must not be empty"); + Assert.notEmpty(messageConverters, "HttpMessageConverter List must not be empty"); this.messageConverters = messageConverters; - this.adapterMap = new HashMap, ResponseBodyEmitterAdapter>(3); + this.adapterMap = new HashMap, ResponseBodyEmitterAdapter>(4); this.adapterMap.put(ResponseBodyEmitter.class, new SimpleResponseBodyEmitterAdapter()); } @@ -146,7 +146,10 @@ public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethod ShallowEtagHeaderFilter.disableContentCaching(request); ResponseBodyEmitterAdapter adapter = getAdapterFor(returnValue.getClass()); - Assert.notNull(adapter); + if (adapter == null) { + throw new IllegalStateException( + "Could not find ResponseBodyEmitterAdapter for return value type: " + returnValue.getClass()); + } ResponseBodyEmitter emitter = adapter.adaptToEmitter(returnValue, outputMessage); emitter.extendResponse(outputMessage); @@ -170,7 +173,7 @@ public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethod @Override public ResponseBodyEmitter adaptToEmitter(Object returnValue, ServerHttpResponse response) { - Assert.isInstanceOf(ResponseBodyEmitter.class, returnValue); + Assert.isInstanceOf(ResponseBodyEmitter.class, returnValue, "ResponseBodyEmitter expected"); return (ResponseBodyEmitter) returnValue; } } 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 a3b646125c..cbbd1e62a9 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 367aed8503..f39c12a45b 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 7d1b432fcb..7b7067506f 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-2015 the original author or authors. + * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -214,7 +214,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport @Override public View resolveViewName(String viewName, Locale locale) throws Exception { RequestAttributes attrs = RequestContextHolder.getRequestAttributes(); - Assert.isInstanceOf(ServletRequestAttributes.class, attrs); + Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes"); List 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 73f4fbed2b..6e2d84465b 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. @@ -121,7 +121,7 @@ public class ScriptTemplateView extends AbstractUrlBasedView { * See {@link ScriptTemplateConfigurer#setEngine(ScriptEngine)} documentation. */ public void setEngine(ScriptEngine engine) { - Assert.isInstanceOf(Invocable.class, engine); + Assert.isInstanceOf(Invocable.class, engine, "ScriptEngine must implement Invocable"); this.engine = engine; } 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 44a22bb6ca..3709a5e8ed 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 58c4ef1f49..02b3f9f6dc 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-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. @@ -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,8 @@ 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 +64,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 +109,15 @@ 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 +129,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 +148,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 90a1aac47d..11a03ec00d 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 ce6a3085cf..34147e3893 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 2dd7ff41ac..246f0900be 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.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required"); return ((ServletServerHttpRequest) request).getServletRequest(); } protected final HttpServletResponse getHttpServletResponse(ServerHttpResponse response) { - Assert.isTrue(response instanceof ServletServerHttpResponse); + Assert.isInstanceOf(ServletServerHttpResponse.class, response, "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 cab4e6cf48..3b48a7706d 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-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. @@ -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 1a7dc43f3c..e5c4a10ef3 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-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. @@ -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 5905bf5819..c9f170d598 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 4dec50eee4..4d89acbdba 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-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. @@ -67,7 +67,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();