Polishing

This commit is contained in:
Juergen Hoeller 2014-07-28 22:47:22 +02:00
parent 84a4433898
commit 9ad6618207
23 changed files with 213 additions and 198 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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,7 +35,7 @@ import org.springframework.context.annotation.Role;
@Configuration @Configuration
public class AspectJCachingConfiguration extends AbstractCachingConfiguration { public class AspectJCachingConfiguration extends AbstractCachingConfiguration {
@Bean(name=AnnotationConfigUtils.CACHE_ASPECT_BEAN_NAME) @Bean(name = AnnotationConfigUtils.CACHE_ASPECT_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AnnotationCacheAspect cacheAspect() { public AnnotationCacheAspect cacheAspect() {
AnnotationCacheAspect cacheAspect = AnnotationCacheAspect.aspectOf(); AnnotationCacheAspect cacheAspect = AnnotationCacheAspect.aspectOf();
@ -47,4 +47,5 @@ public class AspectJCachingConfiguration extends AbstractCachingConfiguration {
} }
return cacheAspect; return cacheAspect;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2014 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.
@ -37,7 +37,7 @@ import org.springframework.scheduling.annotation.EnableAsync;
@Configuration @Configuration
public class AspectJAsyncConfiguration extends AbstractAsyncConfiguration { public class AspectJAsyncConfiguration extends AbstractAsyncConfiguration {
@Bean(name=AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME) @Bean(name = AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AnnotationAsyncExecutionAspect asyncAdvisor() { public AnnotationAsyncExecutionAspect asyncAdvisor() {
AnnotationAsyncExecutionAspect asyncAspect = AnnotationAsyncExecutionAspect.aspectOf(); AnnotationAsyncExecutionAspect asyncAspect = AnnotationAsyncExecutionAspect.aspectOf();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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.
@ -37,7 +37,7 @@ import org.springframework.transaction.config.TransactionManagementConfigUtils;
@Configuration @Configuration
public class AspectJTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration { public class AspectJTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
@Bean(name=TransactionManagementConfigUtils.TRANSACTION_ASPECT_BEAN_NAME) @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ASPECT_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AnnotationTransactionAspect transactionAspect() { public AnnotationTransactionAspect transactionAspect() {
AnnotationTransactionAspect txAspect = AnnotationTransactionAspect.aspectOf(); AnnotationTransactionAspect txAspect = AnnotationTransactionAspect.aspectOf();
@ -46,4 +46,5 @@ public class AspectJTransactionManagementConfiguration extends AbstractTransacti
} }
return txAspect; return txAspect;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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.
@ -37,11 +37,11 @@ import org.springframework.context.annotation.Role;
@Configuration @Configuration
public class ProxyCachingConfiguration extends AbstractCachingConfiguration { public class ProxyCachingConfiguration extends AbstractCachingConfiguration {
@Bean(name=AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME) @Bean(name = AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanFactoryCacheOperationSourceAdvisor cacheAdvisor() { public BeanFactoryCacheOperationSourceAdvisor cacheAdvisor() {
BeanFactoryCacheOperationSourceAdvisor advisor = BeanFactoryCacheOperationSourceAdvisor advisor =
new BeanFactoryCacheOperationSourceAdvisor(); new BeanFactoryCacheOperationSourceAdvisor();
advisor.setCacheOperationSource(cacheOperationSource()); advisor.setCacheOperationSource(cacheOperationSource());
advisor.setAdvice(cacheInterceptor()); advisor.setAdvice(cacheInterceptor());
advisor.setOrder(this.enableCaching.<Integer>getNumber("order")); advisor.setOrder(this.enableCaching.<Integer>getNumber("order"));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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,7 @@
package org.springframework.cache.config; package org.springframework.cache.config;
import static org.springframework.context.annotation.AnnotationConfigUtils.*; import org.w3c.dom.Element;
import org.springframework.aop.config.AopNamespaceUtils; import org.springframework.aop.config.AopNamespaceUtils;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
@ -26,10 +26,9 @@ import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.cache.annotation.AnnotationCacheOperationSource;
import org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor; import org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor;
import org.springframework.cache.interceptor.CacheInterceptor; import org.springframework.cache.interceptor.CacheInterceptor;
import org.w3c.dom.Element; import org.springframework.context.annotation.AnnotationConfigUtils;
/** /**
* {@link org.springframework.beans.factory.xml.BeanDefinitionParser} * {@link org.springframework.beans.factory.xml.BeanDefinitionParser}
@ -83,13 +82,13 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
* </pre> * </pre>
*/ */
private void registerCacheAspect(Element element, ParserContext parserContext) { private void registerCacheAspect(Element element, ParserContext parserContext) {
if (!parserContext.getRegistry().containsBeanDefinition(CACHE_ASPECT_BEAN_NAME)) { if (!parserContext.getRegistry().containsBeanDefinition(AnnotationConfigUtils.CACHE_ASPECT_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(); RootBeanDefinition def = new RootBeanDefinition();
def.setBeanClassName(CACHE_ASPECT_CLASS_NAME); def.setBeanClassName(AnnotationConfigUtils.CACHE_ASPECT_CLASS_NAME);
def.setFactoryMethodName("aspectOf"); def.setFactoryMethodName("aspectOf");
parseCacheManagerProperty(element, def); parseCacheManagerProperty(element, def);
CacheNamespaceHandler.parseKeyGenerator(element, def); CacheNamespaceHandler.parseKeyGenerator(element, def);
parserContext.registerBeanComponent(new BeanComponentDefinition(def, CACHE_ASPECT_BEAN_NAME)); parserContext.registerBeanComponent(new BeanComponentDefinition(def, AnnotationConfigUtils.CACHE_ASPECT_BEAN_NAME));
} }
} }
@ -102,11 +101,11 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
public static void configureAutoProxyCreator(Element element, ParserContext parserContext) { public static void configureAutoProxyCreator(Element element, ParserContext parserContext) {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
if (!parserContext.getRegistry().containsBeanDefinition(CACHE_ADVISOR_BEAN_NAME)) { if (!parserContext.getRegistry().containsBeanDefinition(AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME)) {
Object eleSource = parserContext.extractSource(element); Object eleSource = parserContext.extractSource(element);
// Create the CacheOperationSource definition. // Create the CacheOperationSource definition.
RootBeanDefinition sourceDef = new RootBeanDefinition(AnnotationCacheOperationSource.class); RootBeanDefinition sourceDef = new RootBeanDefinition("org.springframework.cache.annotation.AnnotationCacheOperationSource");
sourceDef.setSource(eleSource); sourceDef.setSource(eleSource);
sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef); String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);
@ -129,15 +128,16 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
if (element.hasAttribute("order")) { if (element.hasAttribute("order")) {
advisorDef.getPropertyValues().add("order", element.getAttribute("order")); advisorDef.getPropertyValues().add("order", element.getAttribute("order"));
} }
parserContext.getRegistry().registerBeanDefinition(CACHE_ADVISOR_BEAN_NAME, advisorDef); parserContext.getRegistry().registerBeanDefinition(AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME, advisorDef);
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(),
eleSource); eleSource);
compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName)); compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName));
compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName)); compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName));
compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, CACHE_ADVISOR_BEAN_NAME)); compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME));
parserContext.registerComponent(compositeDef); parserContext.registerComponent(compositeDef);
} }
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2014 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 org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.cache.annotation.AnnotationCacheOperationSource;
import org.springframework.cache.interceptor.CacheEvictOperation; import org.springframework.cache.interceptor.CacheEvictOperation;
import org.springframework.cache.interceptor.CacheInterceptor; import org.springframework.cache.interceptor.CacheInterceptor;
import org.springframework.cache.interceptor.CacheOperation; import org.springframework.cache.interceptor.CacheOperation;
@ -78,8 +77,8 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
} }
else { else {
// Assume annotations source. // Assume annotations source.
builder.addPropertyValue("cacheOperationSources", new RootBeanDefinition( builder.addPropertyValue("cacheOperationSources",
AnnotationCacheOperationSource.class)); new RootBeanDefinition("org.springframework.cache.annotation.AnnotationCacheOperationSource"));
} }
} }
@ -170,7 +169,7 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
private static String getAttributeValue(Element element, String attributeName, String defaultValue) { private static String getAttributeValue(Element element, String attributeName, String defaultValue) {
String attribute = element.getAttribute(attributeName); String attribute = element.getAttribute(attributeName);
if(StringUtils.hasText(attribute)) { if (StringUtils.hasText(attribute)) {
return attribute.trim(); return attribute.trim();
} }
return defaultValue; return defaultValue;

View File

@ -93,60 +93,6 @@ public class AnnotationConfigUtils {
public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME = public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalCommonAnnotationProcessor"; "org.springframework.context.annotation.internalCommonAnnotationProcessor";
/**
* The bean name of the internally managed Scheduled annotation processor.
*/
public static final String SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalScheduledAnnotationProcessor";
/**
* The bean name of the internally managed Async annotation processor.
*/
public static final String ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalAsyncAnnotationProcessor";
/**
* The bean name of the internally managed AspectJ async execution aspect.
*/
public static final String ASYNC_EXECUTION_ASPECT_BEAN_NAME =
"org.springframework.scheduling.config.internalAsyncExecutionAspect";
/**
* The class name of the AspectJ async execution aspect.
*/
public static final String ASYNC_EXECUTION_ASPECT_CLASS_NAME =
"org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect";
/**
* The name of the AspectJ async execution aspect @{@code Configuration} class.
*/
public static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
/**
* The bean name of the internally managed cache advisor.
*/
public static final String CACHE_ADVISOR_BEAN_NAME =
"org.springframework.cache.config.internalCacheAdvisor";
/**
* The bean name of the internally managed cache aspect.
*/
public static final String CACHE_ASPECT_BEAN_NAME =
"org.springframework.cache.config.internalCacheAspect";
/**
* The class name of the AspectJ caching aspect.
*/
public static final String CACHE_ASPECT_CLASS_NAME =
"org.springframework.cache.aspectj.AnnotationCacheAspect";
/**
* The name of the AspectJ caching aspect @{@code Configuration} class.
*/
public static final String CACHE_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.cache.aspectj.AspectJCachingConfiguration";
/** /**
* The bean name of the internally managed JPA annotation processor. * The bean name of the internally managed JPA annotation processor.
*/ */
@ -158,6 +104,79 @@ public class AnnotationConfigUtils {
"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"; "org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor";
/**
* The bean name of the internally managed Scheduled annotation processor.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalScheduledAnnotationProcessor";
/**
* The bean name of the internally managed Async annotation processor.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalAsyncAnnotationProcessor";
/**
* The bean name of the internally managed AspectJ async execution aspect.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String ASYNC_EXECUTION_ASPECT_BEAN_NAME =
"org.springframework.scheduling.config.internalAsyncExecutionAspect";
/**
* The class name of the AspectJ async execution aspect.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String ASYNC_EXECUTION_ASPECT_CLASS_NAME =
"org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect";
/**
* The name of the AspectJ async execution aspect @{@code Configuration} class.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
/**
* The bean name of the internally managed cache advisor.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String CACHE_ADVISOR_BEAN_NAME =
"org.springframework.cache.config.internalCacheAdvisor";
/**
* The bean name of the internally managed cache aspect.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String CACHE_ASPECT_BEAN_NAME =
"org.springframework.cache.config.internalCacheAspect";
/**
* The class name of the AspectJ caching aspect.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String CACHE_ASPECT_CLASS_NAME =
"org.springframework.cache.aspectj.AnnotationCacheAspect";
/**
* The name of the AspectJ caching aspect @{@code Configuration} class.
* <p>ATTENTION:</p> This constant is meant for internal use only. The value is stable
* but don't rely on the presence of this constant declaration; rather copy the value.
*/
public static final String CACHE_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.cache.aspectj.AspectJCachingConfiguration";
private static final boolean jsr250Present = private static final boolean jsr250Present =
ClassUtils.isPresent("javax.annotation.Resource", AnnotationConfigUtils.class.getClassLoader()); ClassUtils.isPresent("javax.annotation.Resource", AnnotationConfigUtils.class.getClassLoader());

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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.
@ -28,7 +28,6 @@ import org.springframework.context.annotation.AnnotationConfigUtils;
* @since 3.1 * @since 3.1
* @see EnableAsync * @see EnableAsync
* @see ProxyAsyncConfiguration * @see ProxyAsyncConfiguration
* @see AnnotationConfigUtils#ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME
*/ */
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> { public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2014 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.
@ -38,7 +38,7 @@ import org.springframework.util.Assert;
@Configuration @Configuration
public class ProxyAsyncConfiguration extends AbstractAsyncConfiguration { public class ProxyAsyncConfiguration extends AbstractAsyncConfiguration {
@Bean(name=AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME) @Bean(name = AnnotationConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AsyncAnnotationBeanPostProcessor asyncAdvisor() { public AsyncAnnotationBeanPostProcessor asyncAdvisor() {
Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected"); Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2014 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.
@ -57,7 +57,7 @@ import org.springframework.util.StringValueResolver;
* <p>Auto-detects any {@link SchedulingConfigurer} instances in the container, * <p>Auto-detects any {@link SchedulingConfigurer} instances in the container,
* allowing for customization of the scheduler to be used or for fine-grained control * allowing for customization of the scheduler to be used or for fine-grained control
* over task registration (e.g. registration of {@link Trigger} tasks. * over task registration (e.g. registration of {@link Trigger} tasks.
* See @{@link EnableScheduling} Javadoc for complete usage details. * See the @{@link EnableScheduling} javadocs for complete usage details.
* *
* @author Mark Fisher * @author Mark Fisher
* @author Juergen Hoeller * @author Juergen Hoeller
@ -82,6 +82,11 @@ public class ScheduledAnnotationBeanPostProcessor
private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar(); private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
/** /**
* Set the {@link org.springframework.scheduling.TaskScheduler} that will invoke * Set the {@link org.springframework.scheduling.TaskScheduler} that will invoke
* the scheduled methods, or a {@link java.util.concurrent.ScheduledExecutorService} * the scheduled methods, or a {@link java.util.concurrent.ScheduledExecutorService}
@ -101,11 +106,47 @@ public class ScheduledAnnotationBeanPostProcessor
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
@Override @Override
public int getOrder() { public void onApplicationEvent(ContextRefreshedEvent event) {
return LOWEST_PRECEDENCE; if (event.getApplicationContext() != this.applicationContext) {
return;
}
if (this.scheduler != null) {
this.registrar.setScheduler(this.scheduler);
}
Map<String, SchedulingConfigurer> configurers =
this.applicationContext.getBeansOfType(SchedulingConfigurer.class);
for (SchedulingConfigurer configurer : configurers.values()) {
configurer.configureTasks(this.registrar);
}
if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
Map<String, ? super Object> schedulers = new HashMap<String, Object>();
schedulers.putAll(this.applicationContext.getBeansOfType(TaskScheduler.class));
schedulers.putAll(this.applicationContext.getBeansOfType(ScheduledExecutorService.class));
if (schedulers.size() == 0) {
// do nothing -> fall back to default scheduler
}
else if (schedulers.size() == 1) {
this.registrar.setScheduler(schedulers.values().iterator().next());
}
else if (schedulers.size() >= 2){
throw new IllegalStateException(
"More than one TaskScheduler and/or ScheduledExecutorService " +
"exist within the context. Remove all but one of the beans; or " +
"implement the SchedulingConfigurer interface and call " +
"ScheduledTaskRegistrar#setScheduler explicitly within the " +
"configureTasks() callback. Found the following beans: " + schedulers.keySet());
}
}
this.registrar.afterPropertiesSet();
} }
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) { public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean; return bean;
@ -254,44 +295,6 @@ public class ScheduledAnnotationBeanPostProcessor
} }
} }
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext() != this.applicationContext) {
return;
}
if (this.scheduler != null) {
this.registrar.setScheduler(this.scheduler);
}
Map<String, SchedulingConfigurer> configurers =
this.applicationContext.getBeansOfType(SchedulingConfigurer.class);
for (SchedulingConfigurer configurer : configurers.values()) {
configurer.configureTasks(this.registrar);
}
if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
Map<String, ? super Object> schedulers = new HashMap<String, Object>();
schedulers.putAll(this.applicationContext.getBeansOfType(TaskScheduler.class));
schedulers.putAll(this.applicationContext.getBeansOfType(ScheduledExecutorService.class));
if (schedulers.size() == 0) {
// do nothing -> fall back to default scheduler
}
else if (schedulers.size() == 1) {
this.registrar.setScheduler(schedulers.values().iterator().next());
}
else if (schedulers.size() >= 2){
throw new IllegalStateException(
"More than one TaskScheduler and/or ScheduledExecutorService " +
"exist within the context. Remove all but one of the beans; or " +
"implement the SchedulingConfigurer interface and call " +
"ScheduledTaskRegistrar#setScheduler explicitly within the " +
"configureTasks() callback. Found the following beans: " + schedulers.keySet());
}
}
this.registrar.afterPropertiesSet();
}
@Override @Override
public void destroy() { public void destroy() {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2011 the original author or authors. * Copyright 2002-2014 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,7 @@ import org.springframework.context.annotation.Role;
@Configuration @Configuration
public class SchedulingConfiguration { public class SchedulingConfiguration {
@Bean(name=AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME) @Bean(name = AnnotationConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() { public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
return new ScheduledAnnotationBeanPostProcessor(); return new ScheduledAnnotationBeanPostProcessor();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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,9 +136,8 @@ public class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParse
if (StringUtils.hasText(executor)) { if (StringUtils.hasText(executor)) {
builder.addPropertyReference("executor", executor); builder.addPropertyReference("executor", executor);
} }
parserContext.registerBeanComponent( parserContext.registerBeanComponent(new BeanComponentDefinition(builder.getBeanDefinition(),
new BeanComponentDefinition(builder.getBeanDefinition(), AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME));
AnnotationConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME));
} }
} }

View File

@ -48,7 +48,7 @@ import org.springframework.util.ReflectionUtils;
*/ */
abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor { abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor {
protected final Log logger = LogFactory.getLog(this.getClass()); protected final Log logger = LogFactory.getLog(getClass());
protected final AnnotationAttributes attributes; protected final AnnotationAttributes attributes;
@ -94,10 +94,10 @@ abstract class AbstractRecursiveAnnotationVisitor extends AnnotationVisitor {
} }
} }
catch (ClassNotFoundException ex) { catch (ClassNotFoundException ex) {
this.logger.debug("Failed to classload enum type while reading annotation metadata", ex); logger.debug("Failed to classload enum type while reading annotation metadata", ex);
} }
catch (IllegalAccessException ex) { catch (IllegalAccessException ex) {
this.logger.warn("Could not access enum value while reading annotation metadata", ex); logger.warn("Could not access enum value while reading annotation metadata", ex);
} }
return valueToUse; return valueToUse;
} }
@ -169,7 +169,6 @@ class RecursiveAnnotationAttributesVisitor extends AbstractRecursiveAnnotationVi
private final String annotationType; private final String annotationType;
public RecursiveAnnotationAttributesVisitor(String annotationType, AnnotationAttributes attributes, public RecursiveAnnotationAttributesVisitor(String annotationType, AnnotationAttributes attributes,
ClassLoader classLoader) { ClassLoader classLoader) {
super(classLoader, attributes); super(classLoader, attributes);
@ -183,8 +182,8 @@ class RecursiveAnnotationAttributesVisitor extends AbstractRecursiveAnnotationVi
doVisitEnd(annotationClass); doVisitEnd(annotationClass);
} }
catch (ClassNotFoundException ex) { catch (ClassNotFoundException ex) {
this.logger.debug("Failed to class-load type while reading annotation metadata. " logger.debug("Failed to class-load type while reading annotation metadata. " +
+ "This is a non-fatal error, but certain annotation metadata may be unavailable.", ex); "This is a non-fatal error, but certain annotation metadata may be unavailable.", ex);
} }
} }
@ -246,7 +245,6 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
private final Map<String, Set<String>> metaAnnotationMap; private final Map<String, Set<String>> metaAnnotationMap;
public AnnotationAttributesReadingVisitor(String annotationType, public AnnotationAttributesReadingVisitor(String annotationType,
MultiValueMap<String, AnnotationAttributes> attributesMap, Map<String, Set<String>> metaAnnotationMap, MultiValueMap<String, AnnotationAttributes> attributesMap, Map<String, Set<String>> metaAnnotationMap,
ClassLoader classLoader) { ClassLoader classLoader) {
@ -257,7 +255,6 @@ final class AnnotationAttributesReadingVisitor extends RecursiveAnnotationAttrib
this.metaAnnotationMap = metaAnnotationMap; this.metaAnnotationMap = metaAnnotationMap;
} }
@Override @Override
public void doVisitEnd(Class<?> annotationClass) { public void doVisitEnd(Class<?> annotationClass) {
super.doVisitEnd(annotationClass); super.doVisitEnd(annotationClass);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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.
@ -19,8 +19,8 @@ package org.springframework.core.type.filter;
import java.io.IOException; import java.io.IOException;
import org.springframework.core.type.ClassMetadata; import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
/** /**
* Type filter that exposes a * Type filter that exposes a

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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.
@ -29,8 +29,8 @@ import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.SimpleScope; import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.patterns.TypePattern;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
/** /**
* Type filter that uses AspectJ type pattern for matching. * Type filter that uses AspectJ type pattern for matching.

View File

@ -143,9 +143,9 @@ public class GenericMessagingTemplate extends AbstractDestinationResolvingMessag
try { try {
doSend(channel, requestMessage); doSend(channel, requestMessage);
} }
catch (RuntimeException e) { catch (RuntimeException ex) {
tempReplyChannel.setSendFailed(true); tempReplyChannel.setSendFailed(true);
throw e; throw ex;
} }
Message<?> replyMessage = this.doReceive(tempReplyChannel); Message<?> replyMessage = this.doReceive(tempReplyChannel);
@ -177,7 +177,6 @@ public class GenericMessagingTemplate extends AbstractDestinationResolvingMessag
private volatile boolean hasSendFailed; private volatile boolean hasSendFailed;
public void setSendFailed(boolean hasSendError) { public void setSendFailed(boolean hasSendError) {
this.hasSendFailed = hasSendError; this.hasSendFailed = hasSendError;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2014 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,15 +58,15 @@ import org.springframework.util.ClassUtils;
*/ */
public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver { public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver {
private final ConversionService conversionService;
private final ConfigurableBeanFactory configurableBeanFactory; private final ConfigurableBeanFactory configurableBeanFactory;
private final BeanExpressionContext expressionContext; private final BeanExpressionContext expressionContext;
private Map<MethodParameter, NamedValueInfo> namedValueInfoCache = private final Map<MethodParameter, NamedValueInfo> namedValueInfoCache =
new ConcurrentHashMap<MethodParameter, NamedValueInfo>(256); new ConcurrentHashMap<MethodParameter, NamedValueInfo>(256);
private ConversionService conversionService;
/** /**
* Constructor with a {@link ConversionService} and a {@link BeanFactory}. * Constructor with a {@link ConversionService} and a {@link BeanFactory}.
@ -77,15 +77,14 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle
* values are not expected to contain expressions * values are not expected to contain expressions
*/ */
protected AbstractNamedValueMethodArgumentResolver(ConversionService cs, ConfigurableBeanFactory beanFactory) { protected AbstractNamedValueMethodArgumentResolver(ConversionService cs, ConfigurableBeanFactory beanFactory) {
this.conversionService = (cs != null) ? cs : new DefaultConversionService(); this.conversionService = (cs != null ? cs : new DefaultConversionService());
this.configurableBeanFactory = beanFactory; this.configurableBeanFactory = beanFactory;
this.expressionContext = (beanFactory != null) ? new BeanExpressionContext(beanFactory, null) : null; this.expressionContext = (beanFactory != null ? new BeanExpressionContext(beanFactory, null) : null);
} }
@Override @Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
Class<?> paramType = parameter.getParameterType(); Class<?> paramType = parameter.getParameterType();
NamedValueInfo namedValueInfo = getNamedValueInfo(parameter); NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
@ -99,7 +98,7 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle
} }
value = handleNullValue(namedValueInfo.name, value, paramType); value = handleNullValue(namedValueInfo.name, value, paramType);
} }
else if ("".equals(value) && (namedValueInfo.defaultValue != null)) { else if ("".equals(value) && namedValueInfo.defaultValue != null) {
value = resolveDefaultValue(namedValueInfo.defaultValue); value = resolveDefaultValue(namedValueInfo.defaultValue);
} }

View File

@ -21,6 +21,7 @@ import java.util.Map;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
@ -44,6 +45,7 @@ public class HeaderMethodArgumentResolver extends AbstractNamedValueMethodArgume
super(cs, beanFactory); super(cs, beanFactory);
} }
@Override @Override
public boolean supportsParameter(MethodParameter parameter) { public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(Header.class); return parameter.hasParameterAnnotation(Header.class);
@ -56,8 +58,8 @@ public class HeaderMethodArgumentResolver extends AbstractNamedValueMethodArgume
} }
@Override @Override
protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name)
String name) throws Exception { throws Exception {
Object headerValue = message.getHeaders().get(name); Object headerValue = message.getHeaders().get(name);
Object nativeHeaderValue = getNativeHeaderValue(message, name); Object nativeHeaderValue = getNativeHeaderValue(message, name);
@ -71,26 +73,19 @@ public class HeaderMethodArgumentResolver extends AbstractNamedValueMethodArgume
} }
} }
return (headerValue != null) ? headerValue : nativeHeaderValue; return (headerValue != null ? headerValue : nativeHeaderValue);
} }
private Object getNativeHeaderValue(Message<?> message, String name) { private Object getNativeHeaderValue(Message<?> message, String name) {
Map<String, List<String>> nativeHeaders = getNativeHeaders(message); Map<String, List<String>> nativeHeaders = getNativeHeaders(message);
if (name.startsWith("nativeHeaders.")) { if (name.startsWith("nativeHeaders.")) {
name = name.substring("nativeHeaders.".length()); name = name.substring("nativeHeaders.".length());
if (logger.isDebugEnabled()) {
logger.debug("Looking up native header '" + name + "'");
}
} }
if (nativeHeaders == null || !nativeHeaders.containsKey(name)) {
if ((nativeHeaders == null) || !nativeHeaders.containsKey(name)) {
return null; return null;
} }
List<?> nativeHeaderValues = nativeHeaders.get(name); List<?> nativeHeaderValues = nativeHeaders.get(name);
return (nativeHeaderValues.size() == 1) ? nativeHeaderValues.get(0) : nativeHeaderValues; return (nativeHeaderValues.size() == 1 ? nativeHeaderValues.get(0) : nativeHeaderValues);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -62,6 +62,7 @@ public class PayloadArgumentResolver implements HandlerMethodArgumentResolver {
this.validator = validator; this.validator = validator;
} }
@Override @Override
public boolean supportsParameter(MethodParameter parameter) { public boolean supportsParameter(MethodParameter parameter) {
return true; return true;
@ -69,14 +70,12 @@ public class PayloadArgumentResolver implements HandlerMethodArgumentResolver {
@Override @Override
public Object resolveArgument(MethodParameter param, Message<?> message) throws Exception { public Object resolveArgument(MethodParameter param, Message<?> message) throws Exception {
Payload annot = param.getParameterAnnotation(Payload.class); Payload annot = param.getParameterAnnotation(Payload.class);
if ((annot != null) && StringUtils.hasText(annot.value())) { if ((annot != null) && StringUtils.hasText(annot.value())) {
throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver."); throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
} }
Object payload = message.getPayload(); Object payload = message.getPayload();
if (isEmptyPayload(payload)) { if (isEmptyPayload(payload)) {
if (annot == null || annot.required()) { if (annot == null || annot.required()) {
String paramName = getParameterName(param); String paramName = getParameterName(param);
@ -122,7 +121,7 @@ public class PayloadArgumentResolver implements HandlerMethodArgumentResolver {
return ((byte[]) payload).length == 0; return ((byte[]) payload).length == 0;
} }
else if (payload instanceof String) { else if (payload instanceof String) {
return ((String) payload).trim().equals(""); return !StringUtils.hasText((String) payload);
} }
else { else {
return false; return false;
@ -130,14 +129,12 @@ public class PayloadArgumentResolver implements HandlerMethodArgumentResolver {
} }
protected void validate(Message<?> message, MethodParameter parameter, Object target) { protected void validate(Message<?> message, MethodParameter parameter, Object target) {
if (this.validator == null) { if (this.validator == null) {
return; return;
} }
for (Annotation annot : parameter.getParameterAnnotations()) { for (Annotation annot : parameter.getParameterAnnotations()) {
if (annot.annotationType().getSimpleName().startsWith("Valid")) { if (annot.annotationType().getSimpleName().startsWith("Valid")) {
BeanPropertyBindingResult bindingResult = BeanPropertyBindingResult bindingResult =
new BeanPropertyBindingResult(target, getParameterName(parameter)); new BeanPropertyBindingResult(target, getParameterName(parameter));

View File

@ -254,7 +254,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
resolvers.addAll(getCustomArgumentResolvers()); resolvers.addAll(getCustomArgumentResolvers());
resolvers.add(new PayloadArgumentResolver(this.messageConverter, resolvers.add(new PayloadArgumentResolver(this.messageConverter,
(this.validator != null ? this.validator : new NoopValidator()))); (this.validator != null ? this.validator : new NoOpValidator())));
return resolvers; return resolvers;
} }
@ -369,7 +369,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
} }
private static final class NoopValidator implements Validator { private static final class NoOpValidator implements Validator {
@Override @Override
public boolean supports(Class<?> clazz) { public boolean supports(Class<?> clazz) {

View File

@ -40,7 +40,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
@ -58,11 +57,11 @@ import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils; import org.springframework.web.util.UriUtils;
/** /**
* Default builder for {@link MockHttpServletRequest} required as input to * Default builder for {@link MockHttpServletRequest} required as input to perform
* perform request in {@link MockMvc}. * requests in {@link MockMvc}.
* *
* <p>Application tests will typically access this builder through the static * <p>Application tests will typically access this builder through the static factory
* factory methods in {@link MockMvcBuilders}. * methods in {@link org.springframework.test.web.servlet.setup.MockMvcBuilders}.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Arjen Poutsma * @author Arjen Poutsma
@ -427,6 +426,7 @@ public class MockHttpServletRequestBuilder implements RequestBuilder, Mergeable
return this; return this;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
* @return always returns {@code true}. * @return always returns {@code true}.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2013 the original author or authors. * Copyright 2002-2014 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,8 @@
package org.springframework.transaction.config; package org.springframework.transaction.config;
/** /**
* Configuration constants for internal sharing across subpackages.
*
* @author Chris Beams * @author Chris Beams
* @since 3.1 * @since 3.1
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2014 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,20 +18,21 @@ package org.springframework.web.filter;
import java.io.IOException; import java.io.IOException;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.junit.Before; import org.junit.Before;
import static org.junit.Assert.*; import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import static org.junit.Assert.*;
/** /**
* Test for {@link AbstractRequestLoggingFilter} and sub classes. * Test for {@link AbstractRequestLoggingFilter} and sub classes.
* *
@ -41,11 +42,13 @@ public class RequestLoggingFilterTests {
private MyRequestLoggingFilter filter; private MyRequestLoggingFilter filter;
@Before @Before
public void createFilter() throws Exception { public void createFilter() throws Exception {
filter = new MyRequestLoggingFilter(); filter = new MyRequestLoggingFilter();
} }
@Test @Test
public void uri() throws Exception { public void uri() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels"); final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
@ -53,17 +56,17 @@ public class RequestLoggingFilterTests {
request.setQueryString("booking=42"); request.setQueryString("booking=42");
FilterChain filterChain = new NoopFilterChain(); FilterChain filterChain = new NoOpFilterChain();
filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain);
assertNotNull(filter.beforeRequestMessage); assertNotNull(filter.beforeRequestMessage);
assertTrue(filter.beforeRequestMessage.indexOf("uri=/hotel") != -1); assertTrue(filter.beforeRequestMessage.contains("uri=/hotel"));
assertFalse(filter.beforeRequestMessage.indexOf("booking=42") != -1); assertFalse(filter.beforeRequestMessage.contains("booking=42"));
assertNotNull(filter.afterRequestMessage); assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("uri=/hotel") != -1); assertTrue(filter.afterRequestMessage.contains("uri=/hotel"));
assertFalse(filter.afterRequestMessage.indexOf("booking=42") != -1); assertFalse(filter.afterRequestMessage.contains("booking=42"));
} }
@Test @Test
@ -75,15 +78,15 @@ public class RequestLoggingFilterTests {
request.setQueryString("booking=42"); request.setQueryString("booking=42");
FilterChain filterChain = new NoopFilterChain(); FilterChain filterChain = new NoOpFilterChain();
filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain);
assertNotNull(filter.beforeRequestMessage); assertNotNull(filter.beforeRequestMessage);
assertTrue(filter.beforeRequestMessage.indexOf("uri=/hotels?booking=42") != -1); assertTrue(filter.beforeRequestMessage.contains("uri=/hotels?booking=42"));
assertNotNull(filter.afterRequestMessage); assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("uri=/hotels?booking=42") != -1); assertTrue(filter.afterRequestMessage.contains("uri=/hotels?booking=42"));
} }
@Test @Test
@ -109,7 +112,7 @@ public class RequestLoggingFilterTests {
filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain);
assertNotNull(filter.afterRequestMessage); assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("Hello World") != -1); assertTrue(filter.afterRequestMessage.contains("Hello World"));
} }
@Test @Test
@ -135,7 +138,7 @@ public class RequestLoggingFilterTests {
filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain);
assertNotNull(filter.afterRequestMessage); assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf(requestBody) != -1); assertTrue(filter.afterRequestMessage.contains(requestBody));
} }
@Test @Test
@ -162,10 +165,11 @@ public class RequestLoggingFilterTests {
filter.doFilter(request, response, filterChain); filter.doFilter(request, response, filterChain);
assertNotNull(filter.afterRequestMessage); assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("Hel") != -1); assertTrue(filter.afterRequestMessage.contains("Hel"));
assertFalse(filter.afterRequestMessage.indexOf("Hello World") != -1); assertFalse(filter.afterRequestMessage.contains("Hello World"));
} }
private static class MyRequestLoggingFilter extends AbstractRequestLoggingFilter { private static class MyRequestLoggingFilter extends AbstractRequestLoggingFilter {
private String beforeRequestMessage; private String beforeRequestMessage;
@ -183,7 +187,8 @@ public class RequestLoggingFilterTests {
} }
} }
private static class NoopFilterChain implements FilterChain {
private static class NoOpFilterChain implements FilterChain {
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {