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

Issue: SPR-15196
This commit is contained in:
Juergen Hoeller 2017-01-30 22:15:53 +01:00
parent 768802fa96
commit 1b2dc3638f
118 changed files with 708 additions and 828 deletions

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -27,6 +27,7 @@ import org.springframework.util.StringUtils;
* Spring AOP {@link ClassFilter} implementation using AspectJ type matching. * Spring AOP {@link ClassFilter} implementation using AspectJ type matching.
* *
* @author Rod Johnson * @author Rod Johnson
* @author Juergen Hoeller
* @since 2.0 * @since 2.0
*/ */
public class TypePatternClassFilter implements ClassFilter { public class TypePatternClassFilter implements ClassFilter {
@ -76,17 +77,21 @@ public class TypePatternClassFilter implements ClassFilter {
* or is recognized as invalid * or is recognized as invalid
*/ */
public void setTypePattern(String typePattern) { public void setTypePattern(String typePattern) {
Assert.notNull(typePattern); Assert.notNull(typePattern, "Type pattern must not be null");
this.typePattern = typePattern; this.typePattern = typePattern;
this.aspectJTypePatternMatcher = this.aspectJTypePatternMatcher =
PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution(). PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution().
parseTypePattern(replaceBooleanOperators(typePattern)); parseTypePattern(replaceBooleanOperators(typePattern));
} }
/**
* Return the AspectJ type pattern to match.
*/
public String getTypePattern() { public String getTypePattern() {
return typePattern; return this.typePattern;
} }
/** /**
* Should the pointcut apply to the given interface or target class? * Should the pointcut apply to the given interface or target class?
* @param clazz candidate target class * @param clazz candidate target class
@ -95,9 +100,7 @@ public class TypePatternClassFilter implements ClassFilter {
*/ */
@Override @Override
public boolean matches(Class<?> clazz) { public boolean matches(Class<?> clazz) {
if (this.aspectJTypePatternMatcher == null) { Assert.state(this.aspectJTypePatternMatcher != null, "No type pattern has been set");
throw new IllegalStateException("No 'typePattern' has been set via ctor/setter.");
}
return this.aspectJTypePatternMatcher.matches(clazz); return this.aspectJTypePatternMatcher.matches(clazz);
} }
@ -108,9 +111,8 @@ public class TypePatternClassFilter implements ClassFilter {
* <p>This method converts back to {@code &&} for the AspectJ pointcut parser. * <p>This method converts back to {@code &&} for the AspectJ pointcut parser.
*/ */
private String replaceBooleanOperators(String pcExpr) { private String replaceBooleanOperators(String pcExpr) {
pcExpr = StringUtils.replace(pcExpr," and "," && "); String result = StringUtils.replace(pcExpr," and "," && ");
pcExpr = StringUtils.replace(pcExpr, " or ", " || "); result = StringUtils.replace(result, " or ", " || ");
pcExpr = StringUtils.replace(pcExpr, " not ", " ! "); return StringUtils.replace(result, " not ", " ! ");
return pcExpr;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -54,7 +54,8 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC
public void setBeanFactory(BeanFactory beanFactory) { public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory); super.setBeanFactory(beanFactory);
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
throw new IllegalStateException("Cannot use AdvisorAutoProxyCreator without a ConfigurableListableBeanFactory"); throw new IllegalArgumentException(
"AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
} }
initBeanFactory((ConfigurableListableBeanFactory) beanFactory); initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -219,7 +219,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
public void setBeanFactory(BeanFactory beanFactory) { public void setBeanFactory(BeanFactory beanFactory) {
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory"); "AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory: " + beanFactory);
} }
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -102,12 +102,12 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas
} }
else if (value instanceof Class) { else if (value instanceof Class) {
Class<?> scopeClass = (Class<?>) value; Class<?> scopeClass = (Class<?>) value;
Assert.isAssignable(Scope.class, scopeClass); Assert.isAssignable(Scope.class, scopeClass, "Invalid scope class");
beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass)); beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass));
} }
else if (value instanceof String) { else if (value instanceof String) {
Class<?> scopeClass = ClassUtils.resolveClassName((String) value, this.beanClassLoader); 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)); beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass));
} }
else { else {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -762,7 +762,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
@Override @Override
public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) { public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
Assert.notNull(requiredType, "Required type must not be null"); 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); this.customEditors.put(requiredType, propertyEditorClass);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -44,14 +44,15 @@ class DefaultCacheInvocationContext<A extends Annotation>
private final CacheInvocationParameter[] allParameters; private final CacheInvocationParameter[] allParameters;
public DefaultCacheInvocationContext(JCacheOperation<A> operation,
Object target, Object[] args) { public DefaultCacheInvocationContext(JCacheOperation<A> operation, Object target, Object[] args) {
this.operation = operation; this.operation = operation;
this.target = target; this.target = target;
this.args = args; this.args = args;
this.allParameters = operation.getAllParameters(args); this.allParameters = operation.getAllParameters(args);
} }
@Override @Override
public JCacheOperation<A> getOperation() { public JCacheOperation<A> getOperation() {
return this.operation; return this.operation;
@ -94,17 +95,19 @@ class DefaultCacheInvocationContext<A extends Annotation>
@Override @Override
public <T> T unwrap(Class<T> cls) { public <T> T unwrap(Class<T> cls) {
throw new IllegalArgumentException("Could not unwrap to '" + cls.getName() + "'"); throw new IllegalArgumentException("Cannot unwrap to " + cls);
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder sb = new StringBuilder("CacheInvocationContext{"); StringBuilder sb = new StringBuilder("CacheInvocationContext{");
sb.append("operation=").append(operation); sb.append("operation=").append(this.operation);
sb.append(", target=").append(target); sb.append(", target=").append(this.target);
sb.append(", args=").append(Arrays.toString(args)); sb.append(", args=").append(Arrays.toString(this.args));
sb.append(", allParameters=").append(Arrays.toString(allParameters)); sb.append(", allParameters=").append(Arrays.toString(this.allParameters));
sb.append('}'); sb.append('}');
return sb.toString(); return sb.toString();
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -66,7 +66,7 @@ public class JCacheAspectSupport extends AbstractCacheInvoker implements Initial
public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) { public void setCacheOperationSource(JCacheOperationSource cacheOperationSource) {
Assert.notNull(cacheOperationSource); Assert.notNull(cacheOperationSource, "JCacheOperationSource must not be null");
this.cacheOperationSource = cacheOperationSource; this.cacheOperationSource = cacheOperationSource;
} }
@ -80,7 +80,7 @@ public class JCacheAspectSupport extends AbstractCacheInvoker implements Initial
public void afterPropertiesSet() { public void afterPropertiesSet() {
Assert.state(getCacheOperationSource() != null, "The 'cacheOperationSource' property is required: " + Assert.state(getCacheOperationSource() != null, "The 'cacheOperationSource' property is required: " +
"If there are no cacheable methods, then don't use a cache aspect."); "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.cacheResultInterceptor = new CacheResultInterceptor(getErrorHandler());
this.cachePutInterceptor = new CachePutInterceptor(getErrorHandler()); this.cachePutInterceptor = new CachePutInterceptor(getErrorHandler());
@ -128,23 +128,23 @@ public class JCacheAspectSupport extends AbstractCacheInvoker implements Initial
BasicOperation operation = context.getOperation(); BasicOperation operation = context.getOperation();
if (operation instanceof CacheResultOperation) { if (operation instanceof CacheResultOperation) {
return cacheResultInterceptor.invoke( return this.cacheResultInterceptor.invoke(
(CacheOperationInvocationContext<CacheResultOperation>) context, adapter); (CacheOperationInvocationContext<CacheResultOperation>) context, adapter);
} }
else if (operation instanceof CachePutOperation) { else if (operation instanceof CachePutOperation) {
return cachePutInterceptor.invoke( return this.cachePutInterceptor.invoke(
(CacheOperationInvocationContext<CachePutOperation>) context, adapter); (CacheOperationInvocationContext<CachePutOperation>) context, adapter);
} }
else if (operation instanceof CacheRemoveOperation) { else if (operation instanceof CacheRemoveOperation) {
return cacheRemoveEntryInterceptor.invoke( return this.cacheRemoveEntryInterceptor.invoke(
(CacheOperationInvocationContext<CacheRemoveOperation>) context, adapter); (CacheOperationInvocationContext<CacheRemoveOperation>) context, adapter);
} }
else if (operation instanceof CacheRemoveAllOperation) { else if (operation instanceof CacheRemoveAllOperation) {
return cacheRemoveAllInterceptor.invoke( return this.cacheRemoveAllInterceptor.invoke(
(CacheOperationInvocationContext<CacheRemoveAllOperation>) context, adapter); (CacheOperationInvocationContext<CacheRemoveAllOperation>) context, adapter);
} }
else { else {
throw new IllegalArgumentException("Could not handle " + operation); throw new IllegalArgumentException("Cannot handle " + operation);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,7 +43,6 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.scheduling.SchedulingException; import org.springframework.scheduling.SchedulingException;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
/** /**
@ -105,6 +104,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe
private static final ThreadLocal<DataSource> configTimeNonTransactionalDataSourceHolder = private static final ThreadLocal<DataSource> configTimeNonTransactionalDataSourceHolder =
new ThreadLocal<>(); new ThreadLocal<>();
/** /**
* Return the ResourceLoader for the currently configured Quartz Scheduler, * Return the ResourceLoader for the currently configured Quartz Scheduler,
* to be used by ResourceLoaderClassLoadHelper. * to be used by ResourceLoaderClassLoadHelper.
@ -210,7 +210,6 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe
* @see #setQuartzProperties * @see #setQuartzProperties
*/ */
public void setSchedulerFactoryClass(Class<? extends SchedulerFactory> schedulerFactoryClass) { public void setSchedulerFactoryClass(Class<? extends SchedulerFactory> schedulerFactoryClass) {
Assert.isAssignable(SchedulerFactory.class, schedulerFactoryClass);
this.schedulerFactoryClass = schedulerFactoryClass; this.schedulerFactoryClass = schedulerFactoryClass;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,8 +30,6 @@ import org.junit.rules.ExpectedException;
import org.springframework.cache.Cache; import org.springframework.cache.Cache;
import org.springframework.cache.jcache.AbstractJCacheTests; import org.springframework.cache.jcache.AbstractJCacheTests;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*; import static org.mockito.BDDMockito.*;
@ -46,7 +44,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests {
@Test @Test
public void resolveSimpleCache() { public void resolveSimpleCache() throws Exception {
DefaultCacheInvocationContext<?> dummyContext = createDummyContext(); DefaultCacheInvocationContext<?> dummyContext = createDummyContext();
CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, "testCache")); CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, "testCache"));
Collection<? extends Cache> caches = adapter.resolveCaches(dummyContext); Collection<? extends Cache> caches = adapter.resolveCaches(dummyContext);
@ -56,7 +54,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests {
} }
@Test @Test
public void resolveUnknownCache() { public void resolveUnknownCache() throws Exception {
DefaultCacheInvocationContext<?> dummyContext = createDummyContext(); DefaultCacheInvocationContext<?> dummyContext = createDummyContext();
CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, null)); CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, null));
@ -66,7 +64,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests {
protected CacheResolver getCacheResolver(CacheInvocationContext<? extends Annotation> context, String cacheName) { protected CacheResolver getCacheResolver(CacheInvocationContext<? extends Annotation> context, String cacheName) {
CacheResolver cacheResolver = mock(CacheResolver.class); CacheResolver cacheResolver = mock(CacheResolver.class);
final javax.cache.Cache cache; javax.cache.Cache cache;
if (cacheName == null) { if (cacheName == null) {
cache = null; cache = null;
} }
@ -78,9 +76,8 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests {
return cacheResolver; return cacheResolver;
} }
protected DefaultCacheInvocationContext<?> createDummyContext() { protected DefaultCacheInvocationContext<?> createDummyContext() throws Exception {
Method method = ReflectionUtils.findMethod(Sample.class, "get", String.class); Method method = Sample.class.getMethod("get", String.class);
Assert.notNull(method);
CacheResult cacheAnnotation = method.getAnnotation(CacheResult.class); CacheResult cacheAnnotation = method.getAnnotation(CacheResult.class);
CacheMethodDetails<CacheResult> methodDetails = CacheMethodDetails<CacheResult> methodDetails =
new DefaultCacheMethodDetails<>(method, cacheAnnotation, "test"); new DefaultCacheMethodDetails<>(method, cacheAnnotation, "test");
@ -93,7 +90,7 @@ public class CacheResolverAdapterTests extends AbstractJCacheTests {
static class Sample { static class Sample {
@CacheResult @CacheResult
private Object get(String id) { public Object get(String id) {
return null; return null;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -145,19 +145,19 @@ public abstract class CacheOperation implements BasicOperation {
private String condition = ""; private String condition = "";
public void setName(String name) { public void setName(String name) {
Assert.hasText(name); Assert.hasText(name, "Name must not be empty");
this.name = name; this.name = name;
} }
public void setCacheName(String cacheName) { public void setCacheName(String cacheName) {
Assert.hasText(cacheName); Assert.hasText(cacheName, "Cache name must not be empty");
this.cacheNames = Collections.singleton(cacheName); this.cacheNames = Collections.singleton(cacheName);
} }
public void setCacheNames(String... cacheNames) { public void setCacheNames(String... cacheNames) {
this.cacheNames = new LinkedHashSet<>(cacheNames.length); this.cacheNames = new LinkedHashSet<>(cacheNames.length);
for (String cacheName : cacheNames) { 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); this.cacheNames.add(cacheName);
} }
} }
@ -167,7 +167,7 @@ public abstract class CacheOperation implements BasicOperation {
} }
public void setKey(String key) { public void setKey(String key) {
Assert.notNull(key); Assert.notNull(key, "Key must not be null");
this.key = key; this.key = key;
} }
@ -188,22 +188,22 @@ public abstract class CacheOperation implements BasicOperation {
} }
public void setKeyGenerator(String keyGenerator) { public void setKeyGenerator(String keyGenerator) {
Assert.notNull(keyGenerator); Assert.notNull(keyGenerator, "KeyGenerator name must not be null");
this.keyGenerator = keyGenerator; this.keyGenerator = keyGenerator;
} }
public void setCacheManager(String cacheManager) { public void setCacheManager(String cacheManager) {
Assert.notNull(cacheManager); Assert.notNull(cacheManager, "CacheManager name must not be null");
this.cacheManager = cacheManager; this.cacheManager = cacheManager;
} }
public void setCacheResolver(String cacheResolver) { public void setCacheResolver(String cacheResolver) {
Assert.notNull(this.cacheManager); Assert.notNull(cacheResolver, "CacheResolver name must not be null");
this.cacheResolver = cacheResolver; this.cacheResolver = cacheResolver;
} }
public void setCondition(String condition) { public void setCondition(String condition) {
Assert.notNull(condition); Assert.notNull(condition, "Condition must not be null");
this.condition = condition; this.condition = condition;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -143,7 +143,7 @@ class ComponentScanAnnotationParser {
switch (filterType) { switch (filterType) {
case ANNOTATION: case ANNOTATION:
Assert.isAssignable(Annotation.class, filterClass, 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") @SuppressWarnings("unchecked")
Class<Annotation> annotationType = (Class<Annotation>) filterClass; Class<Annotation> annotationType = (Class<Annotation>) filterClass;
typeFilters.add(new AnnotationTypeFilter(annotationType)); typeFilters.add(new AnnotationTypeFilter(annotationType));
@ -153,7 +153,7 @@ class ComponentScanAnnotationParser {
break; break;
case CUSTOM: case CUSTOM:
Assert.isAssignable(TypeFilter.class, filterClass, 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); TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
ParserStrategyUtils.invokeAwareMethods( ParserStrategyUtils.invokeAwareMethods(
filter, this.environment, this.resourceLoader, this.registry); filter, this.environment, this.resourceLoader, this.registry);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -39,7 +39,6 @@ import org.springframework.context.Lifecycle;
import org.springframework.context.LifecycleProcessor; import org.springframework.context.LifecycleProcessor;
import org.springframework.context.Phased; import org.springframework.context.Phased;
import org.springframework.context.SmartLifecycle; import org.springframework.context.SmartLifecycle;
import org.springframework.util.Assert;
/** /**
* Default implementation of the {@link LifecycleProcessor} strategy. * Default implementation of the {@link LifecycleProcessor} strategy.
@ -70,7 +69,10 @@ public class DefaultLifecycleProcessor implements LifecycleProcessor, BeanFactor
@Override @Override
public void setBeanFactory(BeanFactory beanFactory) { 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; this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -126,7 +126,7 @@ public class DateTimeFormatterFactory {
* @param style two characters from the set {"S", "M", "L", "F", "-"} * @param style two characters from the set {"S", "M", "L", "F", "-"}
*/ */
public void setStylePattern(String style) { 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.dateStyle = convertStyleCharacter(style.charAt(0));
this.timeStyle = convertStyleCharacter(style.charAt(1)); this.timeStyle = convertStyleCharacter(style.charAt(1));
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -55,7 +55,7 @@ class WebLogicClassLoaderAdapter {
public WebLogicClassLoaderAdapter(ClassLoader classLoader) { public WebLogicClassLoaderAdapter(ClassLoader classLoader) {
Class<?> wlGenericClassLoaderClass = null; Class<?> wlGenericClassLoaderClass;
try { try {
wlGenericClassLoaderClass = classLoader.loadClass(GENERIC_CLASS_LOADER_NAME); wlGenericClassLoaderClass = classLoader.loadClass(GENERIC_CLASS_LOADER_NAME);
this.wlPreProcessorClass = classLoader.loadClass(CLASS_PRE_PROCESSOR_NAME); this.wlPreProcessorClass = classLoader.loadClass(CLASS_PRE_PROCESSOR_NAME);
@ -66,12 +66,14 @@ class WebLogicClassLoaderAdapter {
this.wlGenericClassLoaderConstructor = wlGenericClassLoaderClass.getConstructor( this.wlGenericClassLoaderConstructor = wlGenericClassLoaderClass.getConstructor(
this.getClassFinderMethod.getReturnType(), ClassLoader.class); this.getClassFinderMethod.getReturnType(), ClassLoader.class);
} }
catch (Exception ex) { catch (Throwable ex) {
throw new IllegalStateException( throw new IllegalStateException(
"Could not initialize WebLogic LoadTimeWeaver because WebLogic 10 API classes are not available", ex); "Could not initialize WebLogic LoadTimeWeaver because WebLogic 10 API classes are not available", ex);
} }
Assert.isInstanceOf(wlGenericClassLoaderClass, classLoader, if (!wlGenericClassLoaderClass.isInstance(classLoader)) {
"ClassLoader must be instance of [" + wlGenericClassLoaderClass.getName() + "]"); throw new IllegalArgumentException(
"ClassLoader must be an instance of [" + wlGenericClassLoaderClass.getName() + "]: " + classLoader);
}
this.classLoader = classLoader; this.classLoader = classLoader;
} }
@ -87,7 +89,7 @@ class WebLogicClassLoaderAdapter {
catch (InvocationTargetException ex) { catch (InvocationTargetException ex) {
throw new IllegalStateException("WebLogic addInstanceClassPreProcessor method threw exception", ex.getCause()); 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); throw new IllegalStateException("Could not invoke WebLogic addInstanceClassPreProcessor method", ex);
} }
} }
@ -106,8 +108,9 @@ class WebLogicClassLoaderAdapter {
catch (InvocationTargetException ex) { catch (InvocationTargetException ex) {
throw new IllegalStateException("WebLogic GenericClassLoader constructor failed", ex.getCause()); throw new IllegalStateException("WebLogic GenericClassLoader constructor failed", ex.getCause());
} }
catch (Exception ex) { catch (Throwable ex) {
throw new IllegalStateException("Could not construct WebLogic GenericClassLoader", ex); throw new IllegalStateException("Could not construct WebLogic GenericClassLoader", ex);
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -33,7 +33,7 @@ public class ClassWithComplexConstructor {
@Autowired @Autowired
public ClassWithComplexConstructor(Dependency dependency) { public ClassWithComplexConstructor(Dependency dependency) {
Assert.notNull(dependency); Assert.notNull(dependency, "No Dependency bean injected");
this.dependency = dependency; this.dependency = dependency;
} }
@ -42,7 +42,8 @@ public class ClassWithComplexConstructor {
} }
public void method() { 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(); this.dependency.method();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -1250,7 +1250,7 @@ public class ConfigurationClassPostProcessorTests {
@PostConstruct @PostConstruct
public void validate() { public void validate() {
Assert.notNull(provider); Assert.notNull(provider, "No ServiceBeanProvider injected");
} }
} }
@ -1291,7 +1291,7 @@ public class ConfigurationClassPostProcessorTests {
@PostConstruct @PostConstruct
public void validate() { public void validate() {
Assert.notNull(provider); Assert.notNull(provider, "No ServiceBeanProvider injected");
} }
} }
@ -1403,7 +1403,7 @@ public class ConfigurationClassPostProcessorTests {
static class DependingFoo { static class DependingFoo {
DependingFoo(BarArgument bar) { DependingFoo(BarArgument bar) {
Assert.notNull(bar); Assert.notNull(bar, "No BarArgument injected");
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -72,7 +72,8 @@ public class Service implements ApplicationContextAware, MessageSourceAware, Dis
Thread thread = new Thread() { Thread thread = new Thread() {
@Override @Override
public void run() { public void run() {
Assert.isTrue(applicationContext.getBean("messageSource") instanceof StaticMessageSource); Assert.state(applicationContext.getBean("messageSource") instanceof StaticMessageSource,
"Invalid MessageSource bean");
try { try {
applicationContext.getBean("service2"); applicationContext.getBean("service2");
// Should have thrown BeanCreationNotAllowedException // Should have thrown BeanCreationNotAllowedException

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -355,6 +355,7 @@ public class DateTimeFormattingTests {
} }
@Test @Test
@SuppressWarnings("deprecation")
public void testBindInstantFromJavaUtilDate() throws Exception { public void testBindInstantFromJavaUtilDate() throws Exception {
MutablePropertyValues propertyValues = new MutablePropertyValues(); MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("instant", new Date(109, 9, 31, 12, 0)); propertyValues.add("instant", new Date(109, 9, 31, 12, 0));

View File

@ -240,7 +240,7 @@ public class SpringValidatorAdapterTests {
else { else {
context.disableDefaultConstraintViolation(); context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message) context.buildConstraintViolationWithTemplate(message)
.addNode(field) .addPropertyNode(field)
.addConstraintViolation(); .addConstraintViolation();
return false; return false;
} }

View File

@ -59,7 +59,7 @@ public class Constants {
* @throws IllegalArgumentException if the supplied {@code clazz} is {@code null} * @throws IllegalArgumentException if the supplied {@code clazz} is {@code null}
*/ */
public Constants(Class<?> clazz) { public Constants(Class<?> clazz) {
Assert.notNull(clazz); Assert.notNull(clazz, "Class must not be null");
this.className = clazz.getName(); this.className = clazz.getName();
Field[] fields = clazz.getFields(); Field[] fields = clazz.getFields();
for (Field field : fields) { for (Field field : fields) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,9 +47,9 @@ public abstract class ParameterizedTypeReference<T> {
protected ParameterizedTypeReference() { protected ParameterizedTypeReference() {
Class<?> parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(getClass()); Class<?> parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(getClass());
Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass(); Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass();
Assert.isInstanceOf(ParameterizedType.class, type); Assert.isInstanceOf(ParameterizedType.class, type, "Type must be a parameterized type");
ParameterizedType parameterizedType = (ParameterizedType) 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]; this.type = parameterizedType.getActualTypeArguments()[0];
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -408,7 +408,10 @@ abstract class SerializableTypeWrapper {
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
inputStream.defaultReadObject(); inputStream.defaultReadObject();
this.method = ReflectionUtils.findMethod(this.declaringClass, this.methodName); 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);
}
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -23,15 +23,15 @@ import java.util.List;
import joptsimple.OptionSet; import joptsimple.OptionSet;
import joptsimple.OptionSpec; import joptsimple.OptionSpec;
import org.springframework.util.Assert;
/** /**
* {@link CommandLinePropertySource} implementation backed by a JOpt {@link OptionSet}. * {@link CommandLinePropertySource} implementation backed by a JOpt {@link OptionSet}.
* *
* <h2>Typical usage</h2> * <h2>Typical usage</h2>
*
* Configure and execute an {@code OptionParser} against the {@code String[]} of arguments * Configure and execute an {@code OptionParser} against the {@code String[]} of arguments
* supplied to the {@code main} method, and create a {@link JOptCommandLinePropertySource} * supplied to the {@code main} method, and create a {@link JOptCommandLinePropertySource}
* using the resulting {@code OptionSet} object: * using the resulting {@code OptionSet} object:
*
* <pre class="code"> * <pre class="code">
* public static void main(String[] args) { * public static void main(String[] args) {
* OptionParser parser = new OptionParser(); * OptionParser parser = new OptionParser();
@ -44,7 +44,7 @@ import org.springframework.util.Assert;
* *
* See {@link CommandLinePropertySource} for complete general usage examples. * See {@link CommandLinePropertySource} for complete general usage examples.
* *
* <p>Requires JOpt version 4.3 or higher. Tested against JOpt up until 4.6. * <p>Requires JOpt Simple version 4.3 or higher. Tested against JOpt up until 5.0.
* *
* @author Chris Beams * @author Chris Beams
* @author Juergen Hoeller * @author Juergen Hoeller
@ -98,7 +98,7 @@ public class JOptCommandLinePropertySource extends CommandLinePropertySource<Opt
List<?> argValues = this.source.valuesOf(name); List<?> argValues = this.source.valuesOf(name);
List<String> stringArgValues = new ArrayList<>(); List<String> stringArgValues = new ArrayList<>();
for (Object argValue : argValues) { for (Object argValue : argValues) {
stringArgValues.add(argValue instanceof String ? (String) argValue : argValue.toString()); stringArgValues.add(argValue.toString());
} }
if (stringArgValues.isEmpty()) { if (stringArgValues.isEmpty()) {
return (this.source.has(name) ? Collections.emptyList() : null); return (this.source.has(name) ? Collections.emptyList() : null);
@ -111,8 +111,7 @@ public class JOptCommandLinePropertySource extends CommandLinePropertySource<Opt
List<?> argValues = this.source.nonOptionArguments(); List<?> argValues = this.source.nonOptionArguments();
List<String> stringArgValues = new ArrayList<>(); List<String> stringArgValues = new ArrayList<>();
for (Object argValue : argValues) { for (Object argValue : argValues) {
Assert.isInstanceOf(String.class, argValue, "Argument values must be of type String"); stringArgValues.add(argValue.toString());
stringArgValues.add((String) argValue);
} }
return (stringArgValues.isEmpty() ? Collections.emptyList() : return (stringArgValues.isEmpty() ? Collections.emptyList() :
Collections.unmodifiableList(stringArgValues)); Collections.unmodifiableList(stringArgValues));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,9 +49,9 @@ import java.util.function.Supplier;
* *
* @author Keith Donald * @author Keith Donald
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Sam Brannen
* @author Colin Sampaleanu * @author Colin Sampaleanu
* @author Rob Harrop * @author Rob Harrop
* @author Sam Brannen
* @since 1.1.2 * @since 1.1.2
*/ */
public abstract class Assert { public abstract class Assert {
@ -66,6 +66,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if {@code expression} is {@code false} * @throws IllegalArgumentException if {@code expression} is {@code false}
* @since 5.0
*/ */
public static void isTrue(boolean expression, Supplier<String> messageSupplier) { public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
if (!expression) { if (!expression) {
@ -87,17 +88,6 @@ public abstract class Assert {
} }
} }
/**
* Assert a boolean expression, throwing an {@code IllegalArgumentException}
* if the expression evaluates to {@code false}.
* <pre class="code">Assert.isTrue(i &gt; 0);</pre>
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is {@code false}
*/
public static void isTrue(boolean expression) {
isTrue(expression, "[Assertion failed] - this expression must be true");
}
/** /**
* Assert that an object is {@code null}. * Assert that an object is {@code null}.
* <pre class="code"> * <pre class="code">
@ -107,6 +97,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if the object is not {@code null} * @throws IllegalArgumentException if the object is not {@code null}
* @since 5.0
*/ */
public static void isNull(Object object, Supplier<String> messageSupplier) { public static void isNull(Object object, Supplier<String> messageSupplier) {
if (object != null) { if (object != null) {
@ -127,16 +118,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that an object is {@code null}.
* <pre class="code">Assert.isNull(value);</pre>
* @param object the object to check
* @throws IllegalArgumentException if the object is not {@code null}
*/
public static void isNull(Object object) {
isNull(object, "[Assertion failed] - the object argument must be null");
}
/** /**
* Assert that an object is not {@code null}. * Assert that an object is not {@code null}.
* <pre class="code"> * <pre class="code">
@ -146,6 +127,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if the object is {@code null} * @throws IllegalArgumentException if the object is {@code null}
* @since 5.0
*/ */
public static void notNull(Object object, Supplier<String> messageSupplier) { public static void notNull(Object object, Supplier<String> messageSupplier) {
if (object == null) { if (object == null) {
@ -166,16 +148,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that an object is not {@code null}.
* <pre class="code">Assert.notNull(clazz);</pre>
* @param object the object to check
* @throws IllegalArgumentException if the object is {@code null}
*/
public static void notNull(Object object) {
notNull(object, "[Assertion failed] - this argument is required; it must not be null");
}
/** /**
* Assert that the given String is not empty; that is, * Assert that the given String is not empty; that is,
* it must not be {@code null} and not the empty String. * it must not be {@code null} and not the empty String.
@ -187,6 +159,7 @@ public abstract class Assert {
* assertion fails * assertion fails
* @see StringUtils#hasLength * @see StringUtils#hasLength
* @throws IllegalArgumentException if the text is empty * @throws IllegalArgumentException if the text is empty
* @since 5.0
*/ */
public static void hasLength(String text, Supplier<String> messageSupplier) { public static void hasLength(String text, Supplier<String> messageSupplier) {
if (!StringUtils.hasLength(text)) { if (!StringUtils.hasLength(text)) {
@ -209,19 +182,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that the given String is not empty; that is,
* it must not be {@code null} and not the empty String.
* <pre class="code">Assert.hasLength(name);</pre>
* @param text the String to check
* @see StringUtils#hasLength
* @throws IllegalArgumentException if the text is empty
*/
public static void hasLength(String text) {
hasLength(text,
"[Assertion failed] - this String argument must have length; it must not be null or empty");
}
/** /**
* Assert that the given String contains valid text content; that is, it must not * 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. * be {@code null} and must contain at least one non-whitespace character.
@ -233,6 +193,7 @@ public abstract class Assert {
* assertion fails * assertion fails
* @see StringUtils#hasText * @see StringUtils#hasText
* @throws IllegalArgumentException if the text does not contain valid text content * @throws IllegalArgumentException if the text does not contain valid text content
* @since 5.0
*/ */
public static void hasText(String text, Supplier<String> messageSupplier) { public static void hasText(String text, Supplier<String> messageSupplier) {
if (!StringUtils.hasText(text)) { if (!StringUtils.hasText(text)) {
@ -255,19 +216,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that the given String contains valid text content; that is, it must not
* be {@code null} and must contain at least one non-whitespace character.
* <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
* @param text the String to check
* @see StringUtils#hasText
* @throws IllegalArgumentException if the text does not contain valid text content
*/
public static void hasText(String text) {
hasText(text,
"[Assertion failed] - this String argument must have text; it must not be null, empty, or blank");
}
/** /**
* Assert that the given text does not contain the given substring. * Assert that the given text does not contain the given substring.
* <pre class="code"> * <pre class="code">
@ -278,6 +226,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if the text contains the substring * @throws IllegalArgumentException if the text contains the substring
* @since 5.0
*/ */
public static void doesNotContain(String textToSearch, String substring, Supplier<String> messageSupplier) { public static void doesNotContain(String textToSearch, String substring, Supplier<String> messageSupplier) {
if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) &&
@ -301,18 +250,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that the given text does not contain the given substring.
* <pre class="code">Assert.doesNotContain(name, "rod");</pre>
* @param textToSearch the text to search
* @param substring the substring to find within the text
* @throws IllegalArgumentException if the text contains the substring
*/
public static void doesNotContain(String textToSearch, String substring) {
doesNotContain(textToSearch, substring,
() -> "[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
}
/** /**
* Assert that an array contains elements; that is, it must not be * Assert that an array contains elements; that is, it must not be
* {@code null} and must contain at least one element. * {@code null} and must contain at least one element.
@ -323,6 +260,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if the object array is {@code null} or contains no elements * @throws IllegalArgumentException if the object array is {@code null} or contains no elements
* @since 5.0
*/ */
public static void notEmpty(Object[] array, Supplier<String> messageSupplier) { public static void notEmpty(Object[] array, Supplier<String> messageSupplier) {
if (ObjectUtils.isEmpty(array)) { if (ObjectUtils.isEmpty(array)) {
@ -344,18 +282,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that an array contains elements; that is, it must not be
* {@code null} and must contain at least one element.
* <pre class="code">Assert.notEmpty(array);</pre>
* @param array the array to check
* @throws IllegalArgumentException if the object array is {@code null} or
* contains no elements
*/
public static void notEmpty(Object[] array) {
notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element");
}
/** /**
* Assert that an array contains no {@code null} elements. * Assert that an array contains no {@code null} elements.
* <p>Note: Does not complain if the array is empty! * <p>Note: Does not complain if the array is empty!
@ -366,6 +292,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if the object array contains a {@code null} element * @throws IllegalArgumentException if the object array contains a {@code null} element
* @since 5.0
*/ */
public static void noNullElements(Object[] array, Supplier<String> messageSupplier) { public static void noNullElements(Object[] array, Supplier<String> messageSupplier) {
if (array != null) { if (array != null) {
@ -395,17 +322,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that an array contains no {@code null} elements.
* <p>Note: Does not complain if the array is empty!
* <pre class="code">Assert.noNullElements(array);</pre>
* @param array the array to check
* @throws IllegalArgumentException if the object array contains a {@code null} element
*/
public static void noNullElements(Object[] array) {
noNullElements(array, "[Assertion failed] - this array must not contain any null elements");
}
/** /**
* Assert that a collection contains elements; that is, it must not be * Assert that a collection contains elements; that is, it must not be
* {@code null} and must contain at least one element. * {@code null} and must contain at least one element.
@ -417,6 +333,7 @@ public abstract class Assert {
* assertion fails * assertion fails
* @throws IllegalArgumentException if the collection is {@code null} or * @throws IllegalArgumentException if the collection is {@code null} or
* contains no elements * contains no elements
* @since 5.0
*/ */
public static void notEmpty(Collection<?> collection, Supplier<String> messageSupplier) { public static void notEmpty(Collection<?> collection, Supplier<String> messageSupplier) {
if (CollectionUtils.isEmpty(collection)) { if (CollectionUtils.isEmpty(collection)) {
@ -439,19 +356,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that a collection contains elements; that is, it must not be
* {@code null} and must contain at least one element.
* <pre class="code">Assert.notEmpty(collection, "Collection must contain elements");</pre>
* @param collection the collection to check
* @throws IllegalArgumentException if the collection is {@code null} or
* contains no elements
*/
public static void notEmpty(Collection<?> collection) {
notEmpty(collection,
"[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
}
/** /**
* Assert that a Map contains entries; that is, it must not be {@code null} * Assert that a Map contains entries; that is, it must not be {@code null}
* and must contain at least one entry. * and must contain at least one entry.
@ -462,6 +366,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalArgumentException if the map is {@code null} or contains no entries * @throws IllegalArgumentException if the map is {@code null} or contains no entries
* @since 5.0
*/ */
public static void notEmpty(Map<?, ?> map, Supplier<String> messageSupplier) { public static void notEmpty(Map<?, ?> map, Supplier<String> messageSupplier) {
if (CollectionUtils.isEmpty(map)) { if (CollectionUtils.isEmpty(map)) {
@ -483,29 +388,6 @@ public abstract class Assert {
} }
} }
/**
* Assert that a Map contains entries; that is, it must not be {@code null}
* and must contain at least one entry.
* <pre class="code">Assert.notEmpty(map);</pre>
* @param map the map to check
* @throws IllegalArgumentException if the map is {@code null} or contains no entries
*/
public static void notEmpty(Map<?, ?> map) {
notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry");
}
/**
* Assert that the provided object is an instance of the provided class.
* <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
* @param type the type to check against
* @param obj the object to check
* @throws IllegalArgumentException if the object is not an instance of type
* @see Class#isInstance
*/
public static void isInstanceOf(Class<?> type, Object obj) {
isInstanceOf(type, obj, "");
}
/** /**
* Assert that the provided object is an instance of the provided class. * Assert that the provided object is an instance of the provided class.
* <pre class="code"> * <pre class="code">
@ -519,11 +401,12 @@ public abstract class Assert {
* in ":" or "." so that the generated message looks OK when appended to it. * in ":" or "." so that the generated message looks OK when appended to it.
* @throws IllegalArgumentException if the object is not an instance of type * @throws IllegalArgumentException if the object is not an instance of type
* @see Class#isInstance * @see Class#isInstance
* @since 5.0
*/ */
public static void isInstanceOf(Class<?> type, Object obj, Supplier<String> messageSupplier) { public static void isInstanceOf(Class<?> type, Object obj, Supplier<String> messageSupplier) {
notNull(type, "Type to check against must not be null"); notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) { if (!type.isInstance(obj)) {
isInstanceCheckFailed(type, obj, nullSafeGet(messageSupplier)); instanceCheckFailed(type, obj, nullSafeGet(messageSupplier));
} }
} }
@ -541,26 +424,26 @@ public abstract class Assert {
public static void isInstanceOf(Class<?> type, Object obj, String message) { public static void isInstanceOf(Class<?> type, Object obj, String message) {
notNull(type, "Type to check against must not be null"); notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) { if (!type.isInstance(obj)) {
isInstanceCheckFailed(type, obj, message); instanceCheckFailed(type, obj, message);
} }
} }
private static void isInstanceCheckFailed(Class<?> type, Object obj, String message) { /**
throw new IllegalArgumentException( * Assert that the provided object is an instance of the provided class.
(StringUtils.hasLength(message) ? message + " " : "") + * <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
"Object of class [" + (obj != null ? obj.getClass().getName() : "null") + * @param type the type to check against
"] must be an instance of " + type); * @param obj the object to check
* @throws IllegalArgumentException if the object is not an instance of type
* @see Class#isInstance
*/
public static void isInstanceOf(Class<?> type, Object obj) {
isInstanceOf(type, obj, "");
} }
/** private static void instanceCheckFailed(Class<?> type, Object obj, String message) {
* Assert that {@code superType.isAssignableFrom(subType)} is {@code true}. String className = (obj != null ? obj.getClass().getName() : "null");
* <pre class="code">Assert.isAssignable(Number.class, myClass);</pre> throw new IllegalArgumentException(StringUtils.hasLength(message) ? message + ": " + className :
* @param superType the super type to check "Object of class [" + className + "] must be an instance of " + type);
* @param subType the sub type to check
* @throws IllegalArgumentException if the classes are not assignable
*/
public static void isAssignable(Class<?> superType, Class<?> subType) {
isAssignable(superType, subType, "");
} }
/** /**
@ -575,11 +458,12 @@ public abstract class Assert {
* by this method in order to provide further context. It should normally end * 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. * in ":" or "." so that the generated message looks OK when appended to it.
* @throws IllegalArgumentException if the classes are not assignable * @throws IllegalArgumentException if the classes are not assignable
* @since 5.0
*/ */
public static void isAssignable(Class<?> superType, Class<?> subType, Supplier<String> messageSupplier) { public static void isAssignable(Class<?> superType, Class<?> subType, Supplier<String> messageSupplier) {
notNull(superType, "Super type to check against must not be null"); notNull(superType, "Super type to check against must not be null");
if (subType == null || !superType.isAssignableFrom(subType)) { if (subType == null || !superType.isAssignableFrom(subType)) {
isAssignableCheckFailed(superType, subType, nullSafeGet(messageSupplier)); assignableCheckFailed(superType, subType, nullSafeGet(messageSupplier));
} }
} }
@ -596,12 +480,23 @@ public abstract class Assert {
public static void isAssignable(Class<?> superType, Class<?> subType, String message) { public static void isAssignable(Class<?> superType, Class<?> subType, String message) {
notNull(superType, "Super type to check against must not be null"); notNull(superType, "Super type to check against must not be null");
if (subType == null || !superType.isAssignableFrom(subType)) { if (subType == null || !superType.isAssignableFrom(subType)) {
isAssignableCheckFailed(superType, subType, message); assignableCheckFailed(superType, subType, message);
} }
} }
private static void isAssignableCheckFailed(Class<?> superType, Class<?> subType, String message) { /**
throw new IllegalArgumentException((StringUtils.hasLength(message) ? message + " " : "") + * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}.
* <pre class="code">Assert.isAssignable(Number.class, myClass);</pre>
* @param superType the super type to check
* @param subType the sub type to check
* @throws IllegalArgumentException if the classes are not assignable
*/
public static void isAssignable(Class<?> superType, Class<?> subType) {
isAssignable(superType, subType, "");
}
private static void assignableCheckFailed(Class<?> superType, Class<?> subType, String message) {
throw new IllegalArgumentException(StringUtils.hasLength(message) ? message + ": " + subType :
subType + " is not assignable to " + superType); subType + " is not assignable to " + superType);
} }
@ -618,6 +513,7 @@ public abstract class Assert {
* @param messageSupplier a supplier for the exception message to use if the * @param messageSupplier a supplier for the exception message to use if the
* assertion fails * assertion fails
* @throws IllegalStateException if {@code expression} is {@code false} * @throws IllegalStateException if {@code expression} is {@code false}
* @since 5.0
*/ */
public static void state(boolean expression, Supplier<String> messageSupplier) { public static void state(boolean expression, Supplier<String> messageSupplier) {
if (!expression) { if (!expression) {
@ -641,19 +537,6 @@ public abstract class Assert {
} }
} }
/**
* Assert a boolean expression, throwing an {@link IllegalStateException}
* if the expression evaluates to {@code false}.
* <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
* on an assertion failure.
* <pre class="code">Assert.state(id == null);</pre>
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is {@code false}
*/
public static void state(boolean expression) {
state(expression, "[Assertion failed] - this state invariant must be true");
}
private static String nullSafeGet(Supplier<String> messageSupplier) { private static String nullSafeGet(Supplier<String> messageSupplier) {
return (messageSupplier != null ? messageSupplier.get() : null); return (messageSupplier != null ? messageSupplier.get() : null);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -903,7 +903,7 @@ public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V> implemen
@Override @Override
public void remove() { public void remove() {
Assert.state(this.last != null); Assert.state(this.last != null, "No element to remove");
ConcurrentReferenceHashMap.this.remove(this.last.getKey()); ConcurrentReferenceHashMap.this.remove(this.last.getKey());
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,6 +35,7 @@ import static org.hamcrest.CoreMatchers.*;
* @author Rick Evans * @author Rick Evans
* @author Arjen Poutsma * @author Arjen Poutsma
* @author Sam Brannen * @author Sam Brannen
* @author Juergen Hoeller
*/ */
public class AssertTests { public class AssertTests {
@ -43,14 +44,15 @@ public class AssertTests {
@Test @Test
public void isTrue() { public void isTrueWithMessage() {
Assert.isTrue(true); Assert.isTrue(true, "enigma");
} }
@Test @Test
public void isTrueWithFalseExpression() { public void isTrueWithFalse() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.isTrue(false); thrown.expectMessage("enigma");
Assert.isTrue(false, "enigma");
} }
@Test @Test
@ -72,22 +74,11 @@ public class AssertTests {
Assert.isTrue(false, (Supplier<String>) null); Assert.isTrue(false, (Supplier<String>) null);
} }
@Test
public void isNull() {
Assert.isNull(null);
}
@Test @Test
public void isNullWithMessage() { public void isNullWithMessage() {
Assert.isNull(null, "Bla"); Assert.isNull(null, "Bla");
} }
@Test
public void isNullWithNonNullObject() {
thrown.expect(IllegalArgumentException.class);
Assert.isNull(new Object());
}
@Test @Test
public void isNullWithMessageSupplier() { public void isNullWithMessageSupplier() {
Assert.isNull(null, () -> "enigma"); Assert.isNull(null, () -> "enigma");
@ -108,8 +99,8 @@ public class AssertTests {
} }
@Test @Test
public void notNull() { public void notNullWithMessage() {
Assert.notNull("foo"); Assert.notNull("foo", "enigma");
} }
@Test @Test
@ -133,24 +124,26 @@ public class AssertTests {
@Test @Test
public void hasLength() { public void hasLength() {
Assert.hasLength("I Heart ..."); Assert.hasLength("I Heart ...", "enigma");
} }
@Test @Test
public void hasLengthWithWhitespaceOnly() { public void hasLengthWithWhitespaceOnly() {
Assert.hasLength("\t "); Assert.hasLength("\t ", "enigma");
} }
@Test @Test
public void hasLengthWithEmptyString() { public void hasLengthWithEmptyString() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.hasLength(""); thrown.expectMessage("enigma");
Assert.hasLength("", "enigma");
} }
@Test @Test
public void hasLengthWithNull() { public void hasLengthWithNull() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.hasLength(null); thrown.expectMessage("enigma");
Assert.hasLength(null, "enigma");
} }
@Test @Test
@ -186,7 +179,7 @@ public class AssertTests {
@Test @Test
public void hasText() { public void hasText() {
Assert.hasText("foo"); Assert.hasText("foo", "enigma");
} }
@Test @Test
@ -204,7 +197,7 @@ public class AssertTests {
} }
@Test @Test
public void hasTextWithNullAndMessage() { public void hasTextWithNull() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma"); thrown.expectMessage("enigma");
Assert.hasText(null, "enigma"); Assert.hasText(null, "enigma");
@ -245,21 +238,21 @@ public class AssertTests {
@Test @Test
public void doesNotContainWithNullSearchString() { public void doesNotContainWithNullSearchString() {
Assert.doesNotContain(null, "rod"); Assert.doesNotContain(null, "rod", "enigma");
} }
@Test @Test
public void doesNotContainWithNullSubstring() { public void doesNotContainWithNullSubstring() {
Assert.doesNotContain("A cool chick's name is Brod.", null); Assert.doesNotContain("A cool chick's name is Brod.", null, "enigma");
} }
@Test @Test
public void doesNotContainWithEmptySubstring() { public void doesNotContainWithEmptySubstring() {
Assert.doesNotContain("A cool chick's name is Brod.", ""); Assert.doesNotContain("A cool chick's name is Brod.", "", "enigma");
} }
@Test @Test
public void doesNotContainWithNullSearchStringAndNullSubstringAndMessage() { public void doesNotContainWithNullSearchStringAndNullSubstring() {
Assert.doesNotContain(null, null, "enigma"); Assert.doesNotContain(null, null, "enigma");
} }
@ -299,12 +292,26 @@ public class AssertTests {
@Test @Test
public void notEmptyArray() { public void notEmptyArray() {
Assert.notEmpty(new String[] { "1234" }); Assert.notEmpty(new String[] {"1234"}, "enigma");
}
@Test
public void notEmptyArrayWithEmptyArray() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma");
Assert.notEmpty(new String[] {}, "enigma");
}
@Test
public void notEmptyArrayWithNullArray() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma");
Assert.notEmpty((Object[]) null, "enigma");
} }
@Test @Test
public void notEmptyArrayWithMessageSupplier() { public void notEmptyArrayWithMessageSupplier() {
Assert.notEmpty(new String[] { "1234" }, () -> "enigma"); Assert.notEmpty(new String[] {"1234"}, () -> "enigma");
} }
@Test @Test
@ -369,19 +376,21 @@ public class AssertTests {
@Test @Test
public void notEmptyCollection() { public void notEmptyCollection() {
Assert.notEmpty(singletonList("foo")); Assert.notEmpty(singletonList("foo"), "enigma");
} }
@Test @Test
public void notEmptyCollectionWithEmptyCollection() { public void notEmptyCollectionWithEmptyCollection() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.notEmpty(emptyList()); thrown.expectMessage("enigma");
Assert.notEmpty(emptyList(), "enigma");
} }
@Test @Test
public void notEmptyCollectionWithNullCollection() { public void notEmptyCollectionWithNullCollection() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.notEmpty((Collection<?>) null); thrown.expectMessage("enigma");
Assert.notEmpty((Collection<?>) null, "enigma");
} }
@Test @Test
@ -412,19 +421,21 @@ public class AssertTests {
@Test @Test
public void notEmptyMap() { public void notEmptyMap() {
Assert.notEmpty(singletonMap("foo", "bar")); Assert.notEmpty(singletonMap("foo", "bar"), "enigma");
} }
@Test @Test
public void notEmptyMapWithNullMap() { public void notEmptyMapWithNullMap() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.notEmpty((Map<?, ?>) null); thrown.expectMessage("enigma");
Assert.notEmpty((Map<?, ?>) null, "enigma");
} }
@Test @Test
public void notEmptyMapWithEmptyMap() { public void notEmptyMapWithEmptyMap() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
Assert.notEmpty(emptyMap()); thrown.expectMessage("enigma");
Assert.notEmpty(emptyMap(), "enigma");
} }
@Test @Test
@ -455,21 +466,21 @@ public class AssertTests {
@Test @Test
public void isInstanceOf() { public void isInstanceOf() {
Assert.isInstanceOf(String.class, "foo"); Assert.isInstanceOf(String.class, "foo", "enigma");
} }
@Test @Test
public void isInstanceOfWithNullType() { public void isInstanceOfWithNullType() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Type to check against must not be null"); thrown.expectMessage("Type to check against must not be null");
Assert.isInstanceOf(null, "foo"); Assert.isInstanceOf(null, "foo", "enigma");
} }
@Test @Test
public void isInstanceOfWithNullInstance() { public void isInstanceOfWithNullInstance() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Object of class [null] must be an instance of class java.lang.String"); thrown.expectMessage("enigma: null");
Assert.isInstanceOf(String.class, null); Assert.isInstanceOf(String.class, null, "enigma");
} }
@Test @Test
@ -482,9 +493,8 @@ public class AssertTests {
@Test @Test
public void isInstanceOfWithTypeMismatchAndCustomMessage() { public void isInstanceOfWithTypeMismatchAndCustomMessage() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage( thrown.expectMessage("Custom message: java.lang.Long");
"Custom message. Object of class [java.lang.Long] must be an instance of class java.lang.String"); Assert.isInstanceOf(String.class, 42L, "Custom message");
Assert.isInstanceOf(String.class, 42L, "Custom message.");
} }
@Test @Test
@ -502,8 +512,8 @@ public class AssertTests {
@Test @Test
public void isInstanceOfWithNullInstanceAndMessageSupplier() { public void isInstanceOfWithNullInstanceAndMessageSupplier() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma: Object of class [null] must be an instance of class java.lang.String"); thrown.expectMessage("enigma: null");
Assert.isInstanceOf(String.class, null, () -> "enigma:"); Assert.isInstanceOf(String.class, null, () -> "enigma");
} }
@Test @Test
@ -516,27 +526,27 @@ public class AssertTests {
@Test @Test
public void isInstanceOfWithTypeMismatchAndMessageSupplier() { public void isInstanceOfWithTypeMismatchAndMessageSupplier() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma: Object of class [java.lang.Long] must be an instance of class java.lang.String"); thrown.expectMessage("enigma: java.lang.Long");
Assert.isInstanceOf(String.class, 42L, () -> "enigma:"); Assert.isInstanceOf(String.class, 42L, () -> "enigma");
} }
@Test @Test
public void isAssignable() { public void isAssignable() {
Assert.isAssignable(Number.class, Integer.class); Assert.isAssignable(Number.class, Integer.class, "enigma");
} }
@Test @Test
public void isAssignableWithNullSupertype() { public void isAssignableWithNullSupertype() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Super type to check against must not be null"); thrown.expectMessage("Super type to check against must not be null");
Assert.isAssignable(null, Integer.class); Assert.isAssignable(null, Integer.class, "enigma");
} }
@Test @Test
public void isAssignableWithNullSubtype() { public void isAssignableWithNullSubtype() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("null is not assignable to class java.lang.Integer"); thrown.expectMessage("enigma: null");
Assert.isAssignable(Integer.class, null); Assert.isAssignable(Integer.class, null, "enigma");
} }
@Test @Test
@ -549,8 +559,8 @@ public class AssertTests {
@Test @Test
public void isAssignableWithTypeMismatchAndCustomMessage() { public void isAssignableWithTypeMismatchAndCustomMessage() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma: class java.lang.Integer is not assignable to class java.lang.String"); thrown.expectMessage("enigma: class java.lang.Integer");
Assert.isAssignable(String.class, Integer.class, "enigma:"); Assert.isAssignable(String.class, Integer.class, "enigma");
} }
@Test @Test
@ -568,8 +578,8 @@ public class AssertTests {
@Test @Test
public void isAssignableWithNullSubtypeAndMessageSupplier() { public void isAssignableWithNullSubtypeAndMessageSupplier() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma: null is not assignable to class java.lang.Integer"); thrown.expectMessage("enigma: null");
Assert.isAssignable(Integer.class, null, () -> "enigma:"); Assert.isAssignable(Integer.class, null, () -> "enigma");
} }
@Test @Test
@ -582,19 +592,20 @@ public class AssertTests {
@Test @Test
public void isAssignableWithTypeMismatchAndMessageSupplier() { public void isAssignableWithTypeMismatchAndMessageSupplier() {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("enigma: class java.lang.Integer is not assignable to class java.lang.String"); thrown.expectMessage("enigma: class java.lang.Integer");
Assert.isAssignable(String.class, Integer.class, () -> "enigma:"); Assert.isAssignable(String.class, Integer.class, () -> "enigma");
} }
@Test @Test
public void state() { public void state() {
Assert.state(true); Assert.state(true, "enigma");
} }
@Test @Test
public void stateWithFalseExpression() { public void stateWithFalseExpression() {
thrown.expect(IllegalStateException.class); thrown.expect(IllegalStateException.class);
Assert.state(false); thrown.expectMessage("enigma");
Assert.state(false, "enigma");
} }
@Test @Test

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,8 +43,8 @@ public class OpDec extends Operator {
public OpDec(int pos, boolean postfix, SpelNodeImpl... operands) { public OpDec(int pos, boolean postfix, SpelNodeImpl... operands) {
super("--", pos, operands); super("--", pos, operands);
Assert.notEmpty(operands);
this.postfix = postfix; this.postfix = postfix;
Assert.notEmpty(operands, "Operands must not be empty");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,8 +43,8 @@ public class OpInc extends Operator {
public OpInc(int pos, boolean postfix, SpelNodeImpl... operands) { public OpInc(int pos, boolean postfix, SpelNodeImpl... operands) {
super("++", pos, operands); super("++", pos, operands);
Assert.notEmpty(operands);
this.postfix = postfix; this.postfix = postfix;
Assert.notEmpty(operands, "Operands must not be empty");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -51,7 +51,7 @@ public class OpPlus extends Operator {
public OpPlus(int pos, SpelNodeImpl... operands) { public OpPlus(int pos, SpelNodeImpl... operands) {
super("+", pos, operands); super("+", pos, operands);
Assert.notEmpty(operands); Assert.notEmpty(operands, "Operands must not be empty");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -51,7 +51,7 @@ public abstract class Operator extends SpelNodeImpl {
protected String rightActualDescriptor; protected String rightActualDescriptor;
public Operator(String payload,int pos,SpelNodeImpl... operands) { public Operator(String payload, int pos, SpelNodeImpl... operands) {
super(pos, operands); super(pos, operands);
this.operatorName = payload; this.operatorName = payload;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -79,6 +79,7 @@ import org.springframework.util.StringUtils;
* Hand written SpEL parser. Instances are reusable but are not thread-safe. * Hand written SpEL parser. Instances are reusable but are not thread-safe.
* *
* @author Andy Clement * @author Andy Clement
* @author Juergen Hoeller
* @author Phillip Webb * @author Phillip Webb
* @since 3.0 * @since 3.0
*/ */
@ -128,7 +129,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
if (moreTokens()) { if (moreTokens()) {
throw new SpelParseException(peekToken().startPos, SpelMessage.MORE_INPUT, toString(nextToken())); 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); return new SpelExpression(expressionString, ast, this.configuration);
} }
catch (InternalParseException ex) { catch (InternalParseException ex) {
@ -232,7 +233,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
if (tk == TokenKind.EQ) { if (tk == TokenKind.EQ) {
return new OpEQ(pos, expr, rhExpr); 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); return new OpNE(pos, expr, rhExpr);
} }
@ -244,7 +245,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return new OperatorMatches(toPos(t), expr, rhExpr); 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 new OperatorBetween(toPos(t), expr, rhExpr);
} }
return expr; return expr;
@ -281,7 +282,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
expr = new OpDivide(toPos(t), expr, rhExpr); expr = new OpDivide(toPos(t), expr, rhExpr);
} }
else { else {
Assert.isTrue(t.kind == TokenKind.MOD); Assert.isTrue(t.kind == TokenKind.MOD, "Mod token expected");
expr = new OpModulus(toPos(t), expr, rhExpr); expr = new OpModulus(toPos(t), expr, rhExpr);
} }
} }
@ -298,7 +299,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return new OperatorPower(toPos(t), expr, rhExpr); 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 Token t = nextToken(); //consume INC/DEC
if (t.getKind() == TokenKind.INC) { if (t.getKind() == TokenKind.INC) {
return new OpInc(toPos(t), true, expr); return new OpInc(toPos(t), true, expr);
@ -321,7 +322,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
if (t.kind == TokenKind.PLUS) { if (t.kind == TokenKind.PLUS) {
return new OpPlus(toPos(t), expr); 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); return new OpMinus(toPos(t), expr);
} }
@ -356,7 +357,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
// node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+; // node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+;
private boolean maybeEatNode() { private boolean maybeEatNode() {
SpelNodeImpl expr = null; SpelNodeImpl expr = null;
if (peekToken(TokenKind.DOT,TokenKind.SAFE_NAVI)) { if (peekToken(TokenKind.DOT, TokenKind.SAFE_NAVI)) {
expr = eatDottedNode(); expr = eatDottedNode();
} }
else { else {
@ -940,7 +941,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return false; return false;
} }
private boolean peekToken(TokenKind possible1,TokenKind possible2) { private boolean peekToken(TokenKind possible1, TokenKind possible2) {
if (!moreTokens()) { if (!moreTokens()) {
return false; return false;
} }
@ -948,12 +949,12 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return (t.kind == possible1 || t.kind == possible2); 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()) { if (!moreTokens()) {
return false; return false;
} }
Token t = peekToken(); 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) { private boolean peekIdentifierToken(String identifierString) {
@ -961,7 +962,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return false; return false;
} }
Token t = peekToken(); Token t = peekToken();
return t.kind == TokenKind.IDENTIFIER && t.stringValue().equalsIgnoreCase(identifierString); return (t.kind == TokenKind.IDENTIFIER && t.stringValue().equalsIgnoreCase(identifierString));
} }
private boolean peekSelectToken() { private boolean peekSelectToken() {
@ -969,8 +970,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
return false; return false;
} }
Token t = peekToken(); Token t = peekToken();
return t.kind == TokenKind.SELECT || t.kind == TokenKind.SELECT_FIRST return (t.kind == TokenKind.SELECT || t.kind == TokenKind.SELECT_FIRST || t.kind == TokenKind.SELECT_LAST);
|| t.kind == TokenKind.SELECT_LAST;
} }
private boolean moreTokens() { private boolean moreTokens() {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -23,7 +23,6 @@ import java.util.List;
import org.springframework.expression.spel.InternalParseException; import org.springframework.expression.spel.InternalParseException;
import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.SpelMessage;
import org.springframework.expression.spel.SpelParseException; 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. * 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. * Check if this might be a two character token.
*/ */
private boolean isTwoCharToken(TokenKind kind) { private boolean isTwoCharToken(TokenKind kind) {
Assert.isTrue(kind.tokenChars.length == 2); return (kind.tokenChars.length == 2 &&
Assert.isTrue(this.toProcess[this.pos] == kind.tokenChars[0]); this.toProcess[this.pos] == kind.tokenChars[0] &&
return this.toProcess[this.pos + 1] == kind.tokenChars[1]; this.toProcess[this.pos + 1] == kind.tokenChars[1]);
} }
/** /**

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,11 +18,11 @@ package org.springframework.jdbc.core;
/** /**
* Interface to be implemented by objects that can close resources * Interface to be implemented by objects that can close resources
* allocated by parameters like SqlLobValues. * allocated by parameters like {@code SqlLobValue} objects.
* *
* <p>Typically implemented by PreparedStatementCreators and * <p>Typically implemented by {@code PreparedStatementCreators} and
* PreparedStatementSetters that support DisposableSqlTypeValue * {@code PreparedStatementSetters} that support {@link DisposableSqlTypeValue}
* objects (e.g. SqlLobValue) as parameters. * objects (e.g. {@code SqlLobValue}) as parameters.
* *
* @author Thomas Risberg * @author Thomas Risberg
* @author Juergen Hoeller * @author Juergen Hoeller
@ -38,9 +38,9 @@ public interface ParameterDisposer {
* Close the resources allocated by parameters that the implementing * Close the resources allocated by parameters that the implementing
* object holds, for example in case of a DisposableSqlTypeValue * object holds, for example in case of a DisposableSqlTypeValue
* (like a SqlLobValue). * (like a SqlLobValue).
* @see DisposableSqlTypeValue#cleanup * @see DisposableSqlTypeValue#cleanup()
* @see org.springframework.jdbc.core.support.SqlLobValue#cleanup * @see org.springframework.jdbc.core.support.SqlLobValue#cleanup()
*/ */
public void cleanupParameters(); void cleanupParameters();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -94,7 +94,9 @@ public class HandlerMethodReturnValueHandlerComposite implements AsyncHandlerMet
throws Exception { throws Exception {
HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType); 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()) { if (logger.isTraceEnabled()) {
logger.trace("Processing return value with " + handler); logger.trace("Processing return value with " + handler);
} }
@ -104,14 +106,15 @@ public class HandlerMethodReturnValueHandlerComposite implements AsyncHandlerMet
@Override @Override
public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) {
HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType); HandlerMethodReturnValueHandler handler = getReturnValueHandler(returnType);
return (handler != null && handler instanceof AsyncHandlerMethodReturnValueHandler && return (handler instanceof AsyncHandlerMethodReturnValueHandler &&
((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(returnValue, returnType)); ((AsyncHandlerMethodReturnValueHandler) handler).isAsyncReturnValue(returnValue, returnType));
} }
@Override @Override
public ListenableFuture<?> toListenableFuture(Object returnValue, MethodParameter returnType) { public ListenableFuture<?> toListenableFuture(Object returnValue, MethodParameter returnType) {
HandlerMethodReturnValueHandler handler = getReturnValueHandler(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); return ((AsyncHandlerMethodReturnValueHandler) handler).toListenableFuture(returnValue, returnType);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,10 +58,10 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
/** /**
* Create a new {@link SimpMessagingTemplate} instance. * Create a new {@link SimpMessagingTemplate} instance.
* @param messageChannel the message channel (must not be {@code null}) * @param messageChannel the message channel (never {@code null})
*/ */
public SimpMessagingTemplate(MessageChannel messageChannel) { public SimpMessagingTemplate(MessageChannel messageChannel) {
Assert.notNull(messageChannel, "'messageChannel' must not be null"); Assert.notNull(messageChannel, "MessageChannel must not be null");
this.messageChannel = messageChannel; this.messageChannel = messageChannel;
} }
@ -79,8 +79,8 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
* @see org.springframework.messaging.simp.user.UserDestinationMessageHandler * @see org.springframework.messaging.simp.user.UserDestinationMessageHandler
*/ */
public void setUserDestinationPrefix(String prefix) { public void setUserDestinationPrefix(String prefix) {
Assert.hasText(prefix, "'destinationPrefix' must not be empty"); Assert.hasText(prefix, "User destination prefix must not be empty");
this.destinationPrefix = prefix.endsWith("/") ? prefix : prefix + "/"; this.destinationPrefix = (prefix.endsWith("/") ? prefix : prefix + "/");
} }
@ -135,7 +135,7 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
*/ */
@Override @Override
public void send(Message<?> message) { public void send(Message<?> message) {
Assert.notNull(message, "'message' is required"); Assert.notNull(message, "Message is required");
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders()); String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
if (destination != null) { if (destination != null) {
sendInternal(message); sendInternal(message);
@ -178,7 +178,7 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
private void sendInternal(Message<?> message) { private void sendInternal(Message<?> message) {
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders()); String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
Assert.notNull(destination); Assert.notNull(destination, "Destination header required");
long timeout = this.sendTimeout; long timeout = this.sendTimeout;
boolean sent = (timeout >= 0 ? this.messageChannel.send(message, timeout) : this.messageChannel.send(message)); boolean sent = (timeout >= 0 ? this.messageChannel.send(message, timeout) : this.messageChannel.send(message));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -480,7 +480,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination); Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination);
if (!CollectionUtils.isEmpty(vars)) { if (!CollectionUtils.isEmpty(vars)) {
MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class); 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); mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.messaging.simp.broker; package org.springframework.messaging.simp.broker;
import java.security.Principal; import java.security.Principal;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -174,7 +175,9 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
* @since 4.2 * @since 4.2
*/ */
public void setHeartbeatValue(long[] heartbeat) { 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; this.heartbeatValue = heartbeat;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -317,14 +317,14 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC
return new NoOpMessageHandler(); return new NoOpMessageHandler();
} }
SimpUserRegistry userRegistry = userRegistry(); SimpUserRegistry userRegistry = userRegistry();
Assert.isInstanceOf(MultiServerUserRegistry.class, userRegistry); Assert.isInstanceOf(MultiServerUserRegistry.class, userRegistry, "MultiServerUserRegistry required");
return new UserRegistryMessageHandler((MultiServerUserRegistry) userRegistry, return new UserRegistryMessageHandler((MultiServerUserRegistry) userRegistry,
brokerMessagingTemplate(), getBrokerRegistry().getUserRegistryBroadcast(), brokerMessagingTemplate(), getBrokerRegistry().getUserRegistryBroadcast(),
messageBrokerTaskScheduler()); messageBrokerTaskScheduler());
} }
// Expose alias for 4.1 compatibility // Expose alias for 4.1 compatibility
@Bean(name={"messageBrokerTaskScheduler", "messageBrokerSockJsTaskScheduler"}) @Bean(name = {"messageBrokerTaskScheduler", "messageBrokerSockJsTaskScheduler"})
public ThreadPoolTaskScheduler messageBrokerTaskScheduler() { public ThreadPoolTaskScheduler messageBrokerTaskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadNamePrefix("MessageBroker-"); scheduler.setThreadNamePrefix("MessageBroker-");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -55,8 +55,8 @@ public class MessageBrokerRegistry {
public MessageBrokerRegistry(SubscribableChannel clientInboundChannel, MessageChannel clientOutboundChannel) { public MessageBrokerRegistry(SubscribableChannel clientInboundChannel, MessageChannel clientOutboundChannel) {
Assert.notNull(clientInboundChannel); Assert.notNull(clientInboundChannel, "Inbound channel must not be null");
Assert.notNull(clientOutboundChannel); Assert.notNull(clientOutboundChannel, "Outbound channel must not be null");
this.clientInboundChannel = clientInboundChannel; this.clientInboundChannel = clientInboundChannel;
this.clientOutboundChannel = clientOutboundChannel; this.clientOutboundChannel = clientOutboundChannel;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -175,7 +175,7 @@ public class DefaultStompSession implements ConnectionHandlingStompSession {
* <p>By default set to 15,000 (15 seconds). * <p>By default set to 15,000 (15 seconds).
*/ */
public void setReceiptTimeLimit(long receiptTimeLimit) { public void setReceiptTimeLimit(long receiptTimeLimit) {
Assert.isTrue(receiptTimeLimit > 0); Assert.isTrue(receiptTimeLimit > 0, "Receipt time limit must be larger than zero");
this.receiptTimeLimit = receiptTimeLimit; this.receiptTimeLimit = receiptTimeLimit;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -126,7 +126,7 @@ public abstract class StompClientSupport {
* <p>By default set to 15,000 (15 seconds). * <p>By default set to 15,000 (15 seconds).
*/ */
public void setReceiptTimeLimit(long receiptTimeLimit) { public void setReceiptTimeLimit(long receiptTimeLimit) {
Assert.isTrue(receiptTimeLimit > 0); Assert.isTrue(receiptTimeLimit > 0, "Receipt time limit must be larger than zero");
this.receiptTimeLimit = receiptTimeLimit; this.receiptTimeLimit = receiptTimeLimit;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -48,7 +48,7 @@ abstract class AbstractMonoToListenableFutureAdapter<S, T> implements Listenable
protected AbstractMonoToListenableFutureAdapter(Mono<S> mono) { protected AbstractMonoToListenableFutureAdapter(Mono<S> mono) {
Assert.notNull(mono, "'mono' must not be null"); Assert.notNull(mono, "Mono must not be null");
this.monoProcessor = mono this.monoProcessor = mono
.doOnSuccess(result -> { .doOnSuccess(result -> {
T adapted; T adapted;
@ -73,10 +73,8 @@ abstract class AbstractMonoToListenableFutureAdapter<S, T> implements Listenable
} }
@Override @Override
public T get(long timeout, TimeUnit unit) public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
throws InterruptedException, ExecutionException, TimeoutException { Assert.notNull(unit, "TimeUnit must not be null");
Assert.notNull(unit);
Duration duration = Duration.ofMillis(TimeUnit.MILLISECONDS.convert(timeout, unit)); Duration duration = Duration.ofMillis(TimeUnit.MILLISECONDS.convert(timeout, unit));
S result = this.monoProcessor.block(duration); S result = this.monoProcessor.block(duration);
return adapt(result); return adapt(result);
@ -112,6 +110,7 @@ abstract class AbstractMonoToListenableFutureAdapter<S, T> implements Listenable
this.registry.addFailureCallback(failureCallback); this.registry.addFailureCallback(failureCallback);
} }
protected abstract T adapt(S result); protected abstract T adapt(S result);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -159,7 +159,7 @@ public class ReactorNettyTcpStompClientTests {
private final List<String> received = new ArrayList<>(); private final List<String> received = new ArrayList<>();
public ConsumingHandler(String... topics) { public ConsumingHandler(String... topics) {
Assert.notEmpty(topics); Assert.notEmpty(topics, "Topics must not be empty");
this.topics = Arrays.asList(topics); this.topics = Arrays.asList(topics);
this.subscriptionLatch = new CountDownLatch(this.topics.size()); this.subscriptionLatch = new CountDownLatch(this.topics.size());
} }
@ -168,7 +168,6 @@ public class ReactorNettyTcpStompClientTests {
return this.received; return this.received;
} }
@Override @Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) { public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
for (String topic : this.topics) { for (String topic : this.topics) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -399,7 +399,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) { public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
headers.setSessionId(sessionId); headers.setSessionId(sessionId);
headers.setReceipt(receiptId); headers.setReceipt(receiptId);
@ -411,7 +410,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
public MessageExchangeBuilder andExpectMessage(String sessionId, String subscriptionId) { 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(); String destination = this.headers.getDestination();
Object payload = this.message.getPayload(); Object payload = this.message.getPayload();
this.expected.add(new StompMessageFrameMessageMatcher(sessionId, subscriptionId, destination, payload)); this.expected.add(new StompMessageFrameMessageMatcher(sessionId, subscriptionId, destination, payload));
@ -420,7 +419,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
public MessageExchangeBuilder andExpectError() { public MessageExchangeBuilder andExpectError() {
String sessionId = this.headers.getSessionId(); 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); return andExpectError(sessionId);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -110,7 +110,7 @@ public abstract class SessionFactoryUtils {
} }
} }
// Check that it is the Hibernate FlushMode type, not JPA's... // 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");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -135,7 +135,6 @@ public abstract class AbstractEntityManagerFactoryBean implements
* @see javax.persistence.Persistence * @see javax.persistence.Persistence
*/ */
public void setPersistenceProviderClass(Class<? extends PersistenceProvider> persistenceProviderClass) { public void setPersistenceProviderClass(Class<? extends PersistenceProvider> persistenceProviderClass) {
Assert.isAssignable(PersistenceProvider.class, persistenceProviderClass);
this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass); this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass);
} }
@ -217,7 +216,6 @@ public abstract class AbstractEntityManagerFactoryBean implements
* @see JpaVendorAdapter#getEntityManagerFactoryInterface() * @see JpaVendorAdapter#getEntityManagerFactoryInterface()
*/ */
public void setEntityManagerFactoryInterface(Class<? extends EntityManagerFactory> emfInterface) { public void setEntityManagerFactoryInterface(Class<? extends EntityManagerFactory> emfInterface) {
Assert.isAssignable(EntityManagerFactory.class, emfInterface);
this.entityManagerFactoryInterface = emfInterface; this.entityManagerFactoryInterface = emfInterface;
} }
@ -231,7 +229,6 @@ public abstract class AbstractEntityManagerFactoryBean implements
* @see EntityManagerFactoryInfo#getEntityManagerInterface() * @see EntityManagerFactoryInfo#getEntityManagerInterface()
*/ */
public void setEntityManagerInterface(Class<? extends EntityManager> emInterface) { public void setEntityManagerInterface(Class<? extends EntityManager> emInterface) {
Assert.isAssignable(EntityManager.class, emInterface);
this.entityManagerInterface = emInterface; this.entityManagerInterface = emInterface;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -68,7 +68,6 @@ public class SharedEntityManagerBean extends EntityManagerFactoryAccessor
*/ */
public void setEntityManagerInterface(Class<? extends EntityManager> entityManagerInterface) { public void setEntityManagerInterface(Class<? extends EntityManager> entityManagerInterface) {
Assert.notNull(entityManagerInterface, "'entityManagerInterface' must not be null"); Assert.notNull(entityManagerInterface, "'entityManagerInterface' must not be null");
Assert.isAssignable(EntityManager.class, entityManagerInterface);
this.entityManagerInterface = entityManagerInterface; this.entityManagerInterface = entityManagerInterface;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -100,7 +100,7 @@ public class HibernateJpaDialect extends DefaultJpaDialect {
} }
} }
// Check that it is the Hibernate FlushMode type, not JPA's... // 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");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -79,7 +79,6 @@ import org.springframework.oxm.UncategorizedMappingException;
import org.springframework.oxm.UnmarshallingFailureException; import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.support.AbstractMarshaller; import org.springframework.oxm.support.AbstractMarshaller;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -114,7 +113,7 @@ import org.springframework.util.xml.StaxUtils;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 3.0 * @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. * The default encoding used for stream access: UTF-8.
@ -130,7 +129,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin
private Mapper mapper; private Mapper mapper;
private Class<?>[] mapperWrappers; private Class<? extends MapperWrapper>[] mapperWrappers;
private ConverterLookup converterLookup = new DefaultConverterLookup(); private ConverterLookup converterLookup = new DefaultConverterLookup();
@ -210,7 +209,8 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin
* of type {@link Mapper} or {@link MapperWrapper}. * of type {@link Mapper} or {@link MapperWrapper}.
* @since 4.0 * @since 4.0
*/ */
public void setMapperWrappers(Class<?>... mapperWrappers) { @SuppressWarnings("unchecked")
public void setMapperWrappers(Class<? extends MapperWrapper>... mapperWrappers) {
this.mapperWrappers = mapperWrappers; this.mapperWrappers = mapperWrappers;
} }
@ -413,9 +413,8 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin
protected MapperWrapper wrapMapper(MapperWrapper next) { protected MapperWrapper wrapMapper(MapperWrapper next) {
MapperWrapper mapperToWrap = next; MapperWrapper mapperToWrap = next;
if (mapperWrappers != null) { if (mapperWrappers != null) {
for (Class<?> mapperWrapper : mapperWrappers) { for (Class<? extends MapperWrapper> mapperWrapper : mapperWrappers) {
Assert.isAssignable(MapperWrapper.class, mapperWrapper); Constructor<? extends MapperWrapper> ctor;
Constructor<?> ctor;
try { try {
ctor = mapperWrapper.getConstructor(Mapper.class); ctor = mapperWrapper.getConstructor(Mapper.class);
} }
@ -428,9 +427,9 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin
} }
} }
try { try {
mapperToWrap = (MapperWrapper) ctor.newInstance(mapperToWrap); mapperToWrap = ctor.newInstance(mapperToWrap);
} }
catch (Exception ex) { catch (Throwable ex) {
throw new IllegalStateException("Failed to construct MapperWrapper: " + mapperWrapper); throw new IllegalStateException("Failed to construct MapperWrapper: " + mapperWrapper);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -61,7 +61,7 @@ public class MockAsyncContext implements AsyncContext {
public void addDispatchHandler(Runnable handler) { public void addDispatchHandler(Runnable handler) {
Assert.notNull(handler); Assert.notNull(handler, "Dispatch handler must not be null");
this.dispatchHandlers.add(handler); this.dispatchHandlers.add(handler);
} }
@ -77,7 +77,7 @@ public class MockAsyncContext implements AsyncContext {
@Override @Override
public boolean hasOriginalRequestAndResponse() { public boolean hasOriginalRequestAndResponse() {
return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse); return (this.request instanceof MockHttpServletRequest && this.response instanceof MockHttpServletResponse);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -356,12 +356,12 @@ public class MockPageContext extends PageContext {
} }
public byte[] getContentAsByteArray() { public byte[] getContentAsByteArray() {
Assert.isTrue(this.response instanceof MockHttpServletResponse); Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");
return ((MockHttpServletResponse) this.response).getContentAsByteArray(); return ((MockHttpServletResponse) this.response).getContentAsByteArray();
} }
public String getContentAsString() throws UnsupportedEncodingException { public String getContentAsString() throws UnsupportedEncodingException {
Assert.isTrue(this.response instanceof MockHttpServletResponse); Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");
return ((MockHttpServletResponse) this.response).getContentAsString(); return ((MockHttpServletResponse) this.response).getContentAsString();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,7 +43,7 @@ public class SimpleRequestExpectationManager extends AbstractRequestExpectationM
@Override @Override
protected void afterExpectationsDeclared() { protected void afterExpectationsDeclared() {
Assert.state(this.expectationIterator == null); Assert.state(this.expectationIterator == null, "Expectations already declared");
this.expectationIterator = getExpectations().iterator(); this.expectationIterator = getExpectations().iterator();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -41,10 +41,10 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
/** /**
* Demonstrates use of SPI extension points: * Demonstrates use of SPI extension points:
* <ul> * <ul>
* <li> {@link org.springframework.test.web.servlet.request.RequestPostProcessor} * <li> {@link org.springframework.test.web.servlet.request.RequestPostProcessor}
* for extending request building with custom methods. * for extending request building with custom methods.
* <li> {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer * <li> {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer
* MockMvcConfigurer} for extending MockMvc building with some automatic setup. * MockMvcConfigurer} for extending MockMvc building with some automatic setup.
* </ul> * </ul>
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
@ -106,6 +106,7 @@ public class FrameworkExtensionTests {
} }
} }
/** /**
* Test {@code MockMvcConfigurer}. * Test {@code MockMvcConfigurer}.
*/ */
@ -126,6 +127,7 @@ public class FrameworkExtensionTests {
} }
} }
@Controller @Controller
@RequestMapping("/") @RequestMapping("/")
private static class SampleController { private static class SampleController {
@ -133,14 +135,14 @@ public class FrameworkExtensionTests {
@RequestMapping(headers = "Foo") @RequestMapping(headers = "Foo")
@ResponseBody @ResponseBody
public String handleFoo(Principal principal) { public String handleFoo(Principal principal) {
Assert.isTrue(principal != null); Assert.notNull(principal, "Principal must not be null");
return "Foo"; return "Foo";
} }
@RequestMapping(headers = "Bar") @RequestMapping(headers = "Bar")
@ResponseBody @ResponseBody
public String handleBar(Principal principal) { public String handleBar(Principal principal) {
Assert.isTrue(principal != null); Assert.notNull(principal, "Principal must not be null");
return "Bar"; return "Bar";
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -26,7 +26,6 @@ import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/** /**
* {@link org.springframework.beans.factory.FactoryBean} that bootstraps * {@link org.springframework.beans.factory.FactoryBean} that bootstraps
@ -66,9 +65,8 @@ public class ResourceAdapterFactoryBean implements FactoryBean<ResourceAdapter>,
* through the "resourceAdapter" property. * through the "resourceAdapter" property.
* @see #setResourceAdapter * @see #setResourceAdapter
*/ */
public void setResourceAdapterClass(Class<?> resourceAdapterClass) { public void setResourceAdapterClass(Class<? extends ResourceAdapter> resourceAdapterClass) {
Assert.isAssignable(ResourceAdapter.class, resourceAdapterClass); this.resourceAdapter = BeanUtils.instantiateClass(resourceAdapterClass);
this.resourceAdapter = (ResourceAdapter) BeanUtils.instantiateClass(resourceAdapterClass);
} }
/** /**

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.config; package org.springframework.web.reactive.config;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -30,7 +31,7 @@ public class UrlBasedViewResolverRegistration {
public UrlBasedViewResolverRegistration(UrlBasedViewResolver viewResolver) { public UrlBasedViewResolverRegistration(UrlBasedViewResolver viewResolver) {
Assert.notNull(viewResolver); Assert.notNull(viewResolver, "ViewResolver must not be null");
this.viewResolver = viewResolver; this.viewResolver = viewResolver;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.config; package org.springframework.web.reactive.config;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,7 +33,6 @@ import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver; import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
/** /**
* Assist with the configuration of a chain of {@link ViewResolver}'s supporting * Assist with the configuration of a chain of {@link ViewResolver}'s supporting
* different template mechanisms. * different template mechanisms.
@ -46,17 +46,17 @@ import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewRes
*/ */
public class ViewResolverRegistry { public class ViewResolverRegistry {
private final ApplicationContext applicationContext;
private final List<ViewResolver> viewResolvers = new ArrayList<>(4); private final List<ViewResolver> viewResolvers = new ArrayList<>(4);
private final List<View> defaultViews = new ArrayList<>(4); private final List<View> defaultViews = new ArrayList<>(4);
private Integer order; private Integer order;
private final ApplicationContext applicationContext;
public ViewResolverRegistry(ApplicationContext applicationContext) { public ViewResolverRegistry(ApplicationContext applicationContext) {
Assert.notNull(applicationContext); Assert.notNull(applicationContext, "ApplicationContext must not be null");
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -41,10 +41,13 @@ import org.springframework.web.server.support.HttpRequestPathHelper;
* implementations. * implementations.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 5.0 * @since 5.0
*/ */
public abstract class AbstractHandlerMapping extends ApplicationObjectSupport public abstract class AbstractHandlerMapping extends ApplicationObjectSupport implements HandlerMapping, Ordered {
implements HandlerMapping, Ordered {
private static final WebHandler REQUEST_HANDLED_HANDLER = exchange -> Mono.empty();
private int order = Integer.MAX_VALUE; // default: same as non-Ordered private int order = Integer.MAX_VALUE; // default: same as non-Ordered
@ -158,7 +161,6 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport
CorsConfiguration configA = this.globalCorsConfigSource.getCorsConfiguration(exchange); CorsConfiguration configA = this.globalCorsConfigSource.getCorsConfiguration(exchange);
CorsConfiguration configB = getCorsConfiguration(handler, exchange); CorsConfiguration configB = getCorsConfiguration(handler, exchange);
CorsConfiguration config = (configA != null ? configA.combine(configB) : configB); CorsConfiguration config = (configA != null ? configA.combine(configB) : configB);
if (!getCorsProcessor().processRequest(config, exchange) || if (!getCorsProcessor().processRequest(config, exchange) ||
CorsUtils.isPreFlightRequest(exchange.getRequest())) { CorsUtils.isPreFlightRequest(exchange.getRequest())) {
return REQUEST_HANDLED_HANDLER; return REQUEST_HANDLED_HANDLER;
@ -171,13 +173,11 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport
/** /**
* Look up a handler for the given request, returning an empty {@code Mono} * Look up a handler for the given request, returning an empty {@code Mono}
* if no specific one is found. This method is called by {@link #getHandler}. * if no specific one is found. This method is called by {@link #getHandler}.
*
* <p>On CORS pre-flight requests this method should return a match not for * <p>On CORS pre-flight requests this method should return a match not for
* the pre-flight request but for the expected actual request based on the URL * the pre-flight request but for the expected actual request based on the URL
* path, the HTTP methods from the "Access-Control-Request-Method" header, and * path, the HTTP methods from the "Access-Control-Request-Method" header, and
* the headers from the "Access-Control-Request-Headers" header thus allowing * the headers from the "Access-Control-Request-Headers" header thus allowing
* the CORS configuration to be obtained via {@link #getCorsConfigurations}, * the CORS configuration to be obtained via {@link #getCorsConfigurations},
*
* @param exchange current exchange * @param exchange current exchange
* @return {@code Mono} for the matching handler, if any * @return {@code Mono} for the matching handler, if any
*/ */
@ -185,18 +185,15 @@ public abstract class AbstractHandlerMapping extends ApplicationObjectSupport
/** /**
* Retrieve the CORS configuration for the given handler. * Retrieve the CORS configuration for the given handler.
* @param handler the handler to check (never {@code null}). * @param handler the handler to check (never {@code null})
* @param exchange the current exchange * @param exchange the current exchange
* @return the CORS configuration for the handler or {@code null}. * @return the CORS configuration for the handler, or {@code null} if none
*/ */
protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) { protected CorsConfiguration getCorsConfiguration(Object handler, ServerWebExchange exchange) {
if (handler != null && handler instanceof CorsConfigurationSource) { if (handler instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) handler).getCorsConfiguration(exchange); return ((CorsConfigurationSource) handler).getCorsConfiguration(exchange);
} }
return null; return null;
} }
private static final WebHandler REQUEST_HANDLED_HANDLER = exchange -> Mono.empty();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -44,6 +44,7 @@ import org.springframework.web.server.ServerWebExchange;
* path pattern that matches the current request path. * path pattern that matches the current request path.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 5.0 * @since 5.0
*/ */
public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping { public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping {
@ -137,6 +138,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping {
if (handler != null) { if (handler != null) {
return handleMatch(handler, urlPath, urlPath, exchange); return handleMatch(handler, urlPath, urlPath, exchange);
} }
// Pattern match? // Pattern match?
List<String> matches = new ArrayList<>(); List<String> matches = new ArrayList<>();
for (String pattern : this.handlerMap.keySet()) { for (String pattern : this.handlerMap.keySet()) {
@ -149,6 +151,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping {
} }
} }
} }
String bestMatch = null; String bestMatch = null;
Comparator<String> comparator = getPathMatcher().getPatternComparator(urlPath); Comparator<String> comparator = getPathMatcher().getPatternComparator(urlPath);
if (!matches.isEmpty()) { if (!matches.isEmpty()) {
@ -161,12 +164,18 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping {
if (bestMatch != null) { if (bestMatch != null) {
handler = this.handlerMap.get(bestMatch); handler = this.handlerMap.get(bestMatch);
if (handler == null) { if (handler == null) {
Assert.isTrue(bestMatch.endsWith("/")); if (bestMatch.endsWith("/")) {
handler = this.handlerMap.get(bestMatch.substring(0, bestMatch.length() - 1)); handler = this.handlerMap.get(bestMatch.substring(0, bestMatch.length() - 1));
}
if (handler == null) {
throw new IllegalStateException(
"Could not find handler for best pattern match [" + bestMatch + "]");
}
} }
String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestMatch, urlPath); String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestMatch, urlPath);
return handleMatch(handler, bestMatch, pathWithinMapping, exchange); return handleMatch(handler, bestMatch, pathWithinMapping, exchange);
} }
// No handler found... // No handler found...
return null; return null;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,11 +52,10 @@ import org.springframework.web.server.ServerWebExchange;
* <p>For each registered handler method, a unique mapping is maintained with * <p>For each registered handler method, a unique mapping is maintained with
* subclasses defining the details of the mapping type {@code <T>}. * subclasses defining the details of the mapping type {@code <T>}.
* *
* @param <T> The mapping for a {@link HandlerMethod} containing the conditions
* needed to match the handler method to incoming request.
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @since 5.0 * @since 5.0
* @param <T> The mapping for a {@link HandlerMethod} containing the conditions
* needed to match the handler method to incoming request.
*/ */
public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping implements InitializingBean { public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping implements InitializingBean {
@ -570,10 +569,9 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private final List<String> directUrls; private final List<String> directUrls;
public MappingRegistration(T mapping, HandlerMethod handlerMethod, List<String> directUrls) { public MappingRegistration(T mapping, HandlerMethod handlerMethod, List<String> directUrls) {
Assert.notNull(mapping); Assert.notNull(mapping, "Mapping must not be null");
Assert.notNull(handlerMethod); Assert.notNull(handlerMethod, "HandlerMethod must not be null");
this.mapping = mapping; this.mapping = mapping;
this.handlerMethod = handlerMethod; this.handlerMethod = handlerMethod;
this.directUrls = (directUrls != null ? directUrls : Collections.emptyList()); this.directUrls = (directUrls != null ? directUrls : Collections.emptyList());
@ -629,10 +627,11 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
} }
} }
private static class PreFlightAmbiguousMatchHandler { private static class PreFlightAmbiguousMatchHandler {
public void handle() { public void handle() {
throw new UnsupportedOperationException("not implemented"); throw new UnsupportedOperationException("Not implemented");
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -55,7 +55,7 @@ public class SyncInvocableHandlerMethod extends InvocableHandlerMethod {
public void setArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { public void setArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.forEach(resolver -> resolvers.forEach(resolver ->
Assert.isInstanceOf(SyncHandlerMethodArgumentResolver.class, resolver, Assert.isInstanceOf(SyncHandlerMethodArgumentResolver.class, resolver,
"Expected sync argument resolver: " + resolver.getClass().getName())); "SyncHandlerMethodArgumentResolver requires SyncHandlerMethodArgumentResolver"));
super.setArgumentResolvers(resolvers); super.setArgumentResolvers(resolvers);
} }

View File

@ -106,7 +106,6 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand
@Override @Override
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
ResolvableType returnType = result.getReturnType(); ResolvableType returnType = result.getReturnType();
MethodParameter bodyType; MethodParameter bodyType;
@ -117,7 +116,7 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand
ReactiveAdapter adapter = getAdapterRegistry().getAdapter(rawClass, optionalValue); ReactiveAdapter adapter = getAdapterRegistry().getAdapter(rawClass, optionalValue);
if (adapter != null) { if (adapter != null) {
Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported."); Assert.isTrue(!adapter.isMultiValue(), "Only a single ResponseEntity supported");
returnValueMono = Mono.from(adapter.toPublisher(optionalValue)); returnValueMono = Mono.from(adapter.toPublisher(optionalValue));
bodyType = new MethodParameter(result.getReturnTypeSource()); bodyType = new MethodParameter(result.getReturnTypeSource());
bodyType.increaseNestingLevel(); bodyType.increaseNestingLevel();
@ -130,8 +129,7 @@ public class ResponseEntityResultHandler extends AbstractMessageWriterResultHand
} }
return returnValueMono.then(returnValue -> { return returnValueMono.then(returnValue -> {
Assert.isInstanceOf(HttpEntity.class, returnValue, "HttpEntity expected");
Assert.isInstanceOf(HttpEntity.class, returnValue);
HttpEntity<?> httpEntity = (HttpEntity<?>) returnValue; HttpEntity<?> httpEntity = (HttpEntity<?>) returnValue;
if (httpEntity instanceof ResponseEntity) { if (httpEntity instanceof ResponseEntity) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -111,7 +111,7 @@ public class ScriptTemplateView extends AbstractUrlBasedView {
* See {@link ScriptTemplateConfigurer#setEngine(ScriptEngine)} documentation. * See {@link ScriptTemplateConfigurer#setEngine(ScriptEngine)} documentation.
*/ */
public void setEngine(ScriptEngine engine) { public void setEngine(ScriptEngine engine) {
Assert.isInstanceOf(Invocable.class, engine); Assert.isInstanceOf(Invocable.class, engine, "ScriptEngine must implement Invocable");
this.engine = engine; this.engine = engine;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -44,7 +44,7 @@ import org.springframework.web.reactive.socket.WebSocketSession;
*/ */
public class JettyWebSocketSession extends AbstractListenerWebSocketSession<Session> { public class JettyWebSocketSession extends AbstractListenerWebSocketSession<Session> {
private SuspendToken suspendToken; private volatile SuspendToken suspendToken;
public JettyWebSocketSession(Session session, HandshakeInfo info, DataBufferFactory factory) { public JettyWebSocketSession(Session session, HandshakeInfo info, DataBufferFactory factory) {
@ -65,14 +65,15 @@ public class JettyWebSocketSession extends AbstractListenerWebSocketSession<Sess
@Override @Override
protected void suspendReceiving() { protected void suspendReceiving() {
Assert.isNull(this.suspendToken); Assert.state(this.suspendToken == null, "Already suspended");
this.suspendToken = getDelegate().suspend(); this.suspendToken = getDelegate().suspend();
} }
@Override @Override
protected void resumeReceiving() { protected void resumeReceiving() {
Assert.notNull(this.suspendToken); SuspendToken tokenToUse = this.suspendToken;
this.suspendToken.resume(); Assert.state(tokenToUse != null, "Not suspended");
tokenToUse.resume();
this.suspendToken = null; this.suspendToken = null;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -146,12 +146,12 @@ public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Life
} }
private HttpServletRequest getHttpServletRequest(ServerHttpRequest request) { private HttpServletRequest getHttpServletRequest(ServerHttpRequest request) {
Assert.isTrue(request instanceof ServletServerHttpRequest); Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required");
return ((ServletServerHttpRequest) request).getServletRequest(); return ((ServletServerHttpRequest) request).getServletRequest();
} }
private HttpServletResponse getHttpServletResponse(ServerHttpResponse response) { private HttpServletResponse getHttpServletResponse(ServerHttpResponse response) {
Assert.isTrue(response instanceof ServletServerHttpResponse); Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required");
return ((ServletServerHttpResponse) response).getServletResponse(); return ((ServletServerHttpResponse) response).getServletResponse();
} }
@ -180,7 +180,6 @@ public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Life
private final Optional<String> protocol; private final Optional<String> protocol;
public WebSocketHandlerContainer(JettyWebSocketHandlerAdapter adapter, Optional<String> protocol) { public WebSocketHandlerContainer(JettyWebSocketHandlerAdapter adapter, Optional<String> protocol) {
this.adapter = adapter; this.adapter = adapter;
this.protocol = protocol; this.protocol = protocol;
@ -194,4 +193,5 @@ public class JettyRequestUpgradeStrategy implements RequestUpgradeStrategy, Life
return this.protocol; return this.protocol;
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,7 +20,6 @@ import java.io.IOException;
import java.security.Principal; import java.security.Principal;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -35,8 +34,8 @@ import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServletServerHttpRequest; import org.springframework.http.server.reactive.ServletServerHttpRequest;
import org.springframework.http.server.reactive.ServletServerHttpResponse; import org.springframework.http.server.reactive.ServletServerHttpResponse;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.HandshakeInfo; import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter; import org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter;
import org.springframework.web.reactive.socket.adapter.StandardWebSocketSession; import org.springframework.web.reactive.socket.adapter.StandardWebSocketSession;
import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
@ -55,9 +54,7 @@ public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy {
@Override @Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol){
Optional<String> subProtocol){
ServerHttpRequest request = exchange.getRequest(); ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse(); ServerHttpResponse response = exchange.getResponse();
@ -87,12 +84,12 @@ public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy {
} }
private HttpServletRequest getHttpServletRequest(ServerHttpRequest request) { private HttpServletRequest getHttpServletRequest(ServerHttpRequest request) {
Assert.isTrue(request instanceof ServletServerHttpRequest); Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required");
return ((ServletServerHttpRequest) request).getServletRequest(); return ((ServletServerHttpRequest) request).getServletRequest();
} }
private HttpServletResponse getHttpServletResponse(ServerHttpResponse response) { private HttpServletResponse getHttpServletResponse(ServerHttpResponse response) {
Assert.isTrue(response instanceof ServletServerHttpResponse); Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required");
return ((ServletServerHttpResponse) response).getServletResponse(); return ((ServletServerHttpResponse) response).getServletResponse();
} }
@ -103,12 +100,9 @@ public class TomcatRequestUpgradeStrategy implements RequestUpgradeStrategy {
} }
private WsServerContainer getContainer(HttpServletRequest request) { private WsServerContainer getContainer(HttpServletRequest request) {
ServletContext servletContext = request.getServletContext(); Object container = request.getServletContext().getAttribute(SERVER_CONTAINER_ATTR);
Object container = servletContext.getAttribute(SERVER_CONTAINER_ATTR); Assert.state(container instanceof WsServerContainer,
Assert.notNull(container, "No 'javax.websocket.server.ServerContainer' ServletContext attribute in a Tomcat container");
"No 'javax.websocket.server.ServerContainer' ServletContext attribute. " +
"Are you running in a Servlet container that supports JSR-356?");
Assert.isTrue(container instanceof WsServerContainer);
return (WsServerContainer) container; return (WsServerContainer) container;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -53,13 +53,10 @@ import org.springframework.web.server.ServerWebExchange;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy { public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy {
@Override @Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
Optional<String> subProtocol) {
ServerHttpRequest request = exchange.getRequest(); ServerHttpRequest request = exchange.getRequest();
Assert.isTrue(request instanceof UndertowServerHttpRequest); Assert.isInstanceOf(UndertowServerHttpRequest.class, request, "UndertowServerHttpRequest required");
HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange(); HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange();
Set<String> protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet()); Set<String> protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet());
@ -92,10 +89,7 @@ public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy {
private final DataBufferFactory bufferFactory; private final DataBufferFactory bufferFactory;
public DefaultCallback(HandshakeInfo handshakeInfo, WebSocketHandler handler, DataBufferFactory bufferFactory) {
public DefaultCallback(HandshakeInfo handshakeInfo, WebSocketHandler handler,
DataBufferFactory bufferFactory) {
this.handshakeInfo = handshakeInfo; this.handshakeInfo = handshakeInfo;
this.handler = handler; this.handler = handler;
this.bufferFactory = bufferFactory; this.bufferFactory = bufferFactory;
@ -103,7 +97,6 @@ public class UndertowRequestUpgradeStrategy implements RequestUpgradeStrategy {
@Override @Override
public void onConnect(WebSocketHttpExchange httpExchange, WebSocketChannel channel) { public void onConnect(WebSocketHttpExchange httpExchange, WebSocketChannel channel) {
UndertowWebSocketSession session = createSession(channel); UndertowWebSocketSession session = createSession(channel);
UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session); UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,13 +35,14 @@ import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.bootstrap.RxNettyHttpServer; import org.springframework.http.server.reactive.bootstrap.RxNettyHttpServer;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.BodyExtractors; import org.springframework.web.reactive.function.BodyExtractors;
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientOperations; import org.springframework.web.reactive.function.client.WebClientOperations;
import org.springframework.web.util.DefaultUriBuilderFactory; import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriBuilderFactory; import org.springframework.web.util.UriBuilderFactory;
import static org.junit.Assert.*;
/** /**
* @author Sebastien Deleuze * @author Sebastien Deleuze
*/ */
@ -52,8 +53,7 @@ public class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTest
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
// TODO: fix failing RxNetty tests
// TODO: fix failing tests
Assume.assumeFalse(this.server instanceof RxNettyHttpServer); Assume.assumeFalse(this.server instanceof RxNettyHttpServer);
super.setup(); super.setup();
@ -88,7 +88,7 @@ public class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTest
.reduce((s1, s2) -> s1 + s2); .reduce((s1, s2) -> s1 + s2);
StepVerifier.create(result) StepVerifier.create(result)
.consumeNextWith(value -> Assert.isTrue(value.length() == 200000)) .consumeNextWith(value -> assertTrue(value.length() == 200000))
.expectComplete() .expectComplete()
.verify(Duration.ofSeconds(10L)); .verify(Duration.ofSeconds(10L));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.result; package org.springframework.web.reactive.result;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
@ -70,7 +71,6 @@ public class ResolvableMethod {
private final Object object; private final Object object;
private String methodName; private String methodName;
private Class<?>[] argumentTypes; private Class<?>[] argumentTypes;
@ -84,13 +84,13 @@ public class ResolvableMethod {
private ResolvableMethod(Class<?> objectClass) { private ResolvableMethod(Class<?> objectClass) {
Assert.notNull(objectClass); Assert.notNull(objectClass, "Class must not be null");
this.objectClass = objectClass; this.objectClass = objectClass;
this.object = null; this.object = null;
} }
private ResolvableMethod(Object object) { private ResolvableMethod(Object object) {
Assert.notNull(object); Assert.notNull(object, "Object must not be null");
this.object = object; this.object = object;
this.objectClass = object.getClass(); this.objectClass = object.getClass();
} }
@ -136,6 +136,7 @@ public class ResolvableMethod {
return this; return this;
} }
// Resolve methods // Resolve methods
public Method resolve() { public Method resolve() {
@ -168,18 +169,17 @@ public class ResolvableMethod {
return true; return true;
}); });
Assert.isTrue(!methods.isEmpty(), "No matching method: " + this); Assert.state(!methods.isEmpty(), () -> "No matching method: " + this);
Assert.isTrue(methods.size() == 1, "Multiple matching methods: " + this); Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this);
return methods.iterator().next(); return methods.iterator().next();
} }
private String getReturnType() { private String getReturnType() {
return this.returnType != null ? this.returnType.toString() : null; return (this.returnType != null ? this.returnType.toString() : null);
} }
public InvocableHandlerMethod resolveHandlerMethod() { public InvocableHandlerMethod resolveHandlerMethod() {
Assert.notNull(this.object); Assert.state(this.object != null, "Object must not be null");
return new InvocableHandlerMethod(this.object, resolve()); return new InvocableHandlerMethod(this.object, resolve());
} }
@ -194,9 +194,7 @@ public class ResolvableMethod {
} }
@SafeVarargs @SafeVarargs
public final MethodParameter resolveParam(ResolvableType type, public final MethodParameter resolveParam(ResolvableType type, Predicate<MethodParameter>... predicates) {
Predicate<MethodParameter>... predicates) {
List<MethodParameter> matches = new ArrayList<>(); List<MethodParameter> matches = new ArrayList<>();
Method method = resolve(); Method method = resolve();
@ -215,9 +213,8 @@ public class ResolvableMethod {
matches.add(param); matches.add(param);
} }
Assert.isTrue(!matches.isEmpty(), "No matching arg on " + method.toString()); Assert.state(!matches.isEmpty(), () -> "No matching arg on " + method.toString());
Assert.isTrue(matches.size() == 1, "Multiple matching args: " + matches + " on " + method.toString()); Assert.state(matches.size() == 1, () -> "Multiple matching args: " + matches + " on " + method.toString());
return matches.get(0); return matches.get(0);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.result.method.annotation; package org.springframework.web.reactive.result.method.annotation;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -43,18 +44,12 @@ import org.springframework.web.reactive.result.ResolvableMethod;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static junit.framework.TestCase.assertNotNull; import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals; import static org.springframework.core.ResolvableType.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClass;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
import static org.springframework.util.Assert.isTrue;
/** /**
* Unit tests for {@link ModelAttributeMethodArgumentResolver}. * Unit tests for {@link ModelAttributeMethodArgumentResolver}.
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
public class ModelAttributeMethodArgumentResolverTests { public class ModelAttributeMethodArgumentResolverTests {
@ -208,7 +203,7 @@ public class ModelAttributeMethodArgumentResolverTests {
resolvedArgumentMono -> { resolvedArgumentMono -> {
Object value = resolvedArgumentMono.blockMillis(5000); Object value = resolvedArgumentMono.blockMillis(5000);
assertNotNull(value); assertNotNull(value);
isTrue(value instanceof Mono); assertTrue(value instanceof Mono);
return (Mono<?>) value; return (Mono<?>) value;
}); });
} }
@ -220,14 +215,13 @@ public class ModelAttributeMethodArgumentResolverTests {
resolvedArgumentMono -> { resolvedArgumentMono -> {
Object value = resolvedArgumentMono.blockMillis(5000); Object value = resolvedArgumentMono.blockMillis(5000);
assertNotNull(value); assertNotNull(value);
isTrue(value instanceof Single); assertTrue(value instanceof Single);
return Mono.from(RxReactiveStreams.toPublisher((Single) value)); return Mono.from(RxReactiveStreams.toPublisher((Single) value));
}); });
} }
private void testBindFoo(ResolvableType type, Function<Object, Foo> valueExtractor) throws Exception { private void testBindFoo(ResolvableType type, Function<Object, Foo> valueExtractor) throws Exception {
Object value = createResolver() Object value = createResolver()
.resolveArgument(parameter(type), this.bindContext, exchange("name=Robert&age=25")) .resolveArgument(parameter(type), this.bindContext, exchange("name=Robert&age=25"))
.blockMillis(0); .blockMillis(0);

View File

@ -23,8 +23,7 @@ import java.nio.charset.StandardCharsets;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.*;
import static java.nio.charset.StandardCharsets.UTF_8;
/** /**
* Represent the content disposition type and parameters as defined in RFC 2183. * Represent the content disposition type and parameters as defined in RFC 2183.
@ -121,7 +120,7 @@ public class ContentDisposition {
*/ */
public static ContentDisposition parse(String contentDisposition) { public static ContentDisposition parse(String contentDisposition) {
String[] parts = StringUtils.tokenizeToStringArray(contentDisposition, ";"); String[] parts = StringUtils.tokenizeToStringArray(contentDisposition, ";");
Assert.isTrue(parts.length >= 1); Assert.isTrue(parts.length >= 1, "Content-Disposition header must not be empty");
String type = parts[0]; String type = parts[0];
String name = null; String name = null;
String filename = null; String filename = null;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.http; package org.springframework.http;
import java.time.Duration; import java.time.Duration;
@ -50,7 +51,7 @@ public final class ResponseCookie extends HttpCookie {
String path, boolean secure, boolean httpOnly) { String path, boolean secure, boolean httpOnly) {
super(name, value); super(name, value);
Assert.notNull(maxAge); Assert.notNull(maxAge, "Max age must not be null");
this.maxAge = maxAge; this.maxAge = maxAge;
this.domain = Optional.ofNullable(domain); this.domain = Optional.ofNullable(domain);
this.path = Optional.ofNullable(path); this.path = Optional.ofNullable(path);
@ -61,7 +62,6 @@ public final class ResponseCookie extends HttpCookie {
/** /**
* Return the cookie "Max-Age" attribute in seconds. * Return the cookie "Max-Age" attribute in seconds.
*
* <p>A positive value indicates when the cookie expires relative to the * <p>A positive value indicates when the cookie expires relative to the
* current time. A value of 0 means the cookie should expire immediately. * current time. A value of 0 means the cookie should expire immediately.
* A negative value means no "Max-Age" attribute in which case the cookie * A negative value means no "Max-Age" attribute in which case the cookie
@ -100,13 +100,6 @@ public final class ResponseCookie extends HttpCookie {
return this.httpOnly; return this.httpOnly;
} }
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + ObjectUtils.nullSafeHashCode(this.domain);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.path);
return result;
}
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
@ -122,6 +115,14 @@ public final class ResponseCookie extends HttpCookie {
ObjectUtils.nullSafeEquals(this.domain, otherCookie.getDomain())); ObjectUtils.nullSafeEquals(this.domain, otherCookie.getDomain()));
} }
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + ObjectUtils.nullSafeHashCode(this.domain);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.path);
return result;
}
/** /**
* Factory method to obtain a builder for a server-defined cookie that starts * Factory method to obtain a builder for a server-defined cookie that starts
@ -144,7 +145,6 @@ public final class ResponseCookie extends HttpCookie {
private boolean httpOnly; private boolean httpOnly;
@Override @Override
public ResponseCookieBuilder maxAge(Duration maxAge) { public ResponseCookieBuilder maxAge(Duration maxAge) {
this.maxAge = maxAge; this.maxAge = maxAge;
@ -189,6 +189,7 @@ public final class ResponseCookie extends HttpCookie {
}; };
} }
/** /**
* A builder for a server-defined HttpCookie with attributes. * A builder for a server-defined HttpCookie with attributes.
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -177,7 +177,9 @@ public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory,
*/ */
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException { protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
URLConnection urlConnection = (proxy != null ? url.openConnection(proxy) : url.openConnection()); 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; return (HttpURLConnection) urlConnection;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -49,6 +49,7 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest {
*/ */
private enum State {NEW, COMMITTING, COMMITTED} private enum State {NEW, COMMITTING, COMMITTED}
private final HttpHeaders headers; private final HttpHeaders headers;
private final MultiValueMap<String, HttpCookie> cookies; private final MultiValueMap<String, HttpCookie> cookies;
@ -63,7 +64,7 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest {
} }
public AbstractClientHttpRequest(HttpHeaders headers) { public AbstractClientHttpRequest(HttpHeaders headers) {
Assert.notNull(headers); Assert.notNull(headers, "HttpHeaders must not be null");
this.headers = headers; this.headers = headers;
this.cookies = new LinkedMultiValueMap<>(); this.cookies = new LinkedMultiValueMap<>();
} }
@ -124,7 +125,7 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest {
@Override @Override
public void beforeCommit(Supplier<? extends Mono<Void>> action) { public void beforeCommit(Supplier<? extends Mono<Void>> action) {
Assert.notNull(action); Assert.notNull(action, "Action must not be null");
this.commitActions.add(action); this.commitActions.add(action);
} }
@ -140,5 +141,4 @@ public abstract class AbstractClientHttpRequest implements ClientHttpRequest {
*/ */
protected abstract void applyCookies(); protected abstract void applyCookies();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,16 +58,17 @@ public class MappingJackson2CborHttpMessageConverter extends AbstractJackson2Htt
*/ */
public MappingJackson2CborHttpMessageConverter(ObjectMapper objectMapper) { public MappingJackson2CborHttpMessageConverter(ObjectMapper objectMapper) {
super(objectMapper, new MediaType("application", "cbor")); super(objectMapper, new MediaType("application", "cbor"));
Assert.isAssignable(CBORFactory.class, objectMapper.getFactory().getClass()); Assert.isInstanceOf(CBORFactory.class, objectMapper.getFactory(), "CBORFactory required");
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* The {@code objectMapper} parameter must be configured with a {@code CBORFactory} instance. * The {@code ObjectMapper} must be configured with a {@code CBORFactory} instance.
*/ */
@Override @Override
public void setObjectMapper(ObjectMapper objectMapper) { public void setObjectMapper(ObjectMapper objectMapper) {
Assert.isAssignable(CBORFactory.class, objectMapper.getFactory().getClass()); Assert.isInstanceOf(CBORFactory.class, objectMapper.getFactory(), "CBORFactory required");
super.setObjectMapper(objectMapper); super.setObjectMapper(objectMapper);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -58,16 +58,17 @@ public class MappingJackson2SmileHttpMessageConverter extends AbstractJackson2Ht
*/ */
public MappingJackson2SmileHttpMessageConverter(ObjectMapper objectMapper) { public MappingJackson2SmileHttpMessageConverter(ObjectMapper objectMapper) {
super(objectMapper, new MediaType("application", "x-jackson-smile")); super(objectMapper, new MediaType("application", "x-jackson-smile"));
Assert.isAssignable(SmileFactory.class, objectMapper.getFactory().getClass()); Assert.isInstanceOf(SmileFactory.class, objectMapper.getFactory(), "SmileFactory required");
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* The {@code objectMapper} parameter must be configured with a {@code SmileFactory} instance. * The {@code ObjectMapper} must be configured with a {@code SmileFactory} instance.
*/ */
@Override @Override
public void setObjectMapper(ObjectMapper objectMapper) { public void setObjectMapper(ObjectMapper objectMapper) {
Assert.isAssignable(SmileFactory.class, objectMapper.getFactory().getClass()); Assert.isInstanceOf(SmileFactory.class, objectMapper.getFactory(), "SmileFactory required");
super.setObjectMapper(objectMapper); super.setObjectMapper(objectMapper);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -60,16 +60,17 @@ public class MappingJackson2XmlHttpMessageConverter extends AbstractJackson2Http
super(objectMapper, new MediaType("application", "xml"), super(objectMapper, new MediaType("application", "xml"),
new MediaType("text", "xml"), new MediaType("text", "xml"),
new MediaType("application", "*+xml")); new MediaType("application", "*+xml"));
Assert.isAssignable(XmlMapper.class, objectMapper.getClass()); Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required");
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* The {@code objectMapper} parameter must be a {@link XmlMapper} instance. * The {@code ObjectMapper} parameter must be a {@link XmlMapper} instance.
*/ */
@Override @Override
public void setObjectMapper(ObjectMapper objectMapper) { public void setObjectMapper(ObjectMapper objectMapper) {
Assert.isAssignable(XmlMapper.class, objectMapper.getClass()); Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required");
super.setObjectMapper(objectMapper); super.setObjectMapper(objectMapper);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -181,7 +181,9 @@ public class ServletServerHttpRequest implements ServerHttpRequest {
@Override @Override
public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response) { public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response) {
if (this.asyncRequestControl == null) { 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; ServletServerHttpResponse servletServerResponse = (ServletServerHttpResponse) response;
this.asyncRequestControl = new ServletServerHttpAsyncRequestControl(this, servletServerResponse); this.asyncRequestControl = new ServletServerHttpAsyncRequestControl(this, servletServerResponse);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.http.server.reactive; package org.springframework.http.server.reactive;
import java.io.IOException; import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -28,6 +27,8 @@ import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription; import org.reactivestreams.Subscription;
import reactor.core.publisher.Operators; import reactor.core.publisher.Operators;
import org.springframework.util.Assert;
/** /**
* Abstract base class for {@code Publisher} implementations that bridge between * Abstract base class for {@code Publisher} implementations that bridge between
* event-listener read APIs and Reactive Streams. * event-listener read APIs and Reactive Streams.
@ -48,6 +49,7 @@ public abstract class AbstractListenerReadPublisher<T> implements Publisher<T> {
private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED); private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED);
@SuppressWarnings("unused")
private volatile long demand; private volatile long demand;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -196,7 +198,8 @@ public abstract class AbstractListenerReadPublisher<T> implements Publisher<T> {
UNSUBSCRIBED { UNSUBSCRIBED {
@Override @Override
<T> void subscribe(AbstractListenerReadPublisher<T> publisher, Subscriber<? super T> subscriber) { <T> void subscribe(AbstractListenerReadPublisher<T> publisher, Subscriber<? super T> subscriber) {
Objects.requireNonNull(subscriber); Assert.notNull(publisher, "Publisher must not be null");
Assert.notNull(subscriber, "Subscriber must not be null");
if (publisher.changeState(this, NO_DEMAND)) { if (publisher.changeState(this, NO_DEMAND)) {
Subscription subscription = new ReadSubscription(publisher); Subscription subscription = new ReadSubscription(publisher);
publisher.subscriber = subscriber; publisher.subscriber = subscriber;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.http.server.reactive; package org.springframework.http.server.reactive;
import java.io.IOException; import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -27,6 +26,8 @@ import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber; import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription; import org.reactivestreams.Subscription;
import org.springframework.util.Assert;
/** /**
* An alternative to {@link AbstractListenerWriteProcessor} but instead writing * An alternative to {@link AbstractListenerWriteProcessor} but instead writing
* a {@code Publisher<Publisher<T>>} with flush boundaries enforces after * a {@code Publisher<Publisher<T>>} with flush boundaries enforces after
@ -127,10 +128,9 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
private enum State { private enum State {
UNSUBSCRIBED { UNSUBSCRIBED {
@Override @Override
public <T> void onSubscribe(AbstractListenerWriteFlushProcessor<T> processor, Subscription subscription) { public <T> void onSubscribe(AbstractListenerWriteFlushProcessor<T> processor, Subscription subscription) {
Objects.requireNonNull(subscription, "Subscription cannot be null"); Assert.notNull(subscription, "Subscription must not be null");
if (processor.changeState(this, REQUESTED)) { if (processor.changeState(this, REQUESTED)) {
processor.subscription = subscription; processor.subscription = subscription;
subscription.request(1); subscription.request(1);
@ -140,8 +140,8 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
} }
} }
}, },
REQUESTED {
REQUESTED {
@Override @Override
public <T> void onNext(AbstractListenerWriteFlushProcessor<T> processor, Publisher<? extends T> chunk) { public <T> void onNext(AbstractListenerWriteFlushProcessor<T> processor, Publisher<? extends T> chunk) {
if (processor.changeState(this, RECEIVED)) { if (processor.changeState(this, RECEIVED)) {
@ -150,7 +150,6 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
chunkProcessor.subscribe(new WriteSubscriber(processor)); chunkProcessor.subscribe(new WriteSubscriber(processor));
} }
} }
@Override @Override
public <T> void onComplete(AbstractListenerWriteFlushProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteFlushProcessor<T> processor) {
if (processor.changeState(this, COMPLETED)) { if (processor.changeState(this, COMPLETED)) {
@ -158,8 +157,8 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
} }
} }
}, },
RECEIVED {
RECEIVED {
@Override @Override
public <T> void writeComplete(AbstractListenerWriteFlushProcessor<T> processor) { public <T> void writeComplete(AbstractListenerWriteFlushProcessor<T> processor) {
try { try {
@ -169,7 +168,6 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
processor.cancel(); processor.cancel();
processor.onError(ex); processor.onError(ex);
} }
if (processor.subscriberCompleted) { if (processor.subscriberCompleted) {
if (processor.changeState(this, COMPLETED)) { if (processor.changeState(this, COMPLETED)) {
processor.resultPublisher.publishComplete(); processor.resultPublisher.publishComplete();
@ -181,26 +179,21 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
} }
} }
} }
@Override @Override
public <T> void onComplete(AbstractListenerWriteFlushProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteFlushProcessor<T> processor) {
processor.subscriberCompleted = true; processor.subscriberCompleted = true;
} }
}, },
COMPLETED { COMPLETED {
@Override @Override
public <T> void onNext(AbstractListenerWriteFlushProcessor<T> processor, public <T> void onNext(AbstractListenerWriteFlushProcessor<T> processor, Publisher<? extends T> publisher) {
Publisher<? extends T> publisher) {
// ignore // ignore
} }
@Override @Override
public <T> void onError(AbstractListenerWriteFlushProcessor<T> processor, Throwable t) { public <T> void onError(AbstractListenerWriteFlushProcessor<T> processor, Throwable t) {
// ignore // ignore
} }
@Override @Override
public <T> void onComplete(AbstractListenerWriteFlushProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteFlushProcessor<T> processor) {
// ignore // ignore
@ -234,7 +227,6 @@ public abstract class AbstractListenerWriteFlushProcessor<T> implements Processo
private final AbstractListenerWriteFlushProcessor<?> processor; private final AbstractListenerWriteFlushProcessor<?> processor;
public WriteSubscriber(AbstractListenerWriteFlushProcessor<?> processor) { public WriteSubscriber(AbstractListenerWriteFlushProcessor<?> processor) {
this.processor = processor; this.processor = processor;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.http.server.reactive; package org.springframework.http.server.reactive;
import java.io.IOException; import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -120,7 +119,9 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
* Called when a data item is received via {@link Subscriber#onNext(Object)} * Called when a data item is received via {@link Subscriber#onNext(Object)}
*/ */
protected void receiveData(T data) { protected void receiveData(T data) {
Assert.state(this.currentData == null); if (this.currentData != null) {
throw new IllegalStateException("Current data not processed yet: " + this.currentData);
}
this.currentData = data; this.currentData = data;
} }
@ -185,10 +186,9 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
* #REQUESTED}. * #REQUESTED}.
*/ */
UNSUBSCRIBED { UNSUBSCRIBED {
@Override @Override
public <T> void onSubscribe(AbstractListenerWriteProcessor<T> processor, Subscription subscription) { public <T> void onSubscribe(AbstractListenerWriteProcessor<T> processor, Subscription subscription) {
Objects.requireNonNull(subscription, "Subscription cannot be null"); Assert.notNull(subscription, "Subscription must not be null");
if (processor.changeState(this, REQUESTED)) { if (processor.changeState(this, REQUESTED)) {
processor.subscription = subscription; processor.subscription = subscription;
subscription.request(1); subscription.request(1);
@ -198,6 +198,7 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
} }
} }
}, },
/** /**
* State that gets entered after a data has been * State that gets entered after a data has been
* {@linkplain Subscription#request(long) requested}. Responds to {@code onNext} * {@linkplain Subscription#request(long) requested}. Responds to {@code onNext}
@ -205,7 +206,6 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
* changing state to {@link #COMPLETED}. * changing state to {@link #COMPLETED}.
*/ */
REQUESTED { REQUESTED {
@Override @Override
public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) { public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) {
if (processor.isDataEmpty(data)) { if (processor.isDataEmpty(data)) {
@ -218,7 +218,6 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
} }
} }
} }
@Override @Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
if (processor.changeState(this, COMPLETED)) { if (processor.changeState(this, COMPLETED)) {
@ -226,6 +225,7 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
} }
} }
}, },
/** /**
* State that gets entered after a data has been * State that gets entered after a data has been
* {@linkplain Subscriber#onNext(Object) received}. Responds to * {@linkplain Subscriber#onNext(Object) received}. Responds to
@ -233,10 +233,9 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
* the state to {@link #WRITING}. If it can be written completely, * the state to {@link #WRITING}. If it can be written completely,
* changes the state to either {@link #REQUESTED} if the subscription * changes the state to either {@link #REQUESTED} if the subscription
* has not been completed; or {@link #COMPLETED} if it has. If it cannot * has not been completed; or {@link #COMPLETED} if it has. If it cannot
* be written completely the state will be changed to {@link #RECEIVED}. * be written completely the state will be changed to {@code #RECEIVED}.
*/ */
RECEIVED { RECEIVED {
@Override @Override
public <T> void onWritePossible(AbstractListenerWriteProcessor<T> processor) { public <T> void onWritePossible(AbstractListenerWriteProcessor<T> processor) {
if (processor.changeState(this, WRITING)) { if (processor.changeState(this, WRITING)) {
@ -265,38 +264,35 @@ public abstract class AbstractListenerWriteProcessor<T> implements Processor<T,
} }
} }
} }
@Override @Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
processor.subscriberCompleted = true; processor.subscriberCompleted = true;
} }
}, },
/** /**
* State that gets entered after a writing of the current data has been * State that gets entered after a writing of the current data has been
* {@code onWritePossible started}. * {@code onWritePossible started}.
*/ */
WRITING { WRITING {
@Override @Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
processor.subscriberCompleted = true; processor.subscriberCompleted = true;
} }
}, },
/** /**
* The terminal completed state. Does not respond to any events. * The terminal completed state. Does not respond to any events.
*/ */
COMPLETED { COMPLETED {
@Override @Override
public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) { public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) {
// ignore // ignore
} }
@Override @Override
public <T> void onError(AbstractListenerWriteProcessor<T> processor, Throwable ex) { public <T> void onError(AbstractListenerWriteProcessor<T> processor, Throwable ex) {
// ignore // ignore
} }
@Override @Override
public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) {
// ignore // ignore

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -89,7 +89,7 @@ public abstract class AbstractServerHttpResponse implements ServerHttpResponse {
@Override @Override
public boolean setStatusCode(HttpStatus statusCode) { public boolean setStatusCode(HttpStatus statusCode) {
Assert.notNull(statusCode); Assert.notNull(statusCode, "Status code must not be null");
if (this.state.get() == State.COMMITTED) { if (this.state.get() == State.COMMITTED) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Can't set the status " + statusCode.toString() + logger.debug("Can't set the status " + statusCode.toString() +

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.http.server.reactive; package org.springframework.http.server.reactive;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -57,11 +58,9 @@ public abstract class HttpHandlerAdapterSupport {
/** /**
* Constructor with {@code HttpHandler}s mapped to distinct context paths. * Constructor with {@code HttpHandler}s mapped to distinct context paths.
* Context paths must start but not end with "/" and must be encoded. * Context paths must start but not end with "/" and must be encoded.
*
* <p>At request time context paths are compared against the "raw" path of * <p>At request time context paths are compared against the "raw" path of
* the request URI in the order in which they are provided. The first one * the request URI in the order in which they are provided. The first one
* to match is chosen. If none match the response status is set to 404. * to match is chosen. If none match the response status is set to 404.
*
* @param handlerMap map with context paths and {@code HttpHandler}s. * @param handlerMap map with context paths and {@code HttpHandler}s.
* @see ServerHttpRequest#getContextPath() * @see ServerHttpRequest#getContextPath()
*/ */
@ -85,9 +84,8 @@ public abstract class HttpHandlerAdapterSupport {
private final Map<String, HttpHandler> handlerMap; private final Map<String, HttpHandler> handlerMap;
public CompositeHttpHandler(Map<String, HttpHandler> handlerMap) { public CompositeHttpHandler(Map<String, HttpHandler> handlerMap) {
Assert.notEmpty(handlerMap); Assert.notEmpty(handlerMap, "Handler map must not be empty");
this.handlerMap = initHandlerMap(handlerMap); this.handlerMap = initHandlerMap(handlerMap);
} }
@ -97,10 +95,10 @@ public abstract class HttpHandlerAdapterSupport {
} }
private static void validateContextPath(String contextPath) { private static void validateContextPath(String contextPath) {
Assert.hasText(contextPath, "contextPath must not be empty"); Assert.hasText(contextPath, "Context path must not be empty");
if (!contextPath.equals("/")) { if (!contextPath.equals("/")) {
Assert.isTrue(contextPath.startsWith("/"), "contextPath must begin with '/'"); Assert.isTrue(contextPath.startsWith("/"), "Context path must begin with '/'");
Assert.isTrue(!contextPath.endsWith("/"), "contextPath must not end with '/'"); Assert.isTrue(!contextPath.endsWith("/"), "Context path must not end with '/'");
} }
} }
@ -124,7 +122,9 @@ public abstract class HttpHandlerAdapterSupport {
}); });
} }
/** Strip the context path from native request if any */ /**
* Strip the context path from the native request, if any.
*/
private String getPathToUse(ServerHttpRequest request) { private String getPathToUse(ServerHttpRequest request) {
String path = request.getURI().getRawPath(); String path = request.getURI().getRawPath();
String contextPath = request.getContextPath(); String contextPath = request.getContextPath();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -50,12 +50,12 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme
private static final int DEFAULT_BUFFER_SIZE = 8192; private static final int DEFAULT_BUFFER_SIZE = 8192;
private int bufferSize = DEFAULT_BUFFER_SIZE;
// Servlet is based on blocking I/O, hence the usage of non-direct, heap-based buffers // Servlet is based on blocking I/O, hence the usage of non-direct, heap-based buffers
// (i.e. 'false' as constructor argument) // (i.e. 'false' as constructor argument)
private DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(false); private DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(false);
private int bufferSize = DEFAULT_BUFFER_SIZE;
public ServletHttpHandlerAdapter(HttpHandler httpHandler) { public ServletHttpHandlerAdapter(HttpHandler httpHandler) {
super(httpHandler); super(httpHandler);
@ -66,21 +66,12 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme
} }
public void setDataBufferFactory(DataBufferFactory dataBufferFactory) {
Assert.notNull(dataBufferFactory, "'dataBufferFactory' must not be null");
this.dataBufferFactory = dataBufferFactory;
}
public DataBufferFactory getDataBufferFactory() {
return this.dataBufferFactory;
}
/** /**
* Set the size of the input buffer used for reading in bytes. * Set the size of the input buffer used for reading in bytes.
* <p>By default this is set to 8192. * <p>By default this is set to 8192.
*/ */
public void setBufferSize(int bufferSize) { public void setBufferSize(int bufferSize) {
Assert.isTrue(bufferSize > 0); Assert.isTrue(bufferSize > 0, "Buffer size must be larger than zero");
this.bufferSize = bufferSize; this.bufferSize = bufferSize;
} }
@ -91,10 +82,20 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme
return this.bufferSize; return this.bufferSize;
} }
public void setDataBufferFactory(DataBufferFactory dataBufferFactory) {
Assert.notNull(dataBufferFactory, "DataBufferFactory must not be null");
this.dataBufferFactory = dataBufferFactory;
}
public DataBufferFactory getDataBufferFactory() {
return this.dataBufferFactory;
}
// The Servlet.service method
@Override @Override
public void service(ServletRequest request, ServletResponse response) throws IOException { public void service(ServletRequest request, ServletResponse response) throws IOException {
// Start async before Read/WriteListener registration // Start async before Read/WriteListener registration
AsyncContext asyncContext = request.startAsync(); AsyncContext asyncContext = request.startAsync();
@ -105,18 +106,15 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme
getHttpHandler().handle(httpRequest, httpResponse).subscribe(subscriber); getHttpHandler().handle(httpRequest, httpResponse).subscribe(subscriber);
} }
protected ServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context) protected ServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context) throws IOException {
throws IOException {
return new ServletServerHttpRequest(request, context, getDataBufferFactory(), getBufferSize()); return new ServletServerHttpRequest(request, context, getDataBufferFactory(), getBufferSize());
} }
protected ServerHttpResponse createResponse(HttpServletResponse response, AsyncContext context) protected ServerHttpResponse createResponse(HttpServletResponse response, AsyncContext context) throws IOException {
throws IOException {
return new ServletServerHttpResponse(response, context, getDataBufferFactory(), getBufferSize()); return new ServletServerHttpResponse(response, context, getDataBufferFactory(), getBufferSize());
} }
// Other Servlet methods... // Other Servlet methods...
@Override @Override
@ -142,7 +140,6 @@ public class ServletHttpHandlerAdapter extends HttpHandlerAdapterSupport impleme
private final AsyncContext asyncContext; private final AsyncContext asyncContext;
public HandlerResultSubscriber(AsyncContext asyncContext) { public HandlerResultSubscriber(AsyncContext asyncContext) {
this.asyncContext = asyncContext; this.asyncContext = asyncContext;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,6 +43,7 @@ import org.springframework.util.Assert;
/** /**
* Adapt {@link ServerHttpResponse} to the Servlet {@link HttpServletResponse}. * Adapt {@link ServerHttpResponse} to the Servlet {@link HttpServletResponse}.
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @since 5.0 * @since 5.0
*/ */
@ -66,7 +67,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons
Assert.notNull(response, "HttpServletResponse must not be null"); Assert.notNull(response, "HttpServletResponse must not be null");
Assert.notNull(bufferFactory, "DataBufferFactory must not be null"); Assert.notNull(bufferFactory, "DataBufferFactory must not be null");
Assert.isTrue(bufferSize > 0, "'bufferSize' must be greater than 0"); Assert.isTrue(bufferSize > 0, "Buffer size must be greater than 0");
this.response = response; this.response = response;
this.bufferSize = bufferSize; this.bufferSize = bufferSize;
@ -210,6 +211,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons
} }
} }
private class ResponseBodyWriteListener implements WriteListener { private class ResponseBodyWriteListener implements WriteListener {
@Override @Override
@ -228,6 +230,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons
} }
} }
private class ResponseBodyFlushProcessor extends AbstractListenerWriteFlushProcessor<DataBuffer> { private class ResponseBodyFlushProcessor extends AbstractListenerWriteFlushProcessor<DataBuffer> {
@Override @Override
@ -251,11 +254,11 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons
} }
} }
private class ResponseBodyProcessor extends AbstractListenerWriteProcessor<DataBuffer> { private class ResponseBodyProcessor extends AbstractListenerWriteProcessor<DataBuffer> {
private final ServletOutputStream outputStream; private final ServletOutputStream outputStream;
public ResponseBodyProcessor(ServletOutputStream outputStream) { public ResponseBodyProcessor(ServletOutputStream outputStream) {
this.outputStream = outputStream; this.outputStream = outputStream;
} }
@ -268,7 +271,7 @@ public class ServletServerHttpResponse extends AbstractListenerServerHttpRespons
@Override @Override
protected void releaseData() { protected void releaseData() {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("releaseBuffer: " + this.currentData); logger.trace("releaseData: " + this.currentData);
} }
DataBufferUtils.release(this.currentData); DataBufferUtils.release(this.currentData);
this.currentData = null; this.currentData = null;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,7 +30,6 @@ import io.undertow.server.handlers.CookieImpl;
import io.undertow.util.HttpString; import io.undertow.util.HttpString;
import org.reactivestreams.Processor; import org.reactivestreams.Processor;
import org.reactivestreams.Publisher; import org.reactivestreams.Publisher;
import org.xnio.ChannelListener;
import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.StreamSinkChannel;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
@ -60,7 +59,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
public UndertowServerHttpResponse(HttpServerExchange exchange, DataBufferFactory bufferFactory) { public UndertowServerHttpResponse(HttpServerExchange exchange, DataBufferFactory bufferFactory) {
super(bufferFactory); super(bufferFactory);
Assert.notNull(exchange, "'exchange' is required."); Assert.notNull(exchange, "HttpServerExchange is required");
this.exchange = exchange; this.exchange = exchange;
} }
@ -69,6 +68,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
return this.exchange; return this.exchange;
} }
@Override @Override
protected void applyStatusCode() { protected void applyStatusCode() {
HttpStatus statusCode = this.getStatusCode(); HttpStatus statusCode = this.getStatusCode();
@ -145,15 +145,13 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
private volatile ByteBuffer byteBuffer; private volatile ByteBuffer byteBuffer;
public ResponseBodyProcessor(StreamSinkChannel channel) { public ResponseBodyProcessor(StreamSinkChannel channel) {
Assert.notNull(channel, "StreamSinkChannel must not be null"); Assert.notNull(channel, "StreamSinkChannel must not be null");
this.channel = channel; this.channel = channel;
} }
public void registerListener() { public void registerListener() {
this.channel.getWriteSetter().set((ChannelListener<StreamSinkChannel>) c -> onWritePossible()); this.channel.getWriteSetter().set(c -> onWritePossible());
this.channel.resumeWrites(); this.channel.resumeWrites();
} }
@ -199,7 +197,7 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
@Override @Override
protected void releaseData() { protected void releaseData() {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("releaseBuffer: " + this.currentData); logger.trace("releaseData: " + this.currentData);
} }
DataBufferUtils.release(this.currentData); DataBufferUtils.release(this.currentData);
this.currentData = null; this.currentData = null;
@ -209,10 +207,11 @@ public class UndertowServerHttpResponse extends AbstractListenerServerHttpRespon
@Override @Override
protected boolean isDataEmpty(DataBuffer dataBuffer) { protected boolean isDataEmpty(DataBuffer dataBuffer) {
return dataBuffer.readableByteCount() == 0; return (dataBuffer.readableByteCount() == 0);
} }
} }
private class ResponseBodyFlushProcessor extends AbstractListenerWriteFlushProcessor<DataBuffer> { private class ResponseBodyFlushProcessor extends AbstractListenerWriteFlushProcessor<DataBuffer> {
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,6 @@
package org.springframework.http.server.reactive; package org.springframework.http.server.reactive;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -26,6 +25,8 @@ import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription; import org.reactivestreams.Subscription;
import reactor.core.publisher.Operators; import reactor.core.publisher.Operators;
import org.springframework.util.Assert;
/** /**
* Publisher returned from {@link ServerHttpResponse#writeWith(Publisher)}. * Publisher returned from {@link ServerHttpResponse#writeWith(Publisher)}.
* *
@ -113,12 +114,10 @@ class WriteResultPublisher implements Publisher<Void> {
UNSUBSCRIBED { UNSUBSCRIBED {
@Override @Override
void subscribe(WriteResultPublisher publisher, void subscribe(WriteResultPublisher publisher, Subscriber<? super Void> subscriber) {
Subscriber<? super Void> subscriber) { Assert.notNull(subscriber, "Subscriber must not be null");
Objects.requireNonNull(subscriber);
if (publisher.changeState(this, SUBSCRIBED)) { if (publisher.changeState(this, SUBSCRIBED)) {
Subscription subscription = Subscription subscription = new ResponseBodyWriteResultSubscription(publisher);
new ResponseBodyWriteResultSubscription(publisher);
publisher.subscriber = subscriber; publisher.subscriber = subscriber;
subscriber.onSubscribe(subscription); subscriber.onSubscribe(subscription);
if (publisher.publisherCompleted) { if (publisher.publisherCompleted) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -136,15 +136,15 @@ public class PathExtensionContentNegotiationStrategy extends AbstractMappingCont
/** /**
* A public method exposing the knowledge of the path extension strategy to * 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 * {@link Resource}. The method first looks up any explicitly registered
* file extensions first and then falls back on JAF if available. * file extensions first and then falls back on JAF if available.
* @param resource the resource to look up * @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 * @since 4.3
*/ */
public MediaType getMediaTypeForResource(Resource resource) { public MediaType getMediaTypeForResource(Resource resource) {
Assert.notNull(resource); Assert.notNull(resource, "Resource must not be null");
MediaType mediaType = null; MediaType mediaType = null;
String filename = resource.getFilename(); String filename = resource.getFilename();
String extension = StringUtils.getFilenameExtension(filename); String extension = StringUtils.getFilenameExtension(filename);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -64,7 +64,7 @@ public class UnsatisfiedServletRequestParameterException extends ServletRequestB
Map<String, String[]> actualParams) { Map<String, String[]> actualParams) {
super(""); super("");
Assert.isTrue(!CollectionUtils.isEmpty(paramConditions)); Assert.notEmpty(paramConditions, "Parameter conditions must not be empty");
this.paramConditions = paramConditions; this.paramConditions = paramConditions;
this.actualParams = actualParams; this.actualParams = actualParams;
} }

View File

@ -37,7 +37,6 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -480,7 +479,10 @@ public class ContextLoader {
private Class<ApplicationContextInitializer<ConfigurableApplicationContext>> loadInitializerClass(String className) { private Class<ApplicationContextInitializer<ConfigurableApplicationContext>> loadInitializerClass(String className) {
try { try {
Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); 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<ApplicationContextInitializer<ConfigurableApplicationContext>>) clazz; return (Class<ApplicationContextInitializer<ConfigurableApplicationContext>>) clazz;
} }
catch (ClassNotFoundException ex) { catch (ClassNotFoundException ex) {

View File

@ -816,7 +816,7 @@ final class HierarchicalUriComponents extends UriComponents {
private final List<PathComponent> pathComponents; private final List<PathComponent> pathComponents;
public PathComponentComposite(List<PathComponent> pathComponents) { public PathComponentComposite(List<PathComponent> pathComponents) {
Assert.notNull(pathComponents); Assert.notNull(pathComponents, "PathComponent List must not be null");
this.pathComponents = pathComponents; this.pathComponents = pathComponents;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -41,10 +41,10 @@ import static org.junit.Assert.fail;
public class HttpHandlerAdapterSupportTests { public class HttpHandlerAdapterSupportTests {
@Test @Test
public void invalidContextPath() throws Exception { public void invalidContextPath() {
testInvalidContextPath(" ", "contextPath must not be empty"); testInvalidContextPath(" ", "Context path must not be empty");
testInvalidContextPath("path", "contextPath must begin with '/'"); testInvalidContextPath("path", "Context path must begin with '/'");
testInvalidContextPath("/path/", "contextPath must not end with '/'"); testInvalidContextPath("/path/", "Context path must not end with '/'");
} }
private void testInvalidContextPath(String contextPath, String errorMessage) { private void testInvalidContextPath(String contextPath, String errorMessage) {
@ -58,7 +58,7 @@ public class HttpHandlerAdapterSupportTests {
} }
@Test @Test
public void match() throws Exception { public void match() {
TestHttpHandler handler1 = new TestHttpHandler(); TestHttpHandler handler1 = new TestHttpHandler();
TestHttpHandler handler2 = new TestHttpHandler(); TestHttpHandler handler2 = new TestHttpHandler();
TestHttpHandler handler3 = new TestHttpHandler(); TestHttpHandler handler3 = new TestHttpHandler();
@ -75,7 +75,7 @@ public class HttpHandlerAdapterSupportTests {
} }
@Test @Test
public void matchWithContextPathEqualToPath() throws Exception { public void matchWithContextPathEqualToPath() {
TestHttpHandler handler1 = new TestHttpHandler(); TestHttpHandler handler1 = new TestHttpHandler();
TestHttpHandler handler2 = new TestHttpHandler(); TestHttpHandler handler2 = new TestHttpHandler();
TestHttpHandler handler3 = new TestHttpHandler(); TestHttpHandler handler3 = new TestHttpHandler();
@ -92,7 +92,7 @@ public class HttpHandlerAdapterSupportTests {
} }
@Test @Test
public void matchWithNativeContextPath() throws Exception { public void matchWithNativeContextPath() {
MockServerHttpRequest request = MockServerHttpRequest MockServerHttpRequest request = MockServerHttpRequest
.get("/yet/another/path") .get("/yet/another/path")
.contextPath("/yet") // contextPath in underlying request .contextPath("/yet") // contextPath in underlying request

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -80,12 +80,12 @@ public abstract class AbstractHttpServer implements HttpServer {
@Override @Override
public final void afterPropertiesSet() throws Exception { public final void afterPropertiesSet() throws Exception {
synchronized (this.lifecycleMonitor) { Assert.notNull(this.host, "Host must not be null");
Assert.isTrue(this.host != null); Assert.isTrue(this.port >= 0, "Port must not be a negative number");
Assert.isTrue(this.port != -1); Assert.isTrue(this.httpHandler != null || this.handlerMap != null, "No HttpHandler configured");
Assert.isTrue(this.httpHandler != null || this.handlerMap != null); Assert.state(!this.running, "Cannot reconfigure while running");
Assert.isTrue(!this.running);
synchronized (this.lifecycleMonitor) {
initServer(); initServer();
} }
} }
@ -110,7 +110,7 @@ public abstract class AbstractHttpServer implements HttpServer {
try { try {
startInternal(); startInternal();
} }
catch (Exception ex) { catch (Throwable ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);
} }
} }
@ -128,7 +128,7 @@ public abstract class AbstractHttpServer implements HttpServer {
try { try {
stopInternal(); stopInternal();
} }
catch (Exception ex) { catch (Throwable ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);
} }
finally { finally {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,6 @@
package org.springframework.http.server.reactive.bootstrap; package org.springframework.http.server.reactive.bootstrap;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.Lifecycle; import org.springframework.context.Lifecycle;
import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.HttpHandler;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,7 +43,7 @@ public class TomcatHttpServer extends AbstractHttpServer {
} }
public TomcatHttpServer(String baseDir, Class<?> wsListener) { public TomcatHttpServer(String baseDir, Class<?> wsListener) {
Assert.notNull(baseDir); Assert.notNull(baseDir, "Base dir must not be null");
this.baseDir = baseDir; this.baseDir = baseDir;
this.wsListener = wsListener; this.wsListener = wsListener;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -61,7 +61,7 @@ public class MockAsyncContext implements AsyncContext {
public void addDispatchHandler(Runnable handler) { public void addDispatchHandler(Runnable handler) {
Assert.notNull(handler); Assert.notNull(handler, "Dispatch handler must not be null");
this.dispatchHandlers.add(handler); this.dispatchHandlers.add(handler);
} }
@ -77,7 +77,7 @@ public class MockAsyncContext implements AsyncContext {
@Override @Override
public boolean hasOriginalRequestAndResponse() { public boolean hasOriginalRequestAndResponse() {
return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse); return (this.request instanceof MockHttpServletRequest && this.response instanceof MockHttpServletResponse);
} }
@Override @Override
@ -112,8 +112,8 @@ public class MockAsyncContext implements AsyncContext {
try { try {
listener.onComplete(new AsyncEvent(this, this.request, this.response)); listener.onComplete(new AsyncEvent(this, this.request, this.response));
} }
catch (IOException e) { catch (IOException ex) {
throw new IllegalStateException("AsyncListener failure", e); throw new IllegalStateException("AsyncListener failure", ex);
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -356,12 +356,12 @@ public class MockPageContext extends PageContext {
} }
public byte[] getContentAsByteArray() { public byte[] getContentAsByteArray() {
Assert.isTrue(this.response instanceof MockHttpServletResponse); Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");
return ((MockHttpServletResponse) this.response).getContentAsByteArray(); return ((MockHttpServletResponse) this.response).getContentAsByteArray();
} }
public String getContentAsString() throws UnsupportedEncodingException { public String getContentAsString() throws UnsupportedEncodingException {
Assert.isTrue(this.response instanceof MockHttpServletResponse); Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");
return ((MockHttpServletResponse) this.response).getContentAsString(); return ((MockHttpServletResponse) this.response).getContentAsString();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.util; package org.springframework.web.util;
import java.net.URI; import java.net.URI;
@ -21,13 +22,14 @@ import java.util.Map;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
/** /**
* Unit tests for {@link DefaultUriTemplateHandler}. * Unit tests for {@link DefaultUriTemplateHandler}.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
@SuppressWarnings("deprecation")
public class DefaultUriTemplateHandlerTests { public class DefaultUriTemplateHandlerTests {
private final DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler(); private final DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -190,7 +190,7 @@ public abstract class HttpServletBean extends HttpServlet
*/ */
@Override @Override
public void setEnvironment(Environment environment) { public void setEnvironment(Environment environment) {
Assert.isInstanceOf(ConfigurableEnvironment.class, environment); Assert.isInstanceOf(ConfigurableEnvironment.class, environment, "ConfigurableEnvironment required");
this.environment = (ConfigurableEnvironment) environment; this.environment = (ConfigurableEnvironment) environment;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2016 the original author or authors. * Copyright 2002-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -679,8 +679,8 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private final String mappingName; private final String mappingName;
public MappingRegistration(T mapping, HandlerMethod handlerMethod, List<String> directUrls, String mappingName) { public MappingRegistration(T mapping, HandlerMethod handlerMethod, List<String> directUrls, String mappingName) {
Assert.notNull(mapping); Assert.notNull(mapping, "Mapping must not be null");
Assert.notNull(handlerMethod); Assert.notNull(handlerMethod, "HandlerMethod must not be null");
this.mapping = mapping; this.mapping = mapping;
this.handlerMethod = handlerMethod; this.handlerMethod = handlerMethod;
this.directUrls = (directUrls != null ? directUrls : Collections.emptyList()); this.directUrls = (directUrls != null ? directUrls : Collections.emptyList());
@ -745,7 +745,7 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private static class EmptyHandler { private static class EmptyHandler {
public void handle() { public void handle() {
throw new UnsupportedOperationException("not implemented"); throw new UnsupportedOperationException("Not implemented");
} }
} }

View File

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

Some files were not shown because too many files have changed in this diff Show More