From b0790bf5e7b6091552ccf17a2e707ab438d129d7 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 27 Nov 2008 00:27:52 +0000 Subject: [PATCH] Java 5 code style --- .../aspectj/AspectJExpressionPointcut.java | 14 +- .../annotation/AspectJProxyFactory.java | 6 +- .../AbstractSingletonProxyFactoryBean.java | 23 +- .../aop/framework/AdvisedSupport.java | 6 +- .../aop/framework/Cglib2AopProxy.java | 85 +++--- .../aop/framework/ProxyFactory.java | 14 +- .../aop/framework/ProxyFactoryBean.java | 39 ++- .../framework/ReflectiveMethodInvocation.java | 14 +- .../adapter/ThrowsAdviceInterceptor.java | 12 +- ...erTargetObjectIntroductionInterceptor.java | 6 +- .../aop/target/ThreadLocalTargetSource.java | 16 +- .../org/springframework/beans/BeanUtils.java | 28 +- .../beans/BeanWrapperImpl.java | 12 +- .../beans/DirectFieldAccessor.java | 8 +- .../beans/factory/ListableBeanFactory.java | 39 +++ .../access/SingletonBeanFactoryLocator.java | 17 +- .../factory/config/AbstractFactoryBean.java | 27 +- .../beans/factory/config/ListFactoryBean.java | 6 +- .../beans/factory/config/MapFactoryBean.java | 6 +- .../factory/config/PropertiesFactoryBean.java | 29 +-- .../beans/factory/config/SetFactoryBean.java | 6 +- .../generic/GenericBeanFactoryAccessor.java | 140 ---------- .../beans/factory/generic/package.html | 8 - .../factory/support/AbstractBeanFactory.java | 7 +- .../support/DefaultListableBeanFactory.java | 40 +++ .../support/StaticListableBeanFactory.java | 33 ++- .../xml/DefaultNamespaceHandlerResolver.java | 10 +- .../ArgumentConvertingMethodInvoker.java | 6 +- .../mail/MailSendException.java | 25 +- .../mail/SimpleMailMessage.java | 4 +- .../mail/javamail/JavaMailSenderImpl.java | 19 +- .../ui/velocity/VelocityEngineFactory.java | 25 +- .../ContextSingletonBeanFactoryLocator.java | 6 +- .../support/AbstractApplicationContext.java | 22 +- .../support/ContextTypeMatchClassLoader.java | 4 +- .../context/support/MessageSourceSupport.java | 4 +- ...ReloadableResourceBundleMessageSource.java | 11 +- .../support/ResourceBundleMessageSource.java | 26 +- .../support/ResourceMapFactoryBean.java | 100 -------- ...bstractConfigurableMBeanInfoAssembler.java | 30 +-- .../InterfaceBasedMBeanInfoAssembler.java | 21 +- .../MethodExclusionMBeanInfoAssembler.java | 12 +- .../MethodNameBasedMBeanInfoAssembler.java | 14 +- .../springframework/jndi/JndiCallback.java | 16 +- .../jndi/JndiLocatorSupport.java | 4 +- .../springframework/jndi/JndiTemplate.java | 8 +- .../jndi/support/SimpleJndiBeanFactory.java | 21 +- .../remoting/support/RemoteInvocation.java | 12 +- .../support/SimpleHttpServerFactoryBean.java | 3 +- .../validation/BindException.java | 12 +- .../validation/DataBinder.java | 18 +- .../core/AttributeAccessorSupport.java | 11 +- .../core/BridgeMethodResolver.java | 26 +- .../core/GenericCollectionTypeResolver.java | 13 +- .../core/GenericTypeResolver.java | 31 +-- .../springframework/core/MethodParameter.java | 4 +- .../core/task/TaskExecutor.java | 13 +- .../core/task/TaskRejectedException.java | 6 +- .../support/ConcurrentExecutorAdapter.java | 15 +- .../util/WeakReferenceMonitor.java | 11 +- .../util/comparator/BooleanComparator.java | 8 +- .../util/comparator/ComparableComparator.java | 10 +- .../util/comparator/CompoundComparator.java | 35 ++- .../util/comparator/InvertibleComparator.java | 12 +- .../util/comparator/NullSafeComparator.java | 12 +- .../expression/spel/SpelUtilities.java | 2 +- .../spel/ast/CompoundExpression.java | 2 +- .../expression/spel/ast/Operator.java | 8 +- .../expression/spel/ast/Projection.java | 2 +- .../expression/spel/ast/Selection.java | 2 +- .../expression/spel/TestScenarioCreator.java | 2 +- .../jdbc/core/BeanPropertyRowMapper.java | 35 ++- .../jdbc/core/CallableStatementCallback.java | 12 +- .../core/CallableStatementCreatorFactory.java | 26 +- .../jdbc/core/ColumnMapRowMapper.java | 11 +- .../jdbc/core/ConnectionCallback.java | 12 +- .../jdbc/core/JdbcOperations.java | 67 ++--- .../jdbc/core/JdbcTemplate.java | 242 +++++++++--------- .../jdbc/core/ParameterMapper.java | 4 +- .../jdbc/core/PreparedStatementCallback.java | 12 +- .../core/PreparedStatementCreatorFactory.java | 44 ++-- .../jdbc/core/ResultSetExtractor.java | 6 +- .../core/ResultSetSupportingSqlParameter.java | 2 +- .../springframework/jdbc/core/RowMapper.java | 4 +- .../core/RowMapperResultSetExtractor.java | 14 +- .../jdbc/core/SingleColumnRowMapper.java | 15 +- .../jdbc/core/SqlParameter.java | 14 +- .../core/SqlRowSetResultSetExtractor.java | 15 +- .../jdbc/core/StatementCallback.java | 12 +- .../jdbc/core/StatementCreatorUtils.java | 49 ++-- .../namedparam/MapSqlParameterSource.java | 6 +- .../NamedParameterJdbcOperations.java | 52 ++-- .../NamedParameterJdbcTemplate.java | 85 +++--- .../core/namedparam/NamedParameterUtils.java | 4 +- .../ParameterizedBeanPropertyRowMapper.java | 21 +- .../core/simple/ParameterizedRowMapper.java | 20 +- .../ParameterizedSingleColumnRowMapper.java | 21 +- .../core/simple/SimpleJdbcOperations.java | 142 +++++----- .../jdbc/core/simple/SimpleJdbcTemplate.java | 40 +-- .../core/support/AbstractSqlTypeValue.java | 4 +- .../TransactionAwareDataSourceProxy.java | 6 +- .../lookup/MapDataSourceLookup.java | 22 +- .../jdbc/support/GeneratedKeyHolder.java | 18 +- .../jdbc/support/JdbcUtils.java | 2 +- .../jdbc/support/KeyHolder.java | 13 +- .../AbstractDataFieldMaxValueIncrementer.java | 8 +- .../jms/core/BrowserCallback.java | 4 +- .../jms/core/JmsOperations.java | 20 +- .../springframework/jms/core/JmsTemplate.java | 38 +-- .../jms/core/ProducerCallback.java | 4 +- .../jms/core/SessionCallback.java | 6 +- .../DefaultMessageListenerContainer.java | 4 +- .../FilterDefinitionFactoryBean.java | 33 ++- .../orm/hibernate3/HibernateOperations.java | 20 +- .../orm/hibernate3/HibernateTemplate.java | 47 ++-- .../orm/hibernate3/SessionHolder.java | 12 +- .../LocalPersistenceManagerFactoryBean.java | 17 +- .../jpa/AbstractEntityManagerFactoryBean.java | 10 +- .../orm/jpa/EntityManagerFactoryAccessor.java | 8 +- .../orm/jpa/JpaOperations.java | 6 +- .../orm/jpa/JpaTransactionManager.java | 12 +- .../orm/jpa/JpaVendorAdapter.java | 2 +- .../jpa/vendor/AbstractJpaVendorAdapter.java | 3 +- .../vendor/EclipseLinkJpaVendorAdapter.java | 17 +- .../jpa/vendor/HibernateJpaVendorAdapter.java | 13 +- .../orm/jpa/vendor/OpenJpaVendorAdapter.java | 16 +- .../jpa/vendor/TopLinkJpaVendorAdapter.java | 15 +- .../mock/jndi/SimpleNamingContext.java | 50 ++-- .../mock/web/HeaderValueHolder.java | 16 +- .../mock/web/MockFilterConfig.java | 15 +- .../mock/web/MockHttpServletRequest.java | 29 +-- .../mock/web/MockHttpServletResponse.java | 21 +- .../mock/web/MockHttpSession.java | 33 +-- .../web/MockMultipartHttpServletRequest.java | 10 +- .../mock/web/MockPageContext.java | 16 +- .../mock/web/MockServletConfig.java | 21 +- .../mock/web/MockServletContext.java | 43 ++-- .../mock/web/portlet/MockActionResponse.java | 17 +- .../portlet/MockMultipartActionRequest.java | 10 +- .../mock/web/portlet/MockPortalContext.java | 43 ++-- .../mock/web/portlet/MockPortletConfig.java | 20 +- .../mock/web/portlet/MockPortletContext.java | 32 +-- .../web/portlet/MockPortletPreferences.java | 14 +- .../mock/web/portlet/MockPortletRequest.java | 71 +++-- .../mock/web/portlet/MockPortletResponse.java | 12 +- .../mock/web/portlet/MockPortletSession.java | 21 +- .../mock/web/portlet/MockPortletURL.java | 61 +++-- ...DependencyInjectionSpringContextTests.java | 3 + .../AbstractSingleSpringContextTests.java | 3 + .../test/AbstractSpringContextTests.java | 49 ++-- ...sactionalDataSourceSpringContextTests.java | 3 + ...stractTransactionalSpringContextTests.java | 134 ++++------ .../springframework/test/AssertThrows.java | 18 +- .../test/ConditionalTestCase.java | 5 +- .../test/jdbc/JdbcTestUtils.java | 18 +- .../test/jdbc/SimpleJdbcTestUtils.java | 11 +- .../test/web/AbstractModelAndViewTests.java | 31 +-- .../test/web/ModelAndViewAssert.java | 130 ++++------ .../GenericBeanFactoryAccessorTests.java | 78 ------ .../beans/factory/generic/MyAnnotation.java | 32 --- .../factory/generic/SomeAnnotatedBean.java | 26 -- .../genericBeanFactoryAccessorTests.xml | 10 - .../support/ResourceMapFactoryBeanTests.java | 75 ------ .../core/BridgeMethodResolverTests.java | 3 +- ...ationTransactionNamespaceHandlerTests.java | 4 +- .../AbstractJasperReportsTests.java | 8 +- .../JasperReportsMultiFormatViewTests.java | 24 +- ...ultiFormatViewWithCustomMappingsTests.java | 19 +- .../view/velocity/VelocityViewTests.java | 15 +- .../dao/support/DataAccessUtils.java | 19 +- .../jca/cci/core/CciOperations.java | 10 +- .../jca/cci/core/CciTemplate.java | 46 ++-- .../jca/cci/core/ConnectionCallback.java | 12 +- .../jca/cci/core/InteractionCallback.java | 12 +- .../jca/cci/core/RecordExtractor.java | 12 +- .../web/portlet/DispatcherPortlet.java | 4 +- .../web/portlet/ModelAndView.java | 10 +- ...PortletContextResourcePatternResolver.java | 10 +- .../AbstractMapBasedHandlerMapping.java | 35 +-- .../handler/ParameterHandlerMapping.java | 28 +- .../handler/PortletModeHandlerMapping.java | 35 +-- .../PortletModeParameterHandlerMapping.java | 93 ++----- .../PortletModeParameterLookupKey.java | 64 +++++ .../CommonsPortletMultipartResolver.java | 11 +- .../DefaultMultipartActionRequest.java | 48 ++-- .../mvc/AbstractCommandController.java | 2 + .../portlet/mvc/AbstractFormController.java | 2 + .../mvc/AbstractWizardFormController.java | 11 +- .../portlet/mvc/BaseCommandController.java | 2 + .../web/portlet/mvc/SimpleFormController.java | 2 + .../DefaultAnnotationHandlerMapping.java | 13 +- .../web/portlet/util/PortletUtils.java | 18 +- .../web/bind/WebDataBinder.java | 13 +- .../web/multipart/MultipartRequest.java | 4 +- .../commons/CommonsFileUploadSupport.java | 53 ++-- .../commons/CommonsMultipartResolver.java | 11 +- .../AbstractMultipartHttpServletRequest.java | 14 +- .../DefaultMultipartHttpServletRequest.java | 36 +-- .../web/servlet/DispatcherServlet.java | 8 +- .../web/servlet/ModelAndView.java | 22 +- .../org/springframework/web/servlet/View.java | 10 +- .../web/servlet/ViewRendererServlet.java | 5 +- .../handler/SimpleUrlHandlerMapping.java | 19 +- .../mvc/AbstractCommandController.java | 2 + .../servlet/mvc/AbstractFormController.java | 2 + .../mvc/AbstractWizardFormController.java | 2 + .../servlet/mvc/BaseCommandController.java | 2 + .../mvc/CancellableFormController.java | 2 + .../web/servlet/mvc/SimpleFormController.java | 2 + .../servlet/mvc/WebContentInterceptor.java | 21 +- .../DefaultAnnotationHandlerMapping.java | 9 +- .../multiaction/MultiActionController.java | 44 ++-- .../ParameterMethodNameResolver.java | 9 +- .../PropertiesMethodNameResolver.java | 17 +- .../ControllerBeanNameHandlerMapping.java | 8 +- .../ControllerClassNameHandlerMapping.java | 6 +- .../web/servlet/support/BindStatus.java | 2 +- .../support/JspAwareRequestContext.java | 9 +- .../web/servlet/support/RequestContext.java | 21 +- .../view/AbstractCachingViewResolver.java | 8 +- .../servlet/view/AbstractTemplateView.java | 4 +- .../servlet/view/AbstractUrlBasedView.java | 4 +- .../web/servlet/view/AbstractView.java | 41 +-- .../servlet/view/InternalResourceView.java | 6 +- .../web/servlet/view/RedirectView.java | 33 +-- .../view/ResourceBundleViewResolver.java | 30 +-- .../servlet/view/UrlBasedViewResolver.java | 11 +- .../view/document/AbstractExcelView.java | 12 +- .../view/document/AbstractJExcelView.java | 27 +- .../view/document/AbstractPdfStamperView.java | 53 ++-- .../view/document/AbstractPdfView.java | 15 +- .../view/feed/AbstractAtomFeedView.java | 58 ++--- .../servlet/view/feed/AbstractFeedView.java | 54 ++-- .../view/feed/AbstractRssFeedView.java | 53 ++-- .../view/freemarker/FreeMarkerView.java | 18 +- ...AbstractJasperReportsSingleFormatView.java | 32 +-- .../AbstractJasperReportsView.java | 84 ++---- .../JasperReportsMultiFormatView.java | 38 +-- .../JasperReportsViewResolver.java | 21 +- .../web/servlet/view/tiles2/TilesView.java | 6 +- .../view/velocity/VelocityToolboxView.java | 28 +- .../servlet/view/velocity/VelocityView.java | 66 +---- .../view/velocity/VelocityViewResolver.java | 20 +- .../servlet/view/xslt/AbstractXsltView.java | 39 +-- .../web/servlet/view/xslt/XsltView.java | 34 +-- .../jaxws/AbstractJaxWsServiceExporter.java | 4 +- .../jaxws/LocalJaxWsServiceFactory.java | 6 +- .../springframework/web/util/WebUtils.java | 5 +- 248 files changed, 2374 insertions(+), 3208 deletions(-) delete mode 100644 org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java delete mode 100644 org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/package.html delete mode 100644 org.springframework.context/src/main/java/org/springframework/context/support/ResourceMapFactoryBean.java delete mode 100644 org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessorTests.java delete mode 100644 org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/MyAnnotation.java delete mode 100644 org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/SomeAnnotatedBean.java delete mode 100644 org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/genericBeanFactoryAccessorTests.xml delete mode 100644 org.springframework.testsuite/src/test/java/org/springframework/context/support/ResourceMapFactoryBeanTests.java create mode 100644 org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java index a51ae393673..36ee8502e19 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java @@ -74,7 +74,7 @@ import org.springframework.util.StringUtils; public class AspectJExpressionPointcut extends AbstractExpressionPointcut implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware { - private static final Set DEFAULT_SUPPORTED_PRIMITIVES = new HashSet(); + private static final Set DEFAULT_SUPPORTED_PRIMITIVES = new HashSet(); static { DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION); @@ -92,7 +92,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut private static final Log logger = LogFactory.getLog(AspectJExpressionPointcut.class); - private final Map shadowMapCache = new HashMap(); + private final Map shadowMatchCache = new HashMap(); private PointcutParser pointcutParser; @@ -364,8 +364,8 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut } private ShadowMatch getShadowMatch(Method targetMethod, Method originalMethod) { - synchronized (this.shadowMapCache) { - ShadowMatch shadowMatch = (ShadowMatch) this.shadowMapCache.get(targetMethod); + synchronized (this.shadowMatchCache) { + ShadowMatch shadowMatch = this.shadowMatchCache.get(targetMethod); if (shadowMatch == null) { try { shadowMatch = this.pointcutExpression.matchesMethodExecution(targetMethod); @@ -378,7 +378,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut } shadowMatch = this.pointcutExpression.matchesMethodExecution(originalMethod); } - this.shadowMapCache.put(targetMethod, shadowMatch); + this.shadowMatchCache.put(targetMethod, shadowMatch); } return shadowMatch; } @@ -520,8 +520,8 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut } if (beanFactory != null) { String[] aliases = beanFactory.getAliases(advisedBeanName); - for (int i = 0; i < aliases.length; i++) { - if (this.expressionPattern.matches(aliases[i])) { + for (String alias : aliases) { + if (this.expressionPattern.matches(alias)) { return true; } } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java index 341e3aff70d..55f684956da 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ import org.springframework.util.ClassUtils; public class AspectJProxyFactory extends ProxyCreatorSupport { /** Cache for singleton aspect instances */ - private static final Map aspectCache = new HashMap(); + private static final Map aspectCache = new HashMap(); private final AspectJAdvisorFactory aspectFactory = new ReflectiveAspectJAdvisorFactory(); @@ -199,6 +199,7 @@ public class AspectJProxyFactory extends ProxyCreatorSupport { * (if necessary for proxy creation). * @return the new proxy */ + @SuppressWarnings("unchecked") public T getProxy() { return (T) createAopProxy().getProxy(); } @@ -211,6 +212,7 @@ public class AspectJProxyFactory extends ProxyCreatorSupport { * @param classLoader the class loader to create the proxy with * @return the new proxy */ + @SuppressWarnings("unchecked") public T getProxy(ClassLoader classLoader) { return (T) createAopProxy().getProxy(classLoader); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java index e3969666edc..ac65af3dc3c 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java @@ -142,8 +142,8 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig ProxyFactory proxyFactory = new ProxyFactory(); if (this.preInterceptors != null) { - for (int i = 0; i < this.preInterceptors.length; i++) { - proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(this.preInterceptors[i])); + for (Object interceptor : this.preInterceptors) { + proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor)); } } @@ -151,8 +151,8 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainInterceptor())); if (this.postInterceptors != null) { - for (int i = 0; i < this.postInterceptors.length; i++) { - proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(this.postInterceptors[i])); + for (Object interceptor : this.postInterceptors) { + proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor)); } } @@ -170,7 +170,7 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), this.proxyClassLoader)); } - this.proxy = getProxy(proxyFactory); + this.proxy = proxyFactory.getProxy(this.proxyClassLoader); } /** @@ -188,19 +188,6 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig } } - /** - * Return the proxy object to expose. - *

The default implementation uses a getProxy call with - * the factory's bean class loader. Can be overridden to specify a - * custom class loader. - * @param aopProxy the prepared AopProxy instance to get the proxy from - * @return the proxy object to expose - * @see AopProxy#getProxy(ClassLoader) - */ - protected Object getProxy(AopProxy aopProxy) { - return aopProxy.getProxy(this.proxyClassLoader); - } - public Object getObject() { if (this.proxy == null) { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java index 201518315bd..49bbbd041ff 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -362,7 +362,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { *

Use with care, and remember to {@link #updateAdvisorArray() refresh the advisor array} * and {@link #adviceChanged() fire advice changed events} when making any modifications. */ - protected final List getAdvisorsInternal() { + protected final List getAdvisorsInternal() { return this.advisors; } @@ -454,7 +454,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @param targetClass the target class * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers) */ - public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) { + public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) { MethodCacheKey cacheKey = new MethodCacheKey(method); List cached = this.methodCache.get(cacheKey); if (cached == null) { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/Cglib2AopProxy.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/Cglib2AopProxy.java index 5ae63613a79..9d649b62daa 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/Cglib2AopProxy.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/Cglib2AopProxy.java @@ -90,7 +90,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { protected final static Log logger = LogFactory.getLog(Cglib2AopProxy.class); /** Keeps track of the Classes that we have validated for final methods */ - private static final Map validatedClasses = new WeakHashMap(); + private static final Map validatedClasses = new WeakHashMap(); /** The configuration used to configure this proxy */ @@ -103,7 +103,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { /** Dispatcher used for methods on Advised */ private final transient AdvisedDispatcher advisedDispatcher; - private transient Map fixedInterceptorMap; + private transient Map fixedInterceptorMap; private transient int fixedInterceptorOffset; @@ -158,8 +158,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { if (AopUtils.isCglibProxyClass(rootClass)) { proxySuperClass = rootClass.getSuperclass(); Class[] additionalInterfaces = rootClass.getInterfaces(); - for (int i = 0; i < additionalInterfaces.length; i++) { - Class additionalInterface = additionalInterfaces[i]; + for (Class additionalInterface : additionalInterfaces) { this.advised.addInterface(additionalInterface); } } @@ -250,8 +249,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { */ private void doValidateClass(Class proxySuperClass) { Method[] methods = proxySuperClass.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) { logger.warn("Unable to proxy method [" + method + "] because it is final: " + "All calls to this method via a proxy will be routed directly to the proxy."); @@ -271,22 +269,21 @@ final class Cglib2AopProxy implements AopProxy, Serializable { // Choose a "straight to target" interceptor. (used for calls that are // unadvised but can return this). May be required to expose the proxy. Callback targetInterceptor = null; - if (exposeProxy) { targetInterceptor = isStatic ? - (Callback) new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) : - (Callback) new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()); + new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) : + new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()); } else { targetInterceptor = isStatic ? - (Callback) new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) : - (Callback) new DynamicUnadvisedInterceptor(this.advised.getTargetSource()); + new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) : + new DynamicUnadvisedInterceptor(this.advised.getTargetSource()); } // Choose a "direct to target" dispatcher (used for // unadvised calls to static targets that cannot return this). Callback targetDispatcher = isStatic ? - (Callback) new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp(); + new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp(); Callback[] mainCallbacks = new Callback[]{ aopInterceptor, // for normal advice @@ -305,29 +302,26 @@ final class Cglib2AopProxy implements AopProxy, Serializable { if (isStatic && isFrozen) { Method[] methods = rootClass.getMethods(); Callback[] fixedCallbacks = new Callback[methods.length]; - this.fixedInterceptorMap = new HashMap(methods.length); + this.fixedInterceptorMap = new HashMap(methods.length); // TODO: small memory optimisation here (can skip creation for // methods with no advice) for (int x = 0; x < methods.length; x++) { - List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass); + List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass); fixedCallbacks[x] = new FixedChainStaticTargetInterceptor( chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass()); - this.fixedInterceptorMap.put(methods[x].toString(), new Integer(x)); + this.fixedInterceptorMap.put(methods[x].toString(), x); } // Now copy both the callbacks from mainCallbacks // and fixedCallbacks into the callbacks array. callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length]; - for (int x = 0; x < mainCallbacks.length; x++) { callbacks[x] = mainCallbacks[x]; } - for (int x = 0; x < fixedCallbacks.length; x++) { callbacks[x + mainCallbacks.length] = fixedCallbacks[x]; } - this.fixedInterceptorOffset = mainCallbacks.length; } else { @@ -523,20 +517,19 @@ final class Cglib2AopProxy implements AopProxy, Serializable { public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) { Object other = args[0]; if (proxy == other) { - return Boolean.TRUE; + return true; } - AdvisedSupport otherAdvised = null; if (other instanceof Factory) { Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS); if (!(callback instanceof EqualsInterceptor)) { - return Boolean.FALSE; + return false; } - otherAdvised = ((EqualsInterceptor) callback).advised; + AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised; + return AopProxyUtils.equalsInProxy(this.advised, otherAdvised); } else { - return Boolean.FALSE; + return false; } - return (AopProxyUtils.equalsInProxy(this.advised, otherAdvised) ? Boolean.TRUE : Boolean.FALSE); } } @@ -554,7 +547,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { } public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) { - return new Integer(Cglib2AopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode()); + return Cglib2AopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode(); } } @@ -564,24 +557,23 @@ final class Cglib2AopProxy implements AopProxy, Serializable { */ private static class FixedChainStaticTargetInterceptor implements MethodInterceptor, Serializable { - private final List adviceChain; + private final List adviceChain; private final Object target; private final Class targetClass; - public FixedChainStaticTargetInterceptor(List adviceChain, Object target, Class targetClass) { + public FixedChainStaticTargetInterceptor(List adviceChain, Object target, Class targetClass) { this.adviceChain = adviceChain; this.target = target; this.targetClass = targetClass; } public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { - Object retVal = null; MethodInvocation invocation = new CglibMethodInvocation(proxy, this.target, method, args, this.targetClass, this.adviceChain, methodProxy); // If we get here, we need to create a MethodInvocation. - retVal = invocation.proceed(); + Object retVal = invocation.proceed(); retVal = massageReturnTypeIfNecessary(proxy, this.target, method, retVal); return retVal; } @@ -601,13 +593,11 @@ final class Cglib2AopProxy implements AopProxy, Serializable { } public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { - MethodInvocation invocation = null; Object oldProxy = null; boolean setProxyContext = false; Class targetClass = null; Object target = null; try { - Object retVal = null; if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy = AopContext.setCurrentProxy(proxy); @@ -619,7 +609,8 @@ final class Cglib2AopProxy implements AopProxy, Serializable { if (target != null) { targetClass = target.getClass(); } - List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); + List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); + Object retVal = null; // Check whether we only have one InvokerInterceptor: that is, // no real advice, but just reflective invocation of the target. if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) { @@ -631,12 +622,8 @@ final class Cglib2AopProxy implements AopProxy, Serializable { } else { // We need to create a method invocation... - invocation = new CglibMethodInvocation(proxy, target, method, args, - targetClass, chain, methodProxy); - // If we get here, we need to create a MethodInvocation. - retVal = invocation.proceed(); + retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed(); } - retVal = massageReturnTypeIfNecessary(proxy, target, method, retVal); return retVal; } @@ -686,7 +673,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { private boolean protectedMethod; public CglibMethodInvocation(Object proxy, Object target, Method method, Object[] arguments, - Class targetClass, List interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) { + Class targetClass, List interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) { super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers); this.methodProxy = methodProxy; this.protectedMethod = Modifier.isProtected(method.getModifiers()); @@ -715,11 +702,11 @@ final class Cglib2AopProxy implements AopProxy, Serializable { private final AdvisedSupport advised; - private final Map fixedInterceptorMap; + private final Map fixedInterceptorMap; private final int fixedInterceptorOffset; - public ProxyCallbackFilter(AdvisedSupport advised, Map fixedInterceptorMap, int fixedInterceptorOffset) { + public ProxyCallbackFilter(AdvisedSupport advised, Map fixedInterceptorMap, int fixedInterceptorOffset) { this.advised = advised; this.fixedInterceptorMap = fixedInterceptorMap; this.fixedInterceptorOffset = fixedInterceptorOffset; @@ -807,7 +794,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable { } // We know that we are optimising so we can use the // FixedStaticChainInterceptors. - int index = ((Integer) this.fixedInterceptorMap.get(key)).intValue(); + int index = this.fixedInterceptorMap.get(key); return (index + this.fixedInterceptorOffset); } else { @@ -910,23 +897,17 @@ final class Cglib2AopProxy implements AopProxy, Serializable { private boolean equalsPointcuts(Advisor a, Advisor b) { // If only one of the advisor (but not both) is PointcutAdvisor, then it is a mismatch. // Takes care of the situations where an IntroductionAdvisor is used (see SPR-3959). - if (a instanceof PointcutAdvisor ^ b instanceof PointcutAdvisor) { - return false; - } - // If both are PointcutAdvisor, match their pointcuts. - if (a instanceof PointcutAdvisor && b instanceof PointcutAdvisor) { - return ObjectUtils.nullSafeEquals(((PointcutAdvisor) a).getPointcut(), ((PointcutAdvisor) b).getPointcut()); - } - // If neither is PointcutAdvisor, then from the pointcut matching perspective, it is a match. - return true; + return (!(a instanceof PointcutAdvisor) || + (b instanceof PointcutAdvisor && + ObjectUtils.nullSafeEquals(((PointcutAdvisor) a).getPointcut(), ((PointcutAdvisor) b).getPointcut()))); } @Override public int hashCode() { int hashCode = 0; Advisor[] advisors = this.advised.getAdvisors(); - for (int i = 0; i < advisors.length; i++) { - Advice advice = advisors[i].getAdvice(); + for (Advisor advisor : advisors) { + Advice advice = advisor.getAdvice(); if (advice != null) { hashCode = 13 * hashCode + advice.getClass().hashCode(); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java index 522774e29ac..d8a06eb6da2 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.util.ClassUtils; * @author Rob Harrop * @since 14.03.2003 */ -public class ProxyFactory extends ProxyCreatorSupport implements AopProxy { +public class ProxyFactory extends ProxyCreatorSupport { /** * Create a new ProxyFactory. @@ -93,8 +93,9 @@ public class ProxyFactory extends ProxyCreatorSupport implements AopProxy { * (if necessary for proxy creation). * @return the proxy object */ - public Object getProxy() { - return createAopProxy().getProxy(); + @SuppressWarnings("unchecked") + public T getProxy() { + return (T) createAopProxy().getProxy(); } /** @@ -106,8 +107,9 @@ public class ProxyFactory extends ProxyCreatorSupport implements AopProxy { * (or null for the low-level proxy facility's default) * @return the proxy object */ - public Object getProxy(ClassLoader classLoader) { - return createAopProxy().getProxy(classLoader); + @SuppressWarnings("unchecked") + public T getProxy(ClassLoader classLoader) { + return (T) createAopProxy().getProxy(classLoader); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java index 78c4f544271..d4b1782c8ad 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java @@ -433,8 +433,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport } // Materialize interceptor chain from bean names. - for (int i = 0; i < this.interceptorNames.length; i++) { - String name = this.interceptorNames[i]; + for (String name : this.interceptorNames) { if (logger.isTraceEnabled()) { logger.trace("Configuring advisor or advice '" + name + "'"); } @@ -452,16 +451,16 @@ public class ProxyFactoryBean extends ProxyCreatorSupport // If we get here, we need to add a named interceptor. // We must check if it's a singleton or prototype. Object advice = null; - if (this.singleton || this.beanFactory.isSingleton(this.interceptorNames[i])) { + if (this.singleton || this.beanFactory.isSingleton(name)) { // Add the real Advisor/Advice to the chain. - advice = this.beanFactory.getBean(this.interceptorNames[i]); + advice = this.beanFactory.getBean(name); } else { // It's a prototype Advice or Advisor: replace with a prototype. // Avoid unnecessary creation of prototype bean just for advisor chain initialization. - advice = new PrototypePlaceholderAdvisor(this.interceptorNames[i]); + advice = new PrototypePlaceholderAdvisor(name); } - addAdvisorOnChainCreation(advice, this.interceptorNames[i]); + addAdvisorOnChainCreation(advice, name); } } } @@ -477,11 +476,10 @@ public class ProxyFactoryBean extends ProxyCreatorSupport */ private List freshAdvisorChain() { Advisor[] advisors = getAdvisors(); - List freshAdvisors = new ArrayList(advisors.length); - - for (int i = 0; i < advisors.length; i++) { - if (advisors[i] instanceof PrototypePlaceholderAdvisor) { - PrototypePlaceholderAdvisor pa = (PrototypePlaceholderAdvisor) advisors[i]; + List freshAdvisors = new ArrayList(advisors.length); + for (Advisor advisor : advisors) { + if (advisor instanceof PrototypePlaceholderAdvisor) { + PrototypePlaceholderAdvisor pa = (PrototypePlaceholderAdvisor) advisor; if (logger.isDebugEnabled()) { logger.debug("Refreshing bean named '" + pa.getBeanName() + "'"); } @@ -497,7 +495,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport } else { // Add the shared instance. - freshAdvisors.add(advisors[i]); + freshAdvisors.add(advisor); } } return freshAdvisors; @@ -511,24 +509,21 @@ public class ProxyFactoryBean extends ProxyCreatorSupport BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Advisor.class); String[] globalInterceptorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Interceptor.class); - List beans = new ArrayList(globalAdvisorNames.length + globalInterceptorNames.length); - Map names = new HashMap(); - for (int i = 0; i < globalAdvisorNames.length; i++) { - String name = globalAdvisorNames[i]; + List beans = new ArrayList(globalAdvisorNames.length + globalInterceptorNames.length); + Map names = new HashMap(beans.size()); + for (String name : globalAdvisorNames) { Object bean = beanFactory.getBean(name); beans.add(bean); names.put(bean, name); } - for (int i = 0; i < globalInterceptorNames.length; i++) { - String name = globalInterceptorNames[i]; + for (String name : globalInterceptorNames) { Object bean = beanFactory.getBean(name); beans.add(bean); names.put(bean, name); } Collections.sort(beans, new OrderComparator()); - for (Iterator it = beans.iterator(); it.hasNext();) { - Object bean = it.next(); - String name = (String) names.get(bean); + for (Object bean : beans) { + String name = names.get(bean); if (name.startsWith(prefix)) { addAdvisorOnChainCreation(bean, name); } @@ -551,7 +546,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport if (logger.isTraceEnabled()) { logger.trace("Adding advisor with name '" + name + "'"); } - addAdvisor((Advisor) advisor); + addAdvisor(advisor); } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java index c487b512fa3..d816acc1433 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ReflectiveMethodInvocation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea /** * Lazily initialized map of user-specific attributes for this invocation. */ - private Map userAttributes; + private Map userAttributes; /** * List of MethodInterceptor and InterceptorAndDynamicMethodMatcher @@ -102,7 +102,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea */ protected ReflectiveMethodInvocation( Object proxy, Object target, Method method, Object[] arguments, - Class targetClass, List interceptorsAndDynamicMethodMatchers) { + Class targetClass, List interceptorsAndDynamicMethodMatchers) { this.proxy = proxy; this.target = target; @@ -213,7 +213,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea // Force initialization of the user attributes Map, // for having a shared Map reference in the clone. if (this.userAttributes == null) { - this.userAttributes = new HashMap(); + this.userAttributes = new HashMap(); } // Create the MethodInvocation clone. @@ -232,7 +232,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea public void setUserAttribute(String key, Object value) { if (value != null) { if (this.userAttributes == null) { - this.userAttributes = new HashMap(); + this.userAttributes = new HashMap(); } this.userAttributes.put(key, value); } @@ -254,9 +254,9 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea * @return any user attributes associated with this invocation * (never null) */ - public Map getUserAttributes() { + public Map getUserAttributes() { if (this.userAttributes == null) { - this.userAttributes = new HashMap(); + this.userAttributes = new HashMap(); } return this.userAttributes; } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java index 320f7fe5b57..8773e933c01 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice { private final Object throwsAdvice; /** Methods on throws advice, keyed by exception class */ - private final Map exceptionHandlerMap = new HashMap(); + private final Map exceptionHandlerMap = new HashMap(); /** @@ -75,10 +75,8 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice { this.throwsAdvice = throwsAdvice; Method[] methods = throwsAdvice.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { if (method.getName().equals(AFTER_THROWING) && - //m.getReturnType() == null && (method.getParameterTypes().length == 1 || method.getParameterTypes().length == 4) && Throwable.class.isAssignableFrom(method.getParameterTypes()[method.getParameterTypes().length - 1]) ) { @@ -110,10 +108,10 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice { if (logger.isTraceEnabled()) { logger.trace("Trying to find handler for exception of type [" + exceptionClass.getName() + "]"); } - Method handler = (Method) this.exceptionHandlerMap.get(exceptionClass); + Method handler = this.exceptionHandlerMap.get(exceptionClass); while (handler == null && !exceptionClass.equals(Throwable.class)) { exceptionClass = exceptionClass.getSuperclass(); - handler = (Method) this.exceptionHandlerMap.get(exceptionClass); + handler = this.exceptionHandlerMap.get(exceptionClass); } if (handler != null && logger.isDebugEnabled()) { logger.debug("Found handler for exception of type [" + exceptionClass.getName() + "]: " + handler); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java index 378fb353c72..5278ee233ff 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2087 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ public class DelegatePerTargetObjectIntroductionInterceptor extends Introduction /** * Hold weak references to keys as we don't want to interfere with garbage collection.. */ - private Map delegateMap = new WeakHashMap(); + private final Map delegateMap = new WeakHashMap(); private Class defaultImplType; @@ -115,7 +115,7 @@ public class DelegatePerTargetObjectIntroductionInterceptor extends Introduction } private Object getIntroductionDelegateFor(Object targetObject) { - synchronized(this.delegateMap) { + synchronized (this.delegateMap) { if (this.delegateMap.containsKey(targetObject)) { return this.delegateMap.get(targetObject); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/target/ThreadLocalTargetSource.java b/org.springframework.aop/src/main/java/org/springframework/aop/target/ThreadLocalTargetSource.java index 1a8a5dd03f1..ccc4d2e32b7 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/target/ThreadLocalTargetSource.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/target/ThreadLocalTargetSource.java @@ -18,7 +18,6 @@ package org.springframework.aop.target; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import org.springframework.aop.IntroductionAdvisor; @@ -26,6 +25,7 @@ import org.springframework.aop.support.DefaultIntroductionAdvisor; import org.springframework.aop.support.DelegatingIntroductionInterceptor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; +import org.springframework.core.NamedThreadLocal; /** * Alternative to an object pool. This TargetSource uses a threading model in which @@ -56,17 +56,13 @@ public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource * thread. Unlike most ThreadLocals, which are static, this variable * is meant to be per thread per instance of the ThreadLocalTargetSource class. */ - private final ThreadLocal targetInThread = new ThreadLocal() { - @Override - public String toString() { - return "Thread-local instance of bean '" + getTargetBeanName() + "'"; - } - }; + private final ThreadLocal targetInThread = + new NamedThreadLocal("Thread-local instance of bean '" + getTargetBeanName() + "'"); /** * Set of managed targets, enabling us to keep track of the targets we've created. */ - private final Set targetSet = Collections.synchronizedSet(new HashSet()); + private final Set targetSet = Collections.synchronizedSet(new HashSet()); private int invocationCount; @@ -104,8 +100,8 @@ public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource public void destroy() { logger.debug("Destroying ThreadLocalTargetSource bindings"); synchronized (this.targetSet) { - for (Iterator it = this.targetSet.iterator(); it.hasNext(); ) { - destroyPrototypeInstance(it.next()); + for (Object target : this.targetSet) { + destroyPrototypeInstance(target); } this.targetSet.clear(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java index 1c69257f064..116d487dc72 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanUtils.java @@ -60,6 +60,32 @@ public abstract class BeanUtils { Collections.synchronizedMap(new WeakHashMap()); + /** + * Convenience method to instantiate a class using its no-arg constructor. + * As this method doesn't try to load classes by name, it should avoid + * class-loading issues. + *

Note that this method tries to set the constructor accessible + * if given a non-accessible (that is, non-public) constructor. + * @param clazz class to instantiate + * @return the new instance + * @throws BeanInstantiationException if the bean cannot be instantiated + */ + public static T instantiate(Class clazz) throws BeanInstantiationException { + Assert.notNull(clazz, "Class must not be null"); + if (clazz.isInterface()) { + throw new BeanInstantiationException(clazz, "Specified class is an interface"); + } + try { + return clazz.newInstance(); + } + catch (InstantiationException ex) { + throw new BeanInstantiationException(clazz, "Is it an abstract class?", ex); + } + catch (IllegalAccessException ex) { + throw new BeanInstantiationException(clazz, "Is the constructor accessible?", ex); + } + } + /** * Convenience method to instantiate a class using its no-arg constructor. * As this method doesn't try to load classes by name, it should avoid @@ -106,7 +132,7 @@ public abstract class BeanUtils { } catch (IllegalAccessException ex) { throw new BeanInstantiationException(ctor.getDeclaringClass(), - "Has the class definition changed? Is the constructor accessible?", ex); + "Is the constructor accessible?", ex); } catch (IllegalArgumentException ex) { throw new BeanInstantiationException(ctor.getDeclaringClass(), diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java index 1b4251b7f91..eefda590f03 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java @@ -100,7 +100,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra /** * Map with cached nested BeanWrappers: nested path -> BeanWrapper instance. */ - private Map nestedBeanWrappers; + private Map nestedBeanWrappers; /** @@ -431,7 +431,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra */ private BeanWrapperImpl getNestedBeanWrapper(String nestedProperty) { if (this.nestedBeanWrappers == null) { - this.nestedBeanWrappers = new HashMap(); + this.nestedBeanWrappers = new HashMap(); } // Get value of bean property. PropertyTokenHolder tokens = getPropertyNameTokens(nestedProperty); @@ -442,7 +442,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra } // Lookup cached sub-BeanWrapper, create new one if not found. - BeanWrapperImpl nestedBw = (BeanWrapperImpl) this.nestedBeanWrappers.get(canonicalName); + BeanWrapperImpl nestedBw = this.nestedBeanWrappers.get(canonicalName); if (nestedBw == null || nestedBw.getWrappedInstance() != propertyValue) { if (logger.isTraceEnabled()) { logger.trace("Creating new nested BeanWrapper for property '" + canonicalName + "'"); @@ -805,7 +805,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra readMethod.setAccessible(true); } try { - oldValue = readMethod.invoke(this.object, new Object[0]); + oldValue = readMethod.invoke(this.object); } catch (Exception ex) { if (logger.isDebugEnabled()) { @@ -816,13 +816,13 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra } valueToApply = this.typeConverterDelegate.convertIfNecessary(oldValue, originalValue, pd); } - pv.getOriginalPropertyValue().conversionNecessary = Boolean.valueOf(valueToApply != originalValue); + pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue); } Method writeMethod = pd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } - writeMethod.invoke(this.object, new Object[] {valueToApply}); + writeMethod.invoke(this.object, valueToApply); } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/DirectFieldAccessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/DirectFieldAccessor.java index 80ec5a5e7f4..b7ee738563b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/DirectFieldAccessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/DirectFieldAccessor.java @@ -46,7 +46,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor { private final Object target; - private final Map fieldMap = new HashMap(); + private final Map fieldMap = new HashMap(); private final TypeConverterDelegate typeConverterDelegate; @@ -79,7 +79,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor { @Override public Class getPropertyType(String propertyName) throws BeansException { - Field field = (Field) this.fieldMap.get(propertyName); + Field field = this.fieldMap.get(propertyName); if (field != null) { return field.getType(); } @@ -88,7 +88,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor { @Override public Object getPropertyValue(String propertyName) throws BeansException { - Field field = (Field) this.fieldMap.get(propertyName); + Field field = this.fieldMap.get(propertyName); if (field == null) { throw new NotReadablePropertyException( this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist"); @@ -104,7 +104,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor { @Override public void setPropertyValue(String propertyName, Object newValue) throws BeansException { - Field field = (Field) this.fieldMap.get(propertyName); + Field field = this.fieldMap.get(propertyName); if (field == null) { throw new NotWritablePropertyException( this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist"); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java index c351f20cdc3..0942874c188 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java @@ -16,6 +16,7 @@ package org.springframework.beans.factory; +import java.lang.annotation.Annotation; import java.util.Map; import org.springframework.beans.BeansException; @@ -210,4 +211,42 @@ $ *

Does not consider any hierarchy this factory may participate in. Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; + /** + * Find all beans whose Class has the supplied {@link java.lang.annotation.Annotation} type. + * @param annotationType the type of annotation to look for + * @return a Map with the matching beans, containing the bean names as + * keys and the corresponding bean instances as values + * @throws BeansException if a bean could not be created + */ + Map getBeansWithAnnotation(Class annotationType) + throws BeansException; + + /** + * Find all beans whose Class has the supplied {@link java.lang.annotation.Annotation} type. + * @param annotationType the type of annotation to look for + * @return a Map with the matching beans, containing the bean names as + * keys and the corresponding bean instances as values + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @throws BeansException if a bean could not be created + */ + Map getBeansWithAnnotation( + Class annotationType, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException; + + /** + * Find a {@link Annotation} of annotationType on the specified + * bean, traversing its interfaces and super classes if no annotation can be + * found on the given class itself. + * @param beanName the name of the bean to look for annotations on + * @param annotationType the annotation class to look for + * @return the annotation of the given type found, or null + */ + A findAnnotationOnBean(String beanName, Class annotationType); + } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java index 70cda453a33..1656fcf12cf 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java @@ -277,7 +277,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator { protected static final Log logger = LogFactory.getLog(SingletonBeanFactoryLocator.class); /** The keyed BeanFactory instances */ - private static Map instances = new HashMap(); + private static final Map instances = new HashMap(); /** @@ -324,7 +324,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator { logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + instances.hashCode() + ", instances=" + instances); } - BeanFactoryLocator bfl = (BeanFactoryLocator) instances.get(resourceLocation); + BeanFactoryLocator bfl = instances.get(resourceLocation); if (bfl == null) { bfl = new SingletonBeanFactoryLocator(resourceLocation); instances.put(resourceLocation, bfl); @@ -335,9 +335,9 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator { // We map BeanFactoryGroup objects by String keys, and by the definition object. - private final Map bfgInstancesByKey = new HashMap(); + private final Map bfgInstancesByKey = new HashMap(); - private final Map bfgInstancesByObj = new HashMap(); + private final Map bfgInstancesByObj = new HashMap(); private final String resourceLocation; @@ -354,7 +354,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator { public BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException { synchronized (this.bfgInstancesByKey) { - BeanFactoryGroup bfg = (BeanFactoryGroup) this.bfgInstancesByKey.get(this.resourceLocation); + BeanFactoryGroup bfg = this.bfgInstancesByKey.get(this.resourceLocation); if (bfg != null) { bfg.refCount++; @@ -394,11 +394,10 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator { try { BeanFactory beanFactory = null; if (factoryKey != null) { - beanFactory = (BeanFactory) bfg.definition.getBean(factoryKey, BeanFactory.class); + beanFactory = bfg.definition.getBean(factoryKey, BeanFactory.class); } else if (bfg.definition instanceof ListableBeanFactory) { - beanFactory = (BeanFactory) - BeanFactoryUtils.beanOfType((ListableBeanFactory) bfg.definition, BeanFactory.class); + beanFactory = BeanFactoryUtils.beanOfType((ListableBeanFactory) bfg.definition, BeanFactory.class); } else { throw new IllegalStateException( @@ -518,7 +517,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator { BeanFactory savedRef = this.groupContextRef; if (savedRef != null) { this.groupContextRef = null; - BeanFactoryGroup bfg = (BeanFactoryGroup) bfgInstancesByObj.get(savedRef); + BeanFactoryGroup bfg = bfgInstancesByObj.get(savedRef); if (bfg != null) { bfg.refCount--; if (bfg.refCount == 0) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java index 15138353376..6bb7a2aaa28 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java @@ -57,8 +57,8 @@ import org.springframework.util.ReflectionUtils; * @see #setSingleton * @see #createInstance() */ -public abstract class AbstractFactoryBean - implements FactoryBean, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean { +public abstract class AbstractFactoryBean + implements FactoryBean, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); @@ -71,9 +71,9 @@ public abstract class AbstractFactoryBean private boolean initialized = false; - private Object singletonInstance; + private T singletonInstance; - private Object earlySingletonInstance; + private T earlySingletonInstance; /** @@ -138,7 +138,7 @@ public abstract class AbstractFactoryBean * @see #createInstance() * @see #getEarlySingletonInterfaces() */ - public final Object getObject() throws Exception { + public final T getObject() throws Exception { if (isSingleton()) { return (this.initialized ? this.singletonInstance : getEarlySingletonInstance()); } @@ -151,14 +151,15 @@ public abstract class AbstractFactoryBean * Determine an 'eager singleton' instance, exposed in case of a * circular reference. Not called in a non-circular scenario. */ - private Object getEarlySingletonInstance() throws Exception { + @SuppressWarnings("unchecked") + private T getEarlySingletonInstance() throws Exception { Class[] ifcs = getEarlySingletonInterfaces(); if (ifcs == null) { throw new FactoryBeanNotInitializedException( getClass().getName() + " does not support circular references"); } if (this.earlySingletonInstance == null) { - this.earlySingletonInstance = Proxy.newProxyInstance( + this.earlySingletonInstance = (T) Proxy.newProxyInstance( this.beanClassLoader, ifcs, new EarlySingletonInvocationHandler()); } return this.earlySingletonInstance; @@ -169,7 +170,7 @@ public abstract class AbstractFactoryBean * @return the singleton instance that this FactoryBean holds * @throws IllegalStateException if the singleton instance is not initialized */ - private Object getSingletonInstance() throws IllegalStateException { + private T getSingletonInstance() throws IllegalStateException { if (!this.initialized) { throw new IllegalStateException("Singleton instance not initialized yet"); } @@ -192,7 +193,7 @@ public abstract class AbstractFactoryBean * interface, for a consistent offering of abstract template methods. * @see org.springframework.beans.factory.FactoryBean#getObjectType() */ - public abstract Class getObjectType(); + public abstract Class getObjectType(); /** * Template method that subclasses must override to construct @@ -203,7 +204,7 @@ public abstract class AbstractFactoryBean * @throws Exception if an exception occured during object creation * @see #getObject() */ - protected abstract Object createInstance() throws Exception; + protected abstract T createInstance() throws Exception; /** * Return an array of interfaces that a singleton object exposed by this @@ -231,7 +232,7 @@ public abstract class AbstractFactoryBean * @throws Exception in case of shutdown errors * @see #createInstance() */ - protected void destroyInstance(Object instance) throws Exception { + protected void destroyInstance(T instance) throws Exception { } @@ -240,11 +241,11 @@ public abstract class AbstractFactoryBean public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (ReflectionUtils.isEqualsMethod(method)) { // Only consider equal when proxies are identical. - return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); + return (proxy == args[0]); } else if (ReflectionUtils.isHashCodeMethod(method)) { // Use hashCode of reference proxy. - return new Integer(System.identityHashCode(proxy)); + return System.identityHashCode(proxy); } else if (!initialized && ReflectionUtils.isToStringMethod(method)) { return "Early singleton proxy for interfaces " + diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java index 557bea793ab..7ceb21f7535 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ListFactoryBean.java @@ -32,7 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver; * @see SetFactoryBean * @see MapFactoryBean */ -public class ListFactoryBean extends AbstractFactoryBean { +public class ListFactoryBean extends AbstractFactoryBean { private List sourceList; @@ -64,13 +64,13 @@ public class ListFactoryBean extends AbstractFactoryBean { @Override - public Class getObjectType() { + public Class getObjectType() { return List.class; } @Override @SuppressWarnings("unchecked") - protected Object createInstance() { + protected List createInstance() { if (this.sourceList == null) { throw new IllegalArgumentException("'sourceList' is required"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java index b2a183b7f49..436e20da935 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/MapFactoryBean.java @@ -32,7 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver; * @see SetFactoryBean * @see ListFactoryBean */ -public class MapFactoryBean extends AbstractFactoryBean { +public class MapFactoryBean extends AbstractFactoryBean { private Map sourceMap; @@ -64,13 +64,13 @@ public class MapFactoryBean extends AbstractFactoryBean { @Override - public Class getObjectType() { + public Class getObjectType() { return Map.class; } @Override @SuppressWarnings("unchecked") - protected Object createInstance() { + protected Map createInstance() { if (this.sourceMap == null) { throw new IllegalArgumentException("'sourceMap' is required"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertiesFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertiesFactoryBean.java index 07403ce47fb..fd4932d71da 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertiesFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertiesFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,11 +43,11 @@ import org.springframework.core.io.support.PropertiesLoaderSupport; * @see java.util.Properties */ public class PropertiesFactoryBean extends PropertiesLoaderSupport - implements FactoryBean, InitializingBean { + implements FactoryBean, InitializingBean { private boolean singleton = true; - private Object singletonInstance; + private Properties singletonInstance; /** @@ -66,36 +66,21 @@ public class PropertiesFactoryBean extends PropertiesLoaderSupport public final void afterPropertiesSet() throws IOException { if (this.singleton) { - this.singletonInstance = createInstance(); + this.singletonInstance = mergeProperties(); } } - public final Object getObject() throws IOException { + public final Properties getObject() throws IOException { if (this.singleton) { return this.singletonInstance; } else { - return createInstance(); + return mergeProperties(); } } - public Class getObjectType() { + public Class getObjectType() { return Properties.class; } - - /** - * Template method that subclasses may override to construct the object - * returned by this factory. The default implementation returns the - * plain merged Properties instance. - *

Invoked on initialization of this FactoryBean in case of a - * shared singleton; else, on each {@link #getObject()} call. - * @return the object returned by this factory - * @throws IOException if an exception occured during properties loading - * @see #mergeProperties() - */ - protected Object createInstance() throws IOException { - return mergeProperties(); - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java index 692b528d73f..e3b2ee9e21e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/SetFactoryBean.java @@ -32,7 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver; * @see ListFactoryBean * @see MapFactoryBean */ -public class SetFactoryBean extends AbstractFactoryBean { +public class SetFactoryBean extends AbstractFactoryBean { private Set sourceSet; @@ -64,13 +64,13 @@ public class SetFactoryBean extends AbstractFactoryBean { @Override - public Class getObjectType() { + public Class getObjectType() { return Set.class; } @Override @SuppressWarnings("unchecked") - protected Object createInstance() { + protected Set createInstance() { if (this.sourceSet == null) { throw new IllegalArgumentException("'sourceSet' is required"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java deleted file mode 100644 index e172efa57f1..00000000000 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.generic; - -import java.lang.annotation.Annotation; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.util.Assert; - -/** - * Simple wrapper around a {@link ListableBeanFactory} that provides typed, generics-based - * access to key methods. This removes the need for casting in many cases and should - * increase compile-time type safety. - * - *

Provides a simple mechanism for accessing all beans with a particular {@link Annotation}. - * - * @author Rob Harrop - * @author Juergen Hoeller - * @since 2.0 - */ -public class GenericBeanFactoryAccessor { - - /** - * The {@link ListableBeanFactory} being wrapped. - */ - private final ListableBeanFactory beanFactory; - - - /** - * Constructs a GenericBeanFactoryAccessor that wraps the supplied {@link ListableBeanFactory}. - */ - public GenericBeanFactoryAccessor(ListableBeanFactory beanFactory) { - Assert.notNull(beanFactory, "Bean factory must not be null"); - this.beanFactory = beanFactory; - } - - /** - * Return the wrapped {@link ListableBeanFactory}. - */ - public final ListableBeanFactory getBeanFactory() { - return this.beanFactory; - } - - - /** - * @see org.springframework.beans.factory.BeanFactory#getBean(String) - */ - public T getBean(String name) throws BeansException { - return (T) this.beanFactory.getBean(name); - } - - /** - * @see org.springframework.beans.factory.BeanFactory#getBean(String, Class) - */ - public T getBean(String name, Class requiredType) throws BeansException { - return (T) this.beanFactory.getBean(name, requiredType); - } - - /** - * @see ListableBeanFactory#getBeansOfType(Class) - */ - public Map getBeansOfType(Class type) throws BeansException { - return this.beanFactory.getBeansOfType(type); - } - - /** - * @see ListableBeanFactory#getBeansOfType(Class, boolean, boolean) - */ - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) - throws BeansException { - - return this.beanFactory.getBeansOfType(type, includeNonSingletons, allowEagerInit); - } - - /** - * Find all beans whose Class has the supplied {@link Annotation} type. - * @param annotationType the type of annotation to look for - * @return a Map with the matching beans, containing the bean names as - * keys and the corresponding bean instances as values - */ - public Map getBeansWithAnnotation(Class annotationType) { - Map results = new LinkedHashMap(); - for (String beanName : this.beanFactory.getBeanNamesForType(Object.class)) { - if (findAnnotationOnBean(beanName, annotationType) != null) { - results.put(beanName, this.beanFactory.getBean(beanName)); - } - } - return results; - } - - /** - * Find a {@link Annotation} of annotationType on the specified - * bean, traversing its interfaces and super classes if no annotation can be - * found on the given class itself, as well as checking its raw bean class - * if not found on the exposed bean reference (e.g. in case of a proxy). - * @param beanName the name of the bean to look for annotations on - * @param annotationType the annotation class to look for - * @return the annotation of the given type found, or null - * @see org.springframework.core.annotation.AnnotationUtils#findAnnotation(Class, Class) - */ - public A findAnnotationOnBean(String beanName, Class annotationType) { - Class handlerType = this.beanFactory.getType(beanName); - A ann = AnnotationUtils.findAnnotation(handlerType, annotationType); - if (ann == null && this.beanFactory instanceof ConfigurableBeanFactory && - this.beanFactory.containsBeanDefinition(beanName)) { - ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) this.beanFactory; - BeanDefinition bd = cbf.getMergedBeanDefinition(beanName); - if (bd instanceof AbstractBeanDefinition) { - AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; - if (abd.hasBeanClass()) { - Class beanClass = abd.getBeanClass(); - ann = AnnotationUtils.findAnnotation(beanClass, annotationType); - } - } - } - return ann; - } - -} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/package.html b/org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/package.html deleted file mode 100644 index e7e3dcf2346..00000000000 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/generic/package.html +++ /dev/null @@ -1,8 +0,0 @@ - - - -Support package for generic BeanFactory access, -leveraging Java 5 generics in the accessor API. - - - diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index f8181f6ade9..2b784ec3ed0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -167,15 +167,15 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp //--------------------------------------------------------------------- public Object getBean(String name) throws BeansException { - return getBean(name, null, null); + return doGetBean(name, null, null, false); } public T getBean(String name, Class requiredType) throws BeansException { - return getBean(name, requiredType, null); + return doGetBean(name, requiredType, null, false); } public Object getBean(String name, Object[] args) throws BeansException { - return getBean(name, null, args); + return doGetBean(name, null, args, false); } /** @@ -202,6 +202,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp * @return an instance of the bean * @throws BeansException if the bean could not be created */ + @SuppressWarnings("unchecked") protected T doGetBean( final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index 44530f7117b..a44d63f0428 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -16,6 +16,7 @@ package org.springframework.beans.factory.support; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -43,6 +44,7 @@ import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -327,6 +329,44 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto return result; } + public Map getBeansWithAnnotation(Class annotationType) { + return getBeansWithAnnotation(annotationType, true, true); + } + + public Map getBeansWithAnnotation( + Class annotationType, boolean includeNonSingletons, boolean allowEagerInit) { + + Map results = new LinkedHashMap(); + for (String beanName : getBeanNamesForType(Object.class, includeNonSingletons, allowEagerInit)) { + if (findAnnotationOnBean(beanName, annotationType) != null) { + results.put(beanName, getBean(beanName)); + } + } + return results; + } + + /** + * Find a {@link Annotation} of annotationType on the specified + * bean, traversing its interfaces and super classes if no annotation can be + * found on the given class itself, as well as checking its raw bean class + * if not found on the exposed bean reference (e.g. in case of a proxy). + */ + public A findAnnotationOnBean(String beanName, Class annotationType) { + Class handlerType = getType(beanName); + A ann = AnnotationUtils.findAnnotation(handlerType, annotationType); + if (ann == null && containsBeanDefinition(beanName)) { + BeanDefinition bd = getMergedBeanDefinition(beanName); + if (bd instanceof AbstractBeanDefinition) { + AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; + if (abd.hasBeanClass()) { + Class beanClass = abd.getBeanClass(); + ann = AnnotationUtils.findAnnotation(beanClass, annotationType); + } + } + } + return ann; + } + //--------------------------------------------------------------------- // Implementation of ConfigurableListableBeanFactory interface diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java index 908b2c99a9b..ee607bd72f3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java @@ -16,8 +16,10 @@ package org.springframework.beans.factory.support; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -30,6 +32,7 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.SmartFactoryBean; +import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.StringUtils; /** @@ -95,9 +98,12 @@ public class StaticListableBeanFactory implements ListableBeanFactory { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } } - return bean; + else { + return bean; + } } + @SuppressWarnings("unchecked") public T getBean(String name, Class requiredType) throws BeansException { Object bean = getBean(name); if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) { @@ -106,6 +112,7 @@ public class StaticListableBeanFactory implements ListableBeanFactory { return (T) bean; } + @SuppressWarnings("unchecked") public Object getBean(String name, Object[] args) throws BeansException { if (args != null) { throw new UnsupportedOperationException( @@ -203,6 +210,7 @@ public class StaticListableBeanFactory implements ListableBeanFactory { return getBeansOfType(type, true, true); } + @SuppressWarnings("unchecked") public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) throws BeansException { @@ -238,4 +246,27 @@ public class StaticListableBeanFactory implements ListableBeanFactory { return matches; } + public Map getBeansWithAnnotation(Class annotationType) + throws BeansException { + + return getBeansWithAnnotation(annotationType, true, true); + } + + public Map getBeansWithAnnotation( + Class annotationType, boolean includeNonSingletons, boolean allowEagerInit) { + + Map results = new LinkedHashMap(); + for (String beanName : this.beans.keySet()) { + if (findAnnotationOnBean(beanName, annotationType) != null) { + results.put(beanName, getBean(beanName)); + } + } + return results; + } + + public A findAnnotationOnBean(String beanName, Class annotationType) { + Class handlerType = getType(beanName); + return AnnotationUtils.findAnnotation(handlerType, annotationType); + } + } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java index bd3173760cc..cfc014c29ec 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java @@ -29,6 +29,7 @@ import org.springframework.beans.FatalBeanException; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.CollectionUtils; /** * Default implementation of the {@link NamespaceHandlerResolver} interface. @@ -63,7 +64,7 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver private final String handlerMappingsLocation; /** Stores the mappings from namespace URI to NamespaceHandler class name / instance */ - private Map handlerMappings; + private Map handlerMappings; /** @@ -109,7 +110,7 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver * @return the located {@link NamespaceHandler}, or null if none found */ public NamespaceHandler resolve(String namespaceUri) { - Map handlerMappings = getHandlerMappings(); + Map handlerMappings = getHandlerMappings(); Object handlerOrClassName = handlerMappings.get(namespaceUri); if (handlerOrClassName == null) { return null; @@ -144,7 +145,7 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver /** * Load the specified NamespaceHandler mappings lazily. */ - private Map getHandlerMappings() { + private Map getHandlerMappings() { if (this.handlerMappings == null) { try { Properties mappings = @@ -152,7 +153,8 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver if (logger.isDebugEnabled()) { logger.debug("Loaded mappings [" + mappings + "]"); } - this.handlerMappings = new HashMap(mappings); + this.handlerMappings = new HashMap(); + CollectionUtils.mergePropertiesIntoMap(mappings, this.handlerMappings); } catch (IOException ex) { throw new IllegalStateException( diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java b/org.springframework.beans/src/main/java/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java index 3bbcd5a0373..36c185f9190 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java @@ -136,9 +136,7 @@ public class ArgumentConvertingMethodInvoker extends MethodInvoker { Method[] candidates = ReflectionUtils.getAllDeclaredMethods(getTargetClass()); int minTypeDiffWeight = Integer.MAX_VALUE; Object[] argumentsToUse = null; - - for (int i = 0; i < candidates.length; i++) { - Method candidate = candidates[i]; + for (Method candidate : candidates) { if (candidate.getName().equals(targetMethod)) { // Check if the inspected method has the correct number of parameters. Class[] paramTypes = candidate.getParameterTypes(); @@ -166,13 +164,11 @@ public class ArgumentConvertingMethodInvoker extends MethodInvoker { } } } - if (matchingMethod != null) { setArguments(argumentsToUse); return matchingMethod; } } - return null; } diff --git a/org.springframework.context.support/src/main/java/org/springframework/mail/MailSendException.java b/org.springframework.context.support/src/main/java/org/springframework/mail/MailSendException.java index f2d54cdeb84..9c69beb3da7 100644 --- a/org.springframework.context.support/src/main/java/org/springframework/mail/MailSendException.java +++ b/org.springframework.context.support/src/main/java/org/springframework/mail/MailSendException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.mail; import java.io.PrintStream; import java.io.PrintWriter; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -33,7 +32,7 @@ import org.springframework.util.ObjectUtils; */ public class MailSendException extends MailException { - private transient Map failedMessages; + private transient final Map failedMessages; private Exception[] messageExceptions; @@ -43,7 +42,7 @@ public class MailSendException extends MailException { * @param msg the detail message */ public MailSendException(String msg) { - super(msg); + this(msg, null); } /** @@ -53,6 +52,7 @@ public class MailSendException extends MailException { */ public MailSendException(String msg, Throwable cause) { super(msg, cause); + this.failedMessages = new LinkedHashMap(); } /** @@ -63,10 +63,10 @@ public class MailSendException extends MailException { * @param failedMessages Map of failed messages as keys and thrown * exceptions as values */ - public MailSendException(Map failedMessages) { + public MailSendException(Map failedMessages) { super(null); - this.failedMessages = new LinkedHashMap(failedMessages); - this.messageExceptions = (Exception[]) failedMessages.values().toArray(new Exception[failedMessages.size()]); + this.failedMessages = new LinkedHashMap(failedMessages); + this.messageExceptions = failedMessages.values().toArray(new Exception[failedMessages.size()]); } @@ -84,13 +84,12 @@ public class MailSendException extends MailException { *

NOTE: This Map will not be available after serialization. * Use {@link #getMessageExceptions()} in such a scenario, which will * be available after serialization as well. - * @return the Map of failed messages as keys and thrown exceptions as - * values, or an empty Map if no failed messages + * @return the Map of failed messages as keys and thrown exceptions as values * @see SimpleMailMessage * @see javax.mail.internet.MimeMessage */ - public final Map getFailedMessages() { - return (this.failedMessages != null ? this.failedMessages : Collections.EMPTY_MAP); + public final Map getFailedMessages() { + return this.failedMessages; } /** @@ -112,7 +111,7 @@ public class MailSendException extends MailException { return super.getMessage(); } else { - StringBuffer sb = new StringBuffer("Failed messages: "); + StringBuilder sb = new StringBuilder("Failed messages: "); for (int i = 0; i < this.messageExceptions.length; i++) { Exception subEx = this.messageExceptions[i]; sb.append(subEx.toString()); @@ -130,7 +129,7 @@ public class MailSendException extends MailException { return super.toString(); } else { - StringBuffer sb = new StringBuffer(getClass().getName()); + StringBuilder sb = new StringBuilder(getClass().getName()); sb.append("; nested exceptions (").append(this.messageExceptions.length).append(") are:"); for (int i = 0; i < this.messageExceptions.length; i++) { Exception subEx = this.messageExceptions[i]; diff --git a/org.springframework.context.support/src/main/java/org/springframework/mail/SimpleMailMessage.java b/org.springframework.context.support/src/main/java/org/springframework/mail/SimpleMailMessage.java index 929e8d97090..e5e5fe73b8c 100644 --- a/org.springframework.context.support/src/main/java/org/springframework/mail/SimpleMailMessage.java +++ b/org.springframework.context.support/src/main/java/org/springframework/mail/SimpleMailMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -201,7 +201,7 @@ public class SimpleMailMessage implements MailMessage, Serializable { @Override public String toString() { - StringBuffer sb = new StringBuffer("SimpleMailMessage: "); + StringBuilder sb = new StringBuilder("SimpleMailMessage: "); sb.append("from=").append(this.from).append("; "); sb.append("replyTo=").append(this.replyTo).append("; "); sb.append("to=").append(StringUtils.arrayToCommaDelimitedString(this.to)).append("; "); diff --git a/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java b/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java index 83f78f37659..96611dda988 100644 --- a/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java +++ b/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -298,14 +298,13 @@ public class JavaMailSenderImpl implements JavaMailSender { } public void send(SimpleMailMessage[] simpleMessages) throws MailException { - List mimeMessages = new ArrayList(simpleMessages.length); - for (int i = 0; i < simpleMessages.length; i++) { - SimpleMailMessage simpleMessage = simpleMessages[i]; + List mimeMessages = new ArrayList(simpleMessages.length); + for (SimpleMailMessage simpleMessage : simpleMessages) { MimeMailMessage message = new MimeMailMessage(createMimeMessage()); simpleMessage.copyTo(message); mimeMessages.add(message.getMimeMessage()); } - doSend((MimeMessage[]) mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages); + doSend(mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages); } @@ -348,13 +347,13 @@ public class JavaMailSenderImpl implements JavaMailSender { public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException { try { - List mimeMessages = new ArrayList(mimeMessagePreparators.length); - for (int i = 0; i < mimeMessagePreparators.length; i++) { + List mimeMessages = new ArrayList(mimeMessagePreparators.length); + for (MimeMessagePreparator preparator : mimeMessagePreparators) { MimeMessage mimeMessage = createMimeMessage(); - mimeMessagePreparators[i].prepare(mimeMessage); + preparator.prepare(mimeMessage); mimeMessages.add(mimeMessage); } - send((MimeMessage[]) mimeMessages.toArray(new MimeMessage[mimeMessages.size()])); + send(mimeMessages.toArray(new MimeMessage[mimeMessages.size()])); } catch (MailException ex) { throw ex; @@ -383,7 +382,7 @@ public class JavaMailSenderImpl implements JavaMailSender { * in case of failure when sending a message */ protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException { - Map failedMessages = new LinkedHashMap(); + Map failedMessages = new LinkedHashMap(); try { Transport transport = getTransport(getSession()); transport.connect(getHost(), getPort(), getUsername(), getPassword()); diff --git a/org.springframework.context.support/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java b/org.springframework.context.support/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java index a20789976f2..302f989f7b4 100644 --- a/org.springframework.context.support/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java +++ b/org.springframework.context.support/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.ui.velocity; import java.io.File; import java.io.IOException; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; @@ -33,6 +32,7 @@ import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PropertiesLoaderUtils; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** @@ -76,7 +76,7 @@ public class VelocityEngineFactory { private Resource configLocation; - private final Map velocityProperties = new HashMap(); + private final Map velocityProperties = new HashMap(); private String resourceLoaderPath; @@ -110,7 +110,7 @@ public class VelocityEngineFactory { * @see #setResourceLoaderPath */ public void setVelocityProperties(Properties velocityProperties) { - setVelocityPropertiesMap(velocityProperties); + CollectionUtils.mergePropertiesIntoMap(velocityProperties, this.velocityProperties); } /** @@ -118,7 +118,7 @@ public class VelocityEngineFactory { * like "ds.resource.loader.instance". * @see #setVelocityProperties */ - public void setVelocityPropertiesMap(Map velocityPropertiesMap) { + public void setVelocityPropertiesMap(Map velocityPropertiesMap) { if (velocityPropertiesMap != null) { this.velocityProperties.putAll(velocityPropertiesMap); } @@ -214,14 +214,14 @@ public class VelocityEngineFactory { */ public VelocityEngine createVelocityEngine() throws IOException, VelocityException { VelocityEngine velocityEngine = newVelocityEngine(); - Properties props = new Properties(); + Map props = new HashMap(); // Load config file if set. if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading Velocity config from [" + this.configLocation + "]"); } - PropertiesLoaderUtils.fillProperties(props, this.configLocation); + CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); } // Merge local properties if set. @@ -240,13 +240,8 @@ public class VelocityEngineFactory { } // Apply properties to VelocityEngine. - for (Iterator it = props.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - if (!(entry.getKey() instanceof String)) { - throw new IllegalArgumentException( - "Illegal property key [" + entry.getKey() + "]: only Strings allowed"); - } - velocityEngine.setProperty((String) entry.getKey(), entry.getValue()); + for (Map.Entry entry : props.entrySet()) { + velocityEngine.setProperty(entry.getKey(), entry.getValue()); } postProcessVelocityEngine(velocityEngine); @@ -301,7 +296,7 @@ public class VelocityEngineFactory { // Try to load via the file system, fall back to SpringResourceLoader // (for hot detection of template changes, if possible). try { - StringBuffer resolvedPath = new StringBuffer(); + StringBuilder resolvedPath = new StringBuilder(); String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath); for (int i = 0; i < paths.length; i++) { String path = paths[i]; diff --git a/org.springframework.context/src/main/java/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java b/org.springframework.context/src/main/java/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java index 3f0d7d14160..cc250cafdd1 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java +++ b/org.springframework.context/src/main/java/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ public class ContextSingletonBeanFactoryLocator extends SingletonBeanFactoryLoca private static final String DEFAULT_RESOURCE_LOCATION = "classpath*:beanRefContext.xml"; /** The keyed singleton instances */ - private static final Map instances = new HashMap(); + private static final Map instances = new HashMap(); /** @@ -101,7 +101,7 @@ public class ContextSingletonBeanFactoryLocator extends SingletonBeanFactoryLoca logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + instances.hashCode() + ", instances=" + instances); } - BeanFactoryLocator bfl = (BeanFactoryLocator) instances.get(resourceLocation); + BeanFactoryLocator bfl = instances.get(resourceLocation); if (bfl == null) { bfl = new ContextSingletonBeanFactoryLocator(resourceLocation); instances.put(resourceLocation, bfl); diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java b/org.springframework.context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java index 020a5235f79..67b2e4bd3f2 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java +++ b/org.springframework.context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java @@ -17,6 +17,7 @@ package org.springframework.context.support; import java.io.IOException; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -907,8 +908,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader // Implementation of ListableBeanFactory interface //--------------------------------------------------------------------- - public boolean containsBeanDefinition(String name) { - return getBeanFactory().containsBeanDefinition(name); + public boolean containsBeanDefinition(String beanName) { + return getBeanFactory().containsBeanDefinition(beanName); } public int getBeanDefinitionCount() { @@ -937,6 +938,23 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader return getBeanFactory().getBeansOfType(type, includePrototypes, allowEagerInit); } + public Map getBeansWithAnnotation(Class annotationType) + throws BeansException { + + return getBeanFactory().getBeansWithAnnotation(annotationType); + } + + public Map getBeansWithAnnotation( + Class annotationType, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + + return getBeanFactory().getBeansWithAnnotation(annotationType, includeNonSingletons, allowEagerInit); + } + + public A findAnnotationOnBean(String beanName, Class annotationType) { + return getBeanFactory().findAnnotationOnBean(beanName, annotationType); + } + //--------------------------------------------------------------------- // Implementation of HierarchicalBeanFactory interface diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/ContextTypeMatchClassLoader.java b/org.springframework.context/src/main/java/org/springframework/context/support/ContextTypeMatchClassLoader.java index 3f22caccd8c..d31a79c0962 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/support/ContextTypeMatchClassLoader.java +++ b/org.springframework.context/src/main/java/org/springframework/context/support/ContextTypeMatchClassLoader.java @@ -51,7 +51,7 @@ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements Smart /** Cache for byte array per class name */ - private final Map bytesCache = new HashMap(); + private final Map bytesCache = new HashMap(); public ContextTypeMatchClassLoader(ClassLoader parent) { @@ -96,7 +96,7 @@ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements Smart @Override protected Class loadClassForOverriding(String name) throws ClassNotFoundException { - byte[] bytes = (byte[]) bytesCache.get(name); + byte[] bytes = bytesCache.get(name); if (bytes == null) { bytes = loadBytesForClass(name); if (bytes != null) { diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/MessageSourceSupport.java b/org.springframework.context/src/main/java/org/springframework/context/support/MessageSourceSupport.java index 63b19f0c565..eebba78c747 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/support/MessageSourceSupport.java +++ b/org.springframework.context/src/main/java/org/springframework/context/support/MessageSourceSupport.java @@ -48,7 +48,7 @@ public abstract class MessageSourceSupport { * Used for passed-in default messages. MessageFormats for resolved * codes are cached on a specific basis in subclasses. */ - private final Map cachedMessageFormats = new HashMap(); + private final Map cachedMessageFormats = new HashMap(); /** @@ -94,7 +94,7 @@ public abstract class MessageSourceSupport { } MessageFormat messageFormat = null; synchronized (this.cachedMessageFormats) { - messageFormat = (MessageFormat) this.cachedMessageFormats.get(msg); + messageFormat = this.cachedMessageFormats.get(msg); if (messageFormat == null) { messageFormat = createMessageFormat(msg, locale); this.cachedMessageFormats.put(msg, messageFormat); diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java b/org.springframework.context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java index 04eae2b9ea2..556d71dbcc6 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java +++ b/org.springframework.context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java @@ -117,8 +117,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource /** Cache to hold already loaded properties per filename */ private final Map cachedProperties = new HashMap(); - /** Cache to hold merged loaded properties per basename */ - private final Map cachedMergedProperties = new HashMap(); + /** Cache to hold merged loaded properties per locale */ + private final Map cachedMergedProperties = new HashMap(); /** @@ -300,9 +300,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource } else { for (String basename : this.basenames) { - List filenames = calculateAllFilenames(basename, locale); - for (int j = 0; j < filenames.size(); j++) { - String filename = (String) filenames.get(j); + List filenames = calculateAllFilenames(basename, locale); + for (String filename : filenames) { PropertiesHolder propHolder = getProperties(filename); MessageFormat result = propHolder.getMessageFormat(code, locale); if (result != null) { @@ -325,7 +324,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource */ protected PropertiesHolder getMergedProperties(Locale locale) { synchronized (this.cachedMergedProperties) { - PropertiesHolder mergedHolder = (PropertiesHolder) this.cachedMergedProperties.get(locale); + PropertiesHolder mergedHolder = this.cachedMergedProperties.get(locale); if (mergedHolder != null) { return mergedHolder; } diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java b/org.springframework.context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java index e9ac2bb6b5a..9080ebd3332 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java +++ b/org.springframework.context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,8 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement * This allows for very efficient hash lookups, significantly faster * than the ResourceBundle class's own cache. */ - private final Map cachedResourceBundles = new HashMap(); + private final Map> cachedResourceBundles = + new HashMap>(); /** * Cache to hold already generated MessageFormats. @@ -79,7 +80,8 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement * very efficient hash lookups without concatenated keys. * @see #getMessageFormat */ - private final Map cachedBundleMessageFormats = new HashMap(); + private final Map>> cachedBundleMessageFormats = + new HashMap>>(); /** @@ -200,9 +202,9 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement */ protected ResourceBundle getResourceBundle(String basename, Locale locale) { synchronized (this.cachedResourceBundles) { - Map localeMap = (Map) this.cachedResourceBundles.get(basename); + Map localeMap = this.cachedResourceBundles.get(basename); if (localeMap != null) { - ResourceBundle bundle = (ResourceBundle) localeMap.get(locale); + ResourceBundle bundle = localeMap.get(locale); if (bundle != null) { return bundle; } @@ -210,7 +212,7 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement try { ResourceBundle bundle = doGetBundle(basename, locale); if (localeMap == null) { - localeMap = new HashMap(); + localeMap = new HashMap(); this.cachedResourceBundles.put(basename, localeMap); } localeMap.put(locale, bundle); @@ -254,12 +256,12 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement throws MissingResourceException { synchronized (this.cachedBundleMessageFormats) { - Map codeMap = (Map) this.cachedBundleMessageFormats.get(bundle); - Map localeMap = null; + Map> codeMap = this.cachedBundleMessageFormats.get(bundle); + Map localeMap = null; if (codeMap != null) { - localeMap = (Map) codeMap.get(code); + localeMap = codeMap.get(code); if (localeMap != null) { - MessageFormat result = (MessageFormat) localeMap.get(locale); + MessageFormat result = localeMap.get(locale); if (result != null) { return result; } @@ -269,11 +271,11 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement String msg = getStringOrNull(bundle, code); if (msg != null) { if (codeMap == null) { - codeMap = new HashMap(); + codeMap = new HashMap>(); this.cachedBundleMessageFormats.put(bundle, codeMap); } if (localeMap == null) { - localeMap = new HashMap(); + localeMap = new HashMap(); codeMap.put(code, localeMap); } MessageFormat result = createMessageFormat(msg, locale); diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/ResourceMapFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/context/support/ResourceMapFactoryBean.java deleted file mode 100644 index 1c7708437c2..00000000000 --- a/org.springframework.context/src/main/java/org/springframework/context/support/ResourceMapFactoryBean.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2002-2005 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.context.support; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.springframework.beans.factory.config.PropertiesFactoryBean; -import org.springframework.context.ResourceLoaderAware; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; - -/** - * FactoryBean that creates a Map with String keys and Resource values from - * properties, interpreting passed-in String values as resource locations. - * - *

Extends PropertiesFactoryBean to inherit the capability of defining - * local properties and loading from properties files. - * - *

Implements the ResourceLoaderAware interface to automatically use - * the context ResourceLoader if running in an ApplicationContext. - * Uses DefaultResourceLoader else. - * - * @author Juergen Hoeller - * @author Keith Donald - * @since 1.0.2 - * @see org.springframework.core.io.DefaultResourceLoader - */ -public class ResourceMapFactoryBean extends PropertiesFactoryBean implements ResourceLoaderAware { - - private String resourceBasePath = ""; - - private ResourceLoader resourceLoader = new DefaultResourceLoader(); - - - /** - * Set a base path to prepend to each resource location value - * in the properties file. - *

E.g.: resourceBasePath="/images", value="/test.gif" - * -> location="/images/test.gif" - */ - public void setResourceBasePath(String resourceBasePath) { - this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : ""); - } - - public void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); - } - - - @Override - public Class getObjectType() { - return Map.class; - } - - /** - * Create the Map instance, populated with keys and Resource values. - */ - @Override - protected Object createInstance() throws IOException { - Map resourceMap = new HashMap(); - Properties props = mergeProperties(); - for (Enumeration en = props.propertyNames(); en.hasMoreElements();) { - String key = (String) en.nextElement(); - String location = props.getProperty(key); - resourceMap.put(key, getResource(location)); - } - return resourceMap; - } - - /** - * Fetch the Resource handle for the given location, - * prepeding the resource base path. - * @param location the resource location - * @return the Resource handle - * @see org.springframework.core.io.ResourceLoader#getResource(String) - */ - protected Resource getResource(String location) { - return this.resourceLoader.getResource(this.resourceBasePath + location); - } - -} diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java index d8a750cac1a..4857f405e08 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractConfigurableMBeanInfoAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,8 @@ package org.springframework.jmx.export.assembler; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; - import javax.management.modelmbean.ModelMBeanNotificationInfo; import org.springframework.jmx.export.metadata.JmxMetadataUtils; @@ -41,7 +39,8 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef private ModelMBeanNotificationInfo[] notificationInfos; - private final Map notificationInfoMappings = new HashMap(); + private final Map notificationInfoMappings = + new HashMap(); public void setNotificationInfos(ManagedNotification[] notificationInfos) { @@ -53,13 +52,8 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef this.notificationInfos = infos; } - public void setNotificationInfoMappings(Map notificationInfoMappings) { - Iterator entries = notificationInfoMappings.entrySet().iterator(); - while (entries.hasNext()) { - Map.Entry entry = (Map.Entry) entries.next(); - if (!(entry.getKey() instanceof String)) { - throw new IllegalArgumentException("Property [notificationInfoMappings] only accepts Strings for Map keys"); - } + public void setNotificationInfoMappings(Map notificationInfoMappings) { + for (Map.Entry entry : notificationInfoMappings.entrySet()) { this.notificationInfoMappings.put(entry.getKey(), extractNotificationMetadata(entry.getValue())); } } @@ -68,16 +62,13 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef @Override protected ModelMBeanNotificationInfo[] getNotificationInfo(Object managedBean, String beanKey) { ModelMBeanNotificationInfo[] result = null; - if (StringUtils.hasText(beanKey)) { - result = (ModelMBeanNotificationInfo[]) this.notificationInfoMappings.get(beanKey); + result = this.notificationInfoMappings.get(beanKey); } - if (result == null) { result = this.notificationInfos; } - - return (result == null) ? new ModelMBeanNotificationInfo[0] : result; + return (result != null ? result : new ModelMBeanNotificationInfo[0]); } private ModelMBeanNotificationInfo[] extractNotificationMetadata(Object mapValue) { @@ -87,9 +78,8 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef } else if (mapValue instanceof Collection) { Collection col = (Collection) mapValue; - List result = new ArrayList(); - for (Iterator iterator = col.iterator(); iterator.hasNext();) { - Object colValue = iterator.next(); + List result = new ArrayList(); + for (Object colValue : col) { if (!(colValue instanceof ManagedNotification)) { throw new IllegalArgumentException( "Property 'notificationInfoMappings' only accepts ManagedNotifications for Map values"); @@ -97,7 +87,7 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef ManagedNotification mn = (ManagedNotification) colValue; result.add(JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn)); } - return (ModelMBeanNotificationInfo[]) result.toArray(new ModelMBeanNotificationInfo[result.size()]); + return result.toArray(new ModelMBeanNotificationInfo[result.size()]); } else { throw new IllegalArgumentException( diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssembler.java b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssembler.java index cf4d01643e2..9d30cbb10ff 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssembler.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,10 +88,9 @@ public class InterfaceBasedMBeanInfoAssembler extends AbstractConfigurableMBeanI */ public void setManagedInterfaces(Class[] managedInterfaces) { if (managedInterfaces != null) { - for (int x = 0; x < managedInterfaces.length; x++) { - if (!managedInterfaces[x].isInterface()) { - throw new IllegalArgumentException( - "Management interface [" + managedInterfaces[x].getName() + "] is no interface"); + for (Class ifc : managedInterfaces) { + if (ifc.isInterface()) { + throw new IllegalArgumentException("Management interface [" + ifc.getName() + "] is no interface"); } } } @@ -126,7 +125,7 @@ public class InterfaceBasedMBeanInfoAssembler extends AbstractConfigurableMBeanI * @return the resolved interface mappings (with Class objects as values) */ private Map resolveInterfaceMappings(Properties mappings) { - Map resolvedMappings = new HashMap(mappings.size()); + Map resolvedMappings = new HashMap(mappings.size()); for (Enumeration en = mappings.propertyNames(); en.hasMoreElements();) { String beanKey = (String) en.nextElement(); String[] classNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey)); @@ -229,12 +228,10 @@ public class InterfaceBasedMBeanInfoAssembler extends AbstractConfigurableMBeanI } if (ifaces != null) { - for (int i = 0; i < ifaces.length; i++) { - Method[] methods = ifaces[i].getMethods(); - for (int j = 0; j < methods.length; j++) { - Method ifaceMethod = methods[j]; - if (ifaceMethod.getName().equals(method.getName()) && - Arrays.equals(ifaceMethod.getParameterTypes(), method.getParameterTypes())) { + for (Class ifc : ifaces) { + for (Method ifcMethod : ifc.getMethods()) { + if (ifcMethod.getName().equals(method.getName()) && + Arrays.equals(ifcMethod.getParameterTypes(), method.getParameterTypes())) { return true; } } diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssembler.java b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssembler.java index f58adb32f46..ba77fd95b9a 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssembler.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssembler.java @@ -57,9 +57,9 @@ import org.springframework.util.StringUtils; */ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBeanInfoAssembler { - private Set ignoredMethods; + private Set ignoredMethods; - private Map ignoredMethodMappings; + private Map> ignoredMethodMappings; /** @@ -69,7 +69,7 @@ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBean * @see #setIgnoredMethodMappings(java.util.Properties) */ public void setIgnoredMethods(String[] ignoredMethodNames) { - this.ignoredMethods = new HashSet(Arrays.asList(ignoredMethodNames)); + this.ignoredMethods = new HashSet(Arrays.asList(ignoredMethodNames)); } /** @@ -80,11 +80,11 @@ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBean * Spring will check these mappings first. */ public void setIgnoredMethodMappings(Properties mappings) { - this.ignoredMethodMappings = new HashMap(); + this.ignoredMethodMappings = new HashMap>(); for (Enumeration en = mappings.keys(); en.hasMoreElements();) { String beanKey = (String) en.nextElement(); String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey)); - this.ignoredMethodMappings.put(beanKey, new HashSet(Arrays.asList(methodNames))); + this.ignoredMethodMappings.put(beanKey, new HashSet(Arrays.asList(methodNames))); } } @@ -113,7 +113,7 @@ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBean */ protected boolean isNotIgnored(Method method, String beanKey) { if (this.ignoredMethodMappings != null) { - Set methodNames = (Set) this.ignoredMethodMappings.get(beanKey); + Set methodNames = this.ignoredMethodMappings.get(beanKey); if (methodNames != null) { return !methodNames.contains(method.getName()); } diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssembler.java b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssembler.java index f4b5095d3bd..d047b4b2e8e 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssembler.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,12 +57,12 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean /** * Stores the set of method names to use for creating the management interface. */ - private Set managedMethods; + private Set managedMethods; /** * Stores the mappings of bean keys to an array of method names. */ - private Map methodMappings; + private Map> methodMappings; /** @@ -73,7 +73,7 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean * @see #setMethodMappings */ public void setManagedMethods(String[] methodNames) { - this.managedMethods = new HashSet(Arrays.asList(methodNames)); + this.managedMethods = new HashSet(Arrays.asList(methodNames)); } /** @@ -84,11 +84,11 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean * @param mappings the mappins of bean keys to method names */ public void setMethodMappings(Properties mappings) { - this.methodMappings = new HashMap(); + this.methodMappings = new HashMap>(); for (Enumeration en = mappings.keys(); en.hasMoreElements();) { String beanKey = (String) en.nextElement(); String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey)); - this.methodMappings.put(beanKey, new HashSet(Arrays.asList(methodNames))); + this.methodMappings.put(beanKey, new HashSet(Arrays.asList(methodNames))); } } @@ -110,7 +110,7 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean protected boolean isMatch(Method method, String beanKey) { if (this.methodMappings != null) { - Set methodNames = (Set) this.methodMappings.get(beanKey); + Set methodNames = this.methodMappings.get(beanKey); if (methodNames != null) { return methodNames.contains(method.getName()); } diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/JndiCallback.java b/org.springframework.context/src/main/java/org/springframework/jndi/JndiCallback.java index 3d4ee57e75e..23d6ebb18c6 100644 --- a/org.springframework.context/src/main/java/org/springframework/jndi/JndiCallback.java +++ b/org.springframework.context/src/main/java/org/springframework/jndi/JndiCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,21 +29,21 @@ import javax.naming.NamingException; * interface, as JndiTemplate provides all usual JNDI operations via * convenience methods. * + * @author Rod Johnson * @see JndiTemplate * @see org.springframework.jdbc.core.JdbcTemplate - * @author Rod Johnson */ -public interface JndiCallback { +public interface JndiCallback { /** * Do something with the given JNDI context. - * Implementations don't need to worry about error handling + *

Implementations don't need to worry about error handling * or cleanup, as the JndiTemplate class will handle this. * @param ctx the current JNDI context * @throws NamingException if thrown by JNDI methods * @return a result object, or null */ - Object doInContext(Context ctx) throws NamingException; + T doInContext(Context ctx) throws NamingException; } diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/JndiLocatorSupport.java b/org.springframework.context/src/main/java/org/springframework/jndi/JndiLocatorSupport.java index 3dd50db3b3d..3b1af83a9e3 100644 --- a/org.springframework.context/src/main/java/org/springframework/jndi/JndiLocatorSupport.java +++ b/org.springframework.context/src/main/java/org/springframework/jndi/JndiLocatorSupport.java @@ -87,10 +87,10 @@ public abstract class JndiLocatorSupport extends JndiAccessor { * @throws NamingException if the JNDI lookup failed * @see #setResourceRef */ - protected Object lookup(String jndiName, Class requiredType) throws NamingException { + protected T lookup(String jndiName, Class requiredType) throws NamingException { Assert.notNull(jndiName, "'jndiName' must not be null"); String convertedName = convertJndiName(jndiName); - Object jndiObject = null; + T jndiObject = null; try { jndiObject = getJndiTemplate().lookup(convertedName, requiredType); } diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/JndiTemplate.java b/org.springframework.context/src/main/java/org/springframework/jndi/JndiTemplate.java index 9e6c1b61a1e..a9dda09e9c7 100644 --- a/org.springframework.context/src/main/java/org/springframework/jndi/JndiTemplate.java +++ b/org.springframework.context/src/main/java/org/springframework/jndi/JndiTemplate.java @@ -18,7 +18,6 @@ package org.springframework.jndi; import java.util.Hashtable; import java.util.Properties; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; @@ -82,7 +81,7 @@ public class JndiTemplate { * @throws NamingException thrown by the callback implementation * @see #createInitialContext */ - public Object execute(JndiCallback contextCallback) throws NamingException { + public T execute(JndiCallback contextCallback) throws NamingException { Context ctx = getContext(); try { return contextCallback.doInContext(ctx); @@ -174,13 +173,14 @@ public class JndiTemplate { * @throws NamingException if there is no object with the given * name bound to JNDI */ - public Object lookup(String name, Class requiredType) throws NamingException { + @SuppressWarnings("unchecked") + public T lookup(String name, Class requiredType) throws NamingException { Object jndiObject = lookup(name); if (requiredType != null && !requiredType.isInstance(jndiObject)) { throw new TypeMismatchNamingException( name, requiredType, (jndiObject != null ? jndiObject.getClass() : null)); } - return jndiObject; + return (T) jndiObject; } /** diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java b/org.springframework.context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java index fd76d701369..e21081c028a 100644 --- a/org.springframework.context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java +++ b/org.springframework.context/src/main/java/org/springframework/jndi/support/SimpleJndiBeanFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,13 +60,13 @@ import org.springframework.jndi.TypeMismatchNamingException; public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFactory { /** JNDI names of resources that are known to be shareable, i.e. can be cached */ - private final Set shareableResources = new HashSet(); + private final Set shareableResources = new HashSet(); /** Cache of shareable singleton objects: bean name --> bean instance */ - private final Map singletonObjects = new HashMap(); + private final Map singletonObjects = new HashMap(); /** Cache of the types of nonshareable resources: bean name --> bean type */ - private final Map resourceTypes = new HashMap(); + private final Map resourceTypes = new HashMap(); public SimpleJndiBeanFactory() { @@ -96,10 +96,10 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac public Object getBean(String name) throws BeansException { - return getBean(name, (Class) null); + return getBean(name, Object.class); } - public Object getBean(String name, Class requiredType) throws BeansException { + public T getBean(String name, Class requiredType) throws BeansException { try { if (isSingleton(name)) { return doGetSingleton(name, requiredType); @@ -170,7 +170,8 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac } - private Object doGetSingleton(String name, Class requiredType) throws NamingException { + @SuppressWarnings("unchecked") + private T doGetSingleton(String name, Class requiredType) throws NamingException { synchronized (this.singletonObjects) { if (this.singletonObjects.containsKey(name)) { Object jndiObject = this.singletonObjects.get(name); @@ -178,9 +179,9 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac throw new TypeMismatchNamingException( convertJndiName(name), requiredType, (jndiObject != null ? jndiObject.getClass() : null)); } - return jndiObject; + return (T) jndiObject; } - Object jndiObject = lookup(name, requiredType); + T jndiObject = lookup(name, requiredType); this.singletonObjects.put(name, jndiObject); return jndiObject; } @@ -194,7 +195,7 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac else { synchronized (this.resourceTypes) { if (this.resourceTypes.containsKey(name)) { - return (Class) this.resourceTypes.get(name); + return this.resourceTypes.get(name); } else { Object jndiObject = lookup(name, null); diff --git a/org.springframework.context/src/main/java/org/springframework/remoting/support/RemoteInvocation.java b/org.springframework.context/src/main/java/org/springframework/remoting/support/RemoteInvocation.java index 9d6e68ff60c..491cddbcd51 100644 --- a/org.springframework.context/src/main/java/org/springframework/remoting/support/RemoteInvocation.java +++ b/org.springframework.context/src/main/java/org/springframework/remoting/support/RemoteInvocation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ public class RemoteInvocation implements Serializable { private Object[] arguments; - private Map attributes; + private Map attributes; /** @@ -143,7 +143,7 @@ public class RemoteInvocation implements Serializable { */ public void addAttribute(String key, Serializable value) throws IllegalStateException { if (this.attributes == null) { - this.attributes = new HashMap(); + this.attributes = new HashMap(); } if (this.attributes.containsKey(key)) { throw new IllegalStateException("There is already an attribute with key '" + key + "' bound"); @@ -162,7 +162,7 @@ public class RemoteInvocation implements Serializable { if (this.attributes == null) { return null; } - return (Serializable) this.attributes.get(key); + return this.attributes.get(key); } /** @@ -172,7 +172,7 @@ public class RemoteInvocation implements Serializable { * @see #addAttribute * @see #getAttribute */ - public void setAttributes(Map attributes) { + public void setAttributes(Map attributes) { this.attributes = attributes; } @@ -183,7 +183,7 @@ public class RemoteInvocation implements Serializable { * @see #addAttribute * @see #getAttribute */ - public Map getAttributes() { + public Map getAttributes() { return this.attributes; } diff --git a/org.springframework.context/src/main/java/org/springframework/remoting/support/SimpleHttpServerFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/remoting/support/SimpleHttpServerFactoryBean.java index b1f685fa914..3043fb600ed 100644 --- a/org.springframework.context/src/main/java/org/springframework/remoting/support/SimpleHttpServerFactoryBean.java +++ b/org.springframework.context/src/main/java/org/springframework/remoting/support/SimpleHttpServerFactoryBean.java @@ -34,7 +34,6 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.task.TaskExecutor; -import org.springframework.core.task.support.ConcurrentExecutorAdapter; /** * {@link org.springframework.beans.factory.FactoryBean} that creates a simple @@ -120,7 +119,7 @@ public class SimpleHttpServerFactoryBean implements FactoryBean, InitializingBea * @see com.sun.net.httpserver.HttpServer#setExecutor */ public void setTaskExecutor(TaskExecutor executor) { - this.executor = new ConcurrentExecutorAdapter(executor); + this.executor = executor; } /** diff --git a/org.springframework.context/src/main/java/org/springframework/validation/BindException.java b/org.springframework.context/src/main/java/org/springframework/validation/BindException.java index b71869203a4..92b82940ac5 100644 --- a/org.springframework.context/src/main/java/org/springframework/validation/BindException.java +++ b/org.springframework.context/src/main/java/org/springframework/validation/BindException.java @@ -42,16 +42,6 @@ import org.springframework.util.Assert; */ public class BindException extends Exception implements BindingResult { - /** - * Prefix for the name of the BindException instance in a model, - * followed by the object name. - * @deprecated in favor of BindingResult.MODEL_KEY_PREFIX - * @see BindingResult#MODEL_KEY_PREFIX - */ - @Deprecated - public static final String ERROR_KEY_PREFIX = BindException.class.getName() + "."; - - private final BindingResult bindingResult; @@ -208,7 +198,7 @@ public class BindException extends Exception implements BindingResult { return this.bindingResult.getTarget(); } - public Map getModel() { + public Map getModel() { return this.bindingResult.getModel(); } diff --git a/org.springframework.context/src/main/java/org/springframework/validation/DataBinder.java b/org.springframework.context/src/main/java/org/springframework/validation/DataBinder.java index 4dce49550bf..105a16425ed 100644 --- a/org.springframework.context/src/main/java/org/springframework/validation/DataBinder.java +++ b/org.springframework.context/src/main/java/org/springframework/validation/DataBinder.java @@ -499,8 +499,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter { */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); - for (int i = 0; i < pvs.length; i++) { - PropertyValue pv = pvs[i]; + for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); @@ -545,16 +544,14 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter { protected void checkRequiredFields(MutablePropertyValues mpvs) { String[] requiredFields = getRequiredFields(); if (!ObjectUtils.isEmpty(requiredFields)) { - Map propertyValues = new HashMap(); + Map propertyValues = new HashMap(); PropertyValue[] pvs = mpvs.getPropertyValues(); - for (int i = 0; i < pvs.length; i++) { - PropertyValue pv = pvs[i]; + for (PropertyValue pv : pvs) { String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); propertyValues.put(canonicalName, pv); } - for (int i = 0; i < requiredFields.length; i++) { - String field = requiredFields[i]; - PropertyValue pv = (PropertyValue) propertyValues.get(field); + for (String field : requiredFields) { + PropertyValue pv = propertyValues.get(field); if (pv == null || pv.getValue() == null || (pv.getValue() instanceof String && !StringUtils.hasText((String) pv.getValue()))) { // Use bind error processor to create FieldError. @@ -589,9 +586,8 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter { } catch (PropertyBatchUpdateException ex) { // Use bind error processor to create FieldErrors. - PropertyAccessException[] exs = ex.getPropertyAccessExceptions(); - for (int i = 0; i < exs.length; i++) { - getBindingErrorProcessor().processPropertyAccessException(exs[i], getInternalBindingResult()); + for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) { + getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult()); } } } diff --git a/org.springframework.core/src/main/java/org/springframework/core/AttributeAccessorSupport.java b/org.springframework.core/src/main/java/org/springframework/core/AttributeAccessorSupport.java index a6bc52560f3..a2424de60b1 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/AttributeAccessorSupport.java +++ b/org.springframework.core/src/main/java/org/springframework/core/AttributeAccessorSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.core; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; -import java.util.Set; import org.springframework.util.Assert; @@ -36,7 +35,7 @@ import org.springframework.util.Assert; public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable { /** Map with String keys and Object values */ - private final Map attributes = new LinkedHashMap(); + private final Map attributes = new LinkedHashMap(); public void setAttribute(String name, Object value) { @@ -65,8 +64,7 @@ public abstract class AttributeAccessorSupport implements AttributeAccessor, Ser } public String[] attributeNames() { - Set attributeNames = this.attributes.keySet(); - return (String[]) attributeNames.toArray(new String[attributeNames.size()]); + return this.attributes.keySet().toArray(new String[this.attributes.size()]); } @@ -77,8 +75,7 @@ public abstract class AttributeAccessorSupport implements AttributeAccessor, Ser protected void copyAttributesFrom(AttributeAccessor source) { Assert.notNull(source, "Source must not be null"); String[] attributeNames = source.attributeNames(); - for (int i = 0; i < attributeNames.length; i++) { - String attributeName = attributeNames[i]; + for (String attributeName : attributeNames) { setAttribute(attributeName, source.getAttribute(attributeName)); } } diff --git a/org.springframework.core/src/main/java/org/springframework/core/BridgeMethodResolver.java b/org.springframework.core/src/main/java/org/springframework/core/BridgeMethodResolver.java index a29a2f0d2c8..ea47b61b45e 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/BridgeMethodResolver.java +++ b/org.springframework.core/src/main/java/org/springframework/core/BridgeMethodResolver.java @@ -64,10 +64,9 @@ public abstract class BridgeMethodResolver { } // Gather all methods with matching name and parameter size. - List candidateMethods = new ArrayList(); + List candidateMethods = new ArrayList(); Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass()); - for (int i = 0; i < methods.length; i++) { - Method candidateMethod = methods[i]; + for (Method candidateMethod : methods) { if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) { candidateMethods.add(candidateMethod); } @@ -76,7 +75,7 @@ public abstract class BridgeMethodResolver { Method result; // Now perform simple quick checks. if (candidateMethods.size() == 1) { - result = (Method) candidateMethods.get(0); + result = candidateMethods.get(0); } else { result = searchCandidates(candidateMethods, bridgeMethod); @@ -86,7 +85,6 @@ public abstract class BridgeMethodResolver { throw new IllegalStateException( "Unable to locate bridged method for bridge method '" + bridgeMethod + "'"); } - return result; } @@ -96,10 +94,9 @@ public abstract class BridgeMethodResolver { * @param bridgeMethod the bridge method * @return the bridged method, or null if none found */ - private static Method searchCandidates(List candidateMethods, Method bridgeMethod) { - Map typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass()); - for (int i = 0; i < candidateMethods.size(); i++) { - Method candidateMethod = (Method) candidateMethods.get(i); + private static Method searchCandidates(List candidateMethods, Method bridgeMethod) { + Map typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass()); + for (Method candidateMethod : candidateMethods) { if (isBridgeMethodFor(bridgeMethod, candidateMethod, typeParameterMap)) { return candidateMethod; } @@ -123,7 +120,7 @@ public abstract class BridgeMethodResolver { * Determines whether or not the bridge {@link Method} is the bridge for the * supplied candidate {@link Method}. */ - static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map typeVariableMap) { + static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map typeVariableMap) { if (isResolvedTypeMatch(candidateMethod, bridgeMethod, typeVariableMap)) { return true; } @@ -149,9 +146,8 @@ public abstract class BridgeMethodResolver { // Search interfaces. Class[] interfaces = ClassUtils.getAllInterfacesForClass(bridgeMethod.getDeclaringClass()); - for (int i = 0; i < interfaces.length; i++) { - Class anInterface = interfaces[i]; - Method method = searchForMatch(anInterface, bridgeMethod); + for (Class ifc : interfaces) { + Method method = searchForMatch(ifc, bridgeMethod); if (method != null && !method.isBridge()) { return method; } @@ -166,7 +162,9 @@ public abstract class BridgeMethodResolver { * are equal after resolving all {@link TypeVariable TypeVariables} using the supplied * TypeVariable Map, otherwise returns false. */ - private static boolean isResolvedTypeMatch(Method genericMethod, Method candidateMethod, Map typeVariableMap) { + private static boolean isResolvedTypeMatch( + Method genericMethod, Method candidateMethod, Map typeVariableMap) { + Type[] genericParameters = genericMethod.getGenericParameterTypes(); Class[] candidateParameters = candidateMethod.getParameterTypes(); if (genericParameters.length != candidateParameters.length) { diff --git a/org.springframework.core/src/main/java/org/springframework/core/GenericCollectionTypeResolver.java b/org.springframework.core/src/main/java/org/springframework/core/GenericCollectionTypeResolver.java index 51fcafe7d01..0df5d9e75bb 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/GenericCollectionTypeResolver.java +++ b/org.springframework.core/src/main/java/org/springframework/core/GenericCollectionTypeResolver.java @@ -34,12 +34,8 @@ import java.util.Map; * target type of values to be added to a collection or map * (to be able to attempt type conversion if appropriate). * - *

Only usable on Java 5. Use an appropriate {@link JdkVersion} check - * before calling this class, if a fallback for JDK 1.4 is desirable. - * * @author Juergen Hoeller * @since 2.0 - * @see org.springframework.beans.BeanWrapper */ public abstract class GenericCollectionTypeResolver { @@ -283,7 +279,7 @@ public abstract class GenericCollectionTypeResolver { Type resolvedType = type; if (type instanceof TypeVariable && methodParam != null && methodParam.typeVariableMap != null) { - Type mappedType = (Type) methodParam.typeVariableMap.get(type); + Type mappedType = methodParam.typeVariableMap.get((TypeVariable) type); if (mappedType != null) { resolvedType = mappedType; } @@ -322,7 +318,7 @@ public abstract class GenericCollectionTypeResolver { int nextLevel = currentLevel + 1; Integer currentTypeIndex = (methodParam != null ? methodParam.getTypeIndexForLevel(nextLevel) : null); // Default is last parameter type: Collection element or Map value. - int indexToUse = (currentTypeIndex != null ? currentTypeIndex.intValue() : paramTypes.length - 1); + int indexToUse = (currentTypeIndex != null ? currentTypeIndex : paramTypes.length - 1); Type paramType = paramTypes[indexToUse]; return extractType(methodParam, paramType, source, typeIndex, nestingLevel, nextLevel); } @@ -339,7 +335,7 @@ public abstract class GenericCollectionTypeResolver { } Type paramType = paramTypes[typeIndex]; if (paramType instanceof TypeVariable && methodParam != null && methodParam.typeVariableMap != null) { - Type mappedType = (Type) methodParam.typeVariableMap.get(paramType); + Type mappedType = methodParam.typeVariableMap.get((TypeVariable) paramType); if (mappedType != null) { paramType = mappedType; } @@ -399,8 +395,7 @@ public abstract class GenericCollectionTypeResolver { } Type[] ifcs = clazz.getGenericInterfaces(); if (ifcs != null) { - for (int i = 0; i < ifcs.length; i++) { - Type ifc = ifcs[i]; + for (Type ifc : ifcs) { Type rawType = ifc; if (ifc instanceof ParameterizedType) { rawType = ((ParameterizedType) ifc).getRawType(); diff --git a/org.springframework.core/src/main/java/org/springframework/core/GenericTypeResolver.java b/org.springframework.core/src/main/java/org/springframework/core/GenericTypeResolver.java index 6826571ad8d..4e3dfc534cb 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/GenericTypeResolver.java +++ b/org.springframework.core/src/main/java/org/springframework/core/GenericTypeResolver.java @@ -34,9 +34,6 @@ import org.springframework.util.Assert; *

Mainly intended for usage within the framework, resolving method * parameter types even when they are declared generically. * - *

Only usable on Java 5. Use an appropriate JdkVersion check before - * calling this class, if a fallback for JDK 1.4 is desirable. - * * @author Juergen Hoeller * @author Rob Harrop * @since 2.5.2 @@ -46,7 +43,8 @@ import org.springframework.util.Assert; public abstract class GenericTypeResolver { /** Cache from Class to TypeVariable Map */ - private static final Map typeVariableCache = Collections.synchronizedMap(new WeakHashMap()); + private static final Map> typeVariableCache = + Collections.synchronizedMap(new WeakHashMap>()); /** @@ -78,7 +76,7 @@ public abstract class GenericTypeResolver { public static Class resolveParameterType(MethodParameter methodParam, Class clazz) { Type genericType = getTargetType(methodParam); Assert.notNull(clazz, "Class must not be null"); - Map typeVariableMap = getTypeVariableMap(clazz); + Map typeVariableMap = getTypeVariableMap(clazz); Type rawType = getRawType(genericType, typeVariableMap); Class result = (rawType instanceof Class ? (Class) rawType : methodParam.getParameterType()); methodParam.setParameterType(result); @@ -96,7 +94,7 @@ public abstract class GenericTypeResolver { Assert.notNull(method, "Method must not be null"); Type genericType = method.getGenericReturnType(); Assert.notNull(clazz, "Class must not be null"); - Map typeVariableMap = getTypeVariableMap(clazz); + Map typeVariableMap = getTypeVariableMap(clazz); Type rawType = getRawType(genericType, typeVariableMap); return (rawType instanceof Class ? (Class) rawType : method.getReturnType()); } @@ -108,7 +106,7 @@ public abstract class GenericTypeResolver { * @param typeVariableMap the TypeVariable Map to resolved against * @return the type if it resolves to a Class, or Object.class otherwise */ - static Class resolveType(Type genericType, Map typeVariableMap) { + static Class resolveType(Type genericType, Map typeVariableMap) { Type rawType = getRawType(genericType, typeVariableMap); return (rawType instanceof Class ? (Class) rawType : Object.class); } @@ -119,11 +117,11 @@ public abstract class GenericTypeResolver { * @param typeVariableMap the TypeVariable Map to resolved against * @return the resolved raw type */ - static Type getRawType(Type genericType, Map typeVariableMap) { + static Type getRawType(Type genericType, Map typeVariableMap) { Type resolvedType = genericType; if (genericType instanceof TypeVariable) { TypeVariable tv = (TypeVariable) genericType; - resolvedType = (Type) typeVariableMap.get(tv); + resolvedType = typeVariableMap.get(tv); if (resolvedType == null) { resolvedType = extractBoundForTypeVariable(tv); } @@ -141,11 +139,11 @@ public abstract class GenericTypeResolver { * {@link Class} for the specified {@link Class}. Searches all super types, * enclosing types and interfaces. */ - static Map getTypeVariableMap(Class clazz) { - Map typeVariableMap = (Map) typeVariableCache.get(clazz); + static Map getTypeVariableMap(Class clazz) { + Map typeVariableMap = typeVariableCache.get(clazz); if (typeVariableMap == null) { - typeVariableMap = new HashMap(); + typeVariableMap = new HashMap(); // interfaces extractTypeVariablesFromGenericInterfaces(clazz.getGenericInterfaces(), typeVariableMap); @@ -195,9 +193,8 @@ public abstract class GenericTypeResolver { return bound; } - private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces, Map typeVariableMap) { - for (int i = 0; i < genericInterfaces.length; i++) { - Type genericInterface = genericInterfaces[i]; + private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces, Map typeVariableMap) { + for (Type genericInterface : genericInterfaces) { if (genericInterface instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericInterface; populateTypeMapFromParameterizedType(pt, typeVariableMap); @@ -229,7 +226,7 @@ public abstract class GenericTypeResolver { * For 'FooImpl' the following mappings would be added to the {@link Map}: * {S=java.lang.String, T=java.lang.Integer}. */ - private static void populateTypeMapFromParameterizedType(ParameterizedType type, Map typeVariableMap) { + private static void populateTypeMapFromParameterizedType(ParameterizedType type, Map typeVariableMap) { if (type.getRawType() instanceof Class) { Type[] actualTypeArguments = type.getActualTypeArguments(); TypeVariable[] typeVariables = ((Class) type.getRawType()).getTypeParameters(); @@ -249,7 +246,7 @@ public abstract class GenericTypeResolver { // We have a type that is parameterized at instantiation time // the nearest match on the bridge method will be the bounded type. TypeVariable typeVariableArgument = (TypeVariable) actualTypeArgument; - Type resolvedType = (Type) typeVariableMap.get(typeVariableArgument); + Type resolvedType = typeVariableMap.get(typeVariableArgument); if (resolvedType == null) { resolvedType = extractBoundForTypeVariable(typeVariableArgument); } diff --git a/org.springframework.core/src/main/java/org/springframework/core/MethodParameter.java b/org.springframework.core/src/main/java/org/springframework/core/MethodParameter.java index c3633786853..17607e6ec2c 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/MethodParameter.java +++ b/org.springframework.core/src/main/java/org/springframework/core/MethodParameter.java @@ -19,6 +19,8 @@ package org.springframework.core; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; @@ -59,7 +61,7 @@ public class MethodParameter { /** Map from Integer level to Integer type index */ private Map typeIndexesPerLevel; - Map typeVariableMap; + Map typeVariableMap; /** diff --git a/org.springframework.core/src/main/java/org/springframework/core/task/TaskExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/task/TaskExecutor.java index 800806f74b7..a13738578a2 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/task/TaskExecutor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/task/TaskExecutor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.core.task; +import java.util.concurrent.Executor; + /** * Simple task executor interface that abstracts the execution * of a {@link Runnable}. @@ -24,15 +26,16 @@ package org.springframework.core.task; * such as: synchronous, asynchronous, using a thread pool, and more. * *

Equivalent to JDK 1.5's {@link java.util.concurrent.Executor} - * interface. Separate mainly for compatibility with JDK 1.4. - * Implementations can simply implement the JDK 1.5 Executor - * interface as well, as it defines the exact same method signature. + * interface; extending it now in Spring 3.0, so that clients may declare + * a dependency on an Executor and receive any TaskExecutor implementation. + * This interface remains separate from the standard Executor interface + * mainly for backwards compatibility with JDK 1.4 in Spring 2.x. * * @author Juergen Hoeller * @since 2.0 * @see java.util.concurrent.Executor */ -public interface TaskExecutor { +public interface TaskExecutor extends Executor { /** * Execute the given task. diff --git a/org.springframework.core/src/main/java/org/springframework/core/task/TaskRejectedException.java b/org.springframework.core/src/main/java/org/springframework/core/task/TaskRejectedException.java index 51d3e7c15d1..1f5ee705f73 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/task/TaskRejectedException.java +++ b/org.springframework.core/src/main/java/org/springframework/core/task/TaskRejectedException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.core.task; -import org.springframework.core.NestedRuntimeException; +import java.util.concurrent.RejectedExecutionException; /** * Exception thrown when a {@link TaskExecutor} rejects to accept @@ -27,7 +27,7 @@ import org.springframework.core.NestedRuntimeException; * @see TaskExecutor#execute(Runnable) * @see TaskTimeoutException */ -public class TaskRejectedException extends NestedRuntimeException { +public class TaskRejectedException extends RejectedExecutionException { /** * Create a new TaskRejectedException diff --git a/org.springframework.core/src/main/java/org/springframework/core/task/support/ConcurrentExecutorAdapter.java b/org.springframework.core/src/main/java/org/springframework/core/task/support/ConcurrentExecutorAdapter.java index 230e888c7a1..3031e3cc3a7 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/task/support/ConcurrentExecutorAdapter.java +++ b/org.springframework.core/src/main/java/org/springframework/core/task/support/ConcurrentExecutorAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,21 +17,19 @@ package org.springframework.core.task.support; import java.util.concurrent.Executor; -import java.util.concurrent.RejectedExecutionException; import org.springframework.core.task.TaskExecutor; -import org.springframework.core.task.TaskRejectedException; import org.springframework.util.Assert; /** - * Adapter that exposes the {@link java.util.concurrent.Executor java.util.concurrent.Executor} + * Adapter that exposes the {@link java.util.concurrent.Executor} * interface for any Spring {@link org.springframework.core.task.TaskExecutor}. - * Follows the JDK executor contract for exception handling. * * @author Juergen Hoeller * @since 2.5 * @see java.util.concurrent.Executor * @see org.springframework.core.task.TaskExecutor + * @deprecated as of Spring 3.0 since TaskExecutor itself implements the Executor interface now */ public class ConcurrentExecutorAdapter implements Executor { @@ -49,12 +47,7 @@ public class ConcurrentExecutorAdapter implements Executor { public void execute(Runnable command) { - try { - this.taskExecutor.execute(command); - } - catch (TaskRejectedException ex) { - throw new RejectedExecutionException(ex.getMessage(), ex); - } + this.taskExecutor.execute(command); } } diff --git a/org.springframework.core/src/main/java/org/springframework/util/WeakReferenceMonitor.java b/org.springframework.core/src/main/java/org/springframework/util/WeakReferenceMonitor.java index 57aeae99a0e..85e8b22cd56 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/WeakReferenceMonitor.java +++ b/org.springframework.core/src/main/java/org/springframework/util/WeakReferenceMonitor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,10 +51,11 @@ public class WeakReferenceMonitor { private static final Log logger = LogFactory.getLog(WeakReferenceMonitor.class); // Queue receiving reachability events - private static final ReferenceQueue handleQueue = new ReferenceQueue(); + private static final ReferenceQueue handleQueue = new ReferenceQueue(); // All tracked entries (WeakReference => ReleaseListener) - private static final Map trackedEntries = Collections.synchronizedMap(new HashMap()); + private static final Map trackedEntries = + Collections.synchronizedMap(new HashMap()); // Thread polling handleQueue, lazy initialized private static Thread monitoringThread = null; @@ -73,7 +74,7 @@ public class WeakReferenceMonitor { // Make weak reference to this handle, so we can say when // handle is not used any more by polling on handleQueue. - WeakReference weakRef = new WeakReference(handle, handleQueue); + WeakReference weakRef = new WeakReference(handle, handleQueue); // Add monitored entry to internal map of all monitored entries. addEntry(weakRef, listener); @@ -105,7 +106,7 @@ public class WeakReferenceMonitor { * @return entry object associated with given reference */ private static ReleaseListener removeEntry(Reference reference) { - return (ReleaseListener) trackedEntries.remove(reference); + return trackedEntries.remove(reference); } /** diff --git a/org.springframework.core/src/main/java/org/springframework/util/comparator/BooleanComparator.java b/org.springframework.core/src/main/java/org/springframework/util/comparator/BooleanComparator.java index 26dd4aaf3f4..3dafae0ec8f 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/comparator/BooleanComparator.java +++ b/org.springframework.core/src/main/java/org/springframework/util/comparator/BooleanComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import java.util.Comparator; * @author Keith Donald * @since 1.2.2 */ -public final class BooleanComparator implements Comparator, Serializable { +public final class BooleanComparator implements Comparator, Serializable { /** * A shared default instance of this comparator, treating true lower @@ -58,9 +58,7 @@ public final class BooleanComparator implements Comparator, Serializable { } - public int compare(Object o1, Object o2) { - boolean v1 = ((Boolean) o1).booleanValue(); - boolean v2 = ((Boolean) o2).booleanValue(); + public int compare(Boolean v1, Boolean v2) { return (v1 ^ v2) ? ((v1 ^ this.trueLow) ? 1 : -1) : 0; } diff --git a/org.springframework.core/src/main/java/org/springframework/util/comparator/ComparableComparator.java b/org.springframework.core/src/main/java/org/springframework/util/comparator/ComparableComparator.java index 221139f02f0..03d21e7d3ca 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/comparator/ComparableComparator.java +++ b/org.springframework.core/src/main/java/org/springframework/util/comparator/ComparableComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,12 +29,10 @@ import org.springframework.util.Assert; * @since 1.2.2 * @see Comparable */ -public class ComparableComparator implements Comparator { +public class ComparableComparator> implements Comparator { - public int compare(Object o1, Object o2) { - Assert.isTrue(o1 instanceof Comparable, "The first object provided is not Comparable"); - Assert.isTrue(o2 instanceof Comparable, "The second object provided is not Comparable"); - return ((Comparable) o1).compareTo(o2); + public int compare(T o1, T o2) { + return o1.compareTo(o2); } } diff --git a/org.springframework.core/src/main/java/org/springframework/util/comparator/CompoundComparator.java b/org.springframework.core/src/main/java/org/springframework/util/comparator/CompoundComparator.java index 95635349549..8faf091ce8e 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/comparator/CompoundComparator.java +++ b/org.springframework.core/src/main/java/org/springframework/util/comparator/CompoundComparator.java @@ -37,9 +37,9 @@ import org.springframework.util.Assert; * @author Juergen Hoeller * @since 1.2.2 */ -public class CompoundComparator implements Comparator, Serializable { +public class CompoundComparator implements Comparator, Serializable { - private final List comparators; + private final List> comparators; /** @@ -48,7 +48,7 @@ public class CompoundComparator implements Comparator, Serializable { * IllegalStateException is thrown. */ public CompoundComparator() { - this.comparators = new ArrayList(); + this.comparators = new ArrayList>(); } /** @@ -59,8 +59,8 @@ public class CompoundComparator implements Comparator, Serializable { * @see InvertibleComparator */ public CompoundComparator(Comparator[] comparators) { - this.comparators = new ArrayList(comparators.length); - for (Comparator comparator : comparators) { + this.comparators = new ArrayList>(comparators.length); + for (Comparator comparator : comparators) { addComparator(comparator); } } @@ -73,12 +73,12 @@ public class CompoundComparator implements Comparator, Serializable { * @param comparator the Comparator to add to the end of the chain * @see InvertibleComparator */ - public void addComparator(Comparator comparator) { + public void addComparator(Comparator comparator) { if (comparator instanceof InvertibleComparator) { - this.comparators.add((InvertibleComparator) comparator); + this.comparators.add((InvertibleComparator) comparator); } else { - this.comparators.add(new InvertibleComparator(comparator)); + this.comparators.add(new InvertibleComparator(comparator)); } } @@ -87,8 +87,8 @@ public class CompoundComparator implements Comparator, Serializable { * @param comparator the Comparator to add to the end of the chain * @param ascending the sort order: ascending (true) or descending (false) */ - public void addComparator(Comparator comparator, boolean ascending) { - this.comparators.add(new InvertibleComparator(comparator, ascending)); + public void addComparator(Comparator comparator, boolean ascending) { + this.comparators.add(new InvertibleComparator(comparator, ascending)); } /** @@ -99,13 +99,12 @@ public class CompoundComparator implements Comparator, Serializable { * @param comparator the Comparator to place at the given index * @see InvertibleComparator */ - public void setComparator(int index, Comparator comparator) { + public void setComparator(int index, Comparator comparator) { if (comparator instanceof InvertibleComparator) { - this.comparators.set(index, (InvertibleComparator) comparator); + this.comparators.set(index, (InvertibleComparator) comparator); } else { - InvertibleComparator invComp = new InvertibleComparator(comparator); - this.comparators.set(index, invComp); + this.comparators.set(index, new InvertibleComparator(comparator)); } } @@ -115,8 +114,8 @@ public class CompoundComparator implements Comparator, Serializable { * @param comparator the Comparator to place at the given index * @param ascending the sort order: ascending (true) or descending (false) */ - public void setComparator(int index, Comparator comparator, boolean ascending) { - this.comparators.set(index, new InvertibleComparator(comparator, ascending)); + public void setComparator(int index, Comparator comparator, boolean ascending) { + this.comparators.set(index, new InvertibleComparator(comparator, ascending)); } /** @@ -161,10 +160,10 @@ public class CompoundComparator implements Comparator, Serializable { } - public int compare(Object o1, Object o2) { + public int compare(T o1, T o2) { Assert.state(this.comparators.size() > 0, "No sort definitions have been added to this CompoundComparator to compare"); - for (InvertibleComparator comparator : this.comparators) { + for (InvertibleComparator comparator : this.comparators) { int result = comparator.compare(o1, o2); if (result != 0) { return result; diff --git a/org.springframework.core/src/main/java/org/springframework/util/comparator/InvertibleComparator.java b/org.springframework.core/src/main/java/org/springframework/util/comparator/InvertibleComparator.java index 1af7fb45160..6fd14f453f4 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/comparator/InvertibleComparator.java +++ b/org.springframework.core/src/main/java/org/springframework/util/comparator/InvertibleComparator.java @@ -28,9 +28,9 @@ import java.util.Comparator; * @author Juergen Hoeller * @since 1.2.2 */ -public class InvertibleComparator implements Comparator, Serializable { +public class InvertibleComparator implements Comparator, Serializable { - private final Comparator comparator; + private final Comparator comparator; private boolean ascending = true; @@ -40,7 +40,7 @@ public class InvertibleComparator implements Comparator, Serializable { * For the actual comparison, the specified Comparator will be used. * @param comparator the comparator to decorate */ - public InvertibleComparator(Comparator comparator) { + public InvertibleComparator(Comparator comparator) { this.comparator = comparator; } @@ -50,7 +50,7 @@ public class InvertibleComparator implements Comparator, Serializable { * @param comparator the comparator to decorate * @param ascending the sort order: ascending (true) or descending (false) */ - public InvertibleComparator(Comparator comparator, boolean ascending) { + public InvertibleComparator(Comparator comparator, boolean ascending) { this.comparator = comparator; setAscending(ascending); } @@ -67,7 +67,7 @@ public class InvertibleComparator implements Comparator, Serializable { * Return the sort order: ascending (true) or descending (false). */ public boolean isAscending() { - return ascending; + return this.ascending; } /** @@ -79,7 +79,7 @@ public class InvertibleComparator implements Comparator, Serializable { } - public int compare(Object o1, Object o2) { + public int compare(T o1, T o2) { int result = this.comparator.compare(o1, o2); if (result != 0) { // Invert the order if it is a reverse sort. diff --git a/org.springframework.core/src/main/java/org/springframework/util/comparator/NullSafeComparator.java b/org.springframework.core/src/main/java/org/springframework/util/comparator/NullSafeComparator.java index 915553ea241..b2e761ebb68 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/comparator/NullSafeComparator.java +++ b/org.springframework.core/src/main/java/org/springframework/util/comparator/NullSafeComparator.java @@ -29,7 +29,7 @@ import org.springframework.util.Assert; * @since 1.2.2 * @see Comparable */ -public class NullSafeComparator implements Comparator { +public class NullSafeComparator implements Comparator { /** * A shared default instance of this comparator, treating nulls lower @@ -44,7 +44,7 @@ public class NullSafeComparator implements Comparator { public static final NullSafeComparator NULLS_HIGH = new NullSafeComparator(false); - private final Comparator nonNullComparator; + private final Comparator nonNullComparator; private final boolean nullsLow; @@ -63,8 +63,10 @@ public class NullSafeComparator implements Comparator { * @see #NULLS_LOW * @see #NULLS_HIGH */ + @SuppressWarnings("unchecked") private NullSafeComparator(boolean nullsLow) { - this(new ComparableComparator(), nullsLow); + this.nonNullComparator = new ComparableComparator(); + this.nullsLow = nullsLow; } /** @@ -76,14 +78,14 @@ public class NullSafeComparator implements Comparator { * @param comparator the comparator to use when comparing two non-null objects * @param nullsLow whether to treat nulls lower or higher than non-null objects */ - public NullSafeComparator(Comparator comparator, boolean nullsLow) { + public NullSafeComparator(Comparator comparator, boolean nullsLow) { Assert.notNull(comparator, "The non-null comparator is required"); this.nonNullComparator = comparator; this.nullsLow = nullsLow; } - public int compare(Object o1, Object o2) { + public int compare(T o1, T o2) { if (o1 == o2) { return 0; } diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/SpelUtilities.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/SpelUtilities.java index 38fe3a25517..6e8ad8b48f7 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/SpelUtilities.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/SpelUtilities.java @@ -44,7 +44,7 @@ public class SpelUtilities { */ private static void printAST(PrintStream out, SpelNode t, String indent) { if (t != null) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); String s = (t.getType() == -1 ? "EOF" : t.getClass().getSimpleName()); sb.append(indent).append(s); sb.append(" value=").append(t.getText()); diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java index e3a29b5bc7d..eb95853c541 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java @@ -110,7 +110,7 @@ public class CompoundExpression extends SpelNode { @Override public String toStringAST() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < getChildCount(); i++) { sb.append(getChild(i).toStringAST()); } diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Operator.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Operator.java index df254fbe286..10819c419fd 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Operator.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Operator.java @@ -54,16 +54,18 @@ public abstract class Operator extends SpelNode { */ @Override public String toStringAST() { - StringBuffer sb = new StringBuffer(); - if (getChildCount() > 0) + StringBuilder sb = new StringBuilder(); + if (getChildCount() > 0) { sb.append("("); + } sb.append(getChild(0).toStringAST()); for (int i = 1; i < getChildCount(); i++) { sb.append(" ").append(getOperatorName()).append(" "); sb.append(getChild(i).toStringAST()); } - if (getChildCount() > 0) + if (getChildCount() > 0) { sb.append(")"); + } return sb.toString(); } diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java index f2c054c72a2..83a0c906176 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Projection.java @@ -86,7 +86,7 @@ public class Projection extends SpelNode { @Override public String toStringAST() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); return sb.append("!{").append(getChild(0).toStringAST()).append("}").toString(); } diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Selection.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Selection.java index 1fc580ea840..e9ac8cabe2e 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Selection.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/ast/Selection.java @@ -123,7 +123,7 @@ public class Selection extends SpelNode { @Override public String toStringAST() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); switch (variant) { case ALL: sb.append("?{"); diff --git a/org.springframework.expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java b/org.springframework.expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java index e4c5a7e3c27..a9888990f3c 100644 --- a/org.springframework.expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java +++ b/org.springframework.expression/src/test/java/org/springframework/expression/spel/TestScenarioCreator.java @@ -198,7 +198,7 @@ public class TestScenarioCreator { } public static String reverseString(String input) { - StringBuffer backwards = new StringBuffer(); + StringBuilder backwards = new StringBuilder(); for (int i = 0; i < input.length(); i++) { backwards.append(input.charAt(input.length() - 1 - i)); } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java index 88b17e7a3ee..33dae94f109 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java @@ -61,22 +61,22 @@ import org.springframework.util.Assert; * @author Juergen Hoeller * @since 2.5 */ -public class BeanPropertyRowMapper implements RowMapper { +public class BeanPropertyRowMapper implements RowMapper { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); /** The class we are mapping to */ - private Class mappedClass; + private Class mappedClass; /** Whether we're strictly validating */ private boolean checkFullyPopulated = false; /** Map of the fields we provide mapping for */ - private Map mappedFields; + private Map mappedFields; /** Set of bean properties we provide mapping for */ - private Set mappedProperties; + private Set mappedProperties; /** @@ -92,7 +92,7 @@ public class BeanPropertyRowMapper implements RowMapper { * in the target bean. * @param mappedClass the class that each row should be mapped to */ - public BeanPropertyRowMapper(Class mappedClass) { + public BeanPropertyRowMapper(Class mappedClass) { initialize(mappedClass); } @@ -102,7 +102,7 @@ public class BeanPropertyRowMapper implements RowMapper { * @param checkFullyPopulated whether we're strictly validating that * all bean properties have been mapped from corresponding database fields */ - public BeanPropertyRowMapper(Class mappedClass, boolean checkFullyPopulated) { + public BeanPropertyRowMapper(Class mappedClass, boolean checkFullyPopulated) { initialize(mappedClass); this.checkFullyPopulated = checkFullyPopulated; } @@ -111,7 +111,7 @@ public class BeanPropertyRowMapper implements RowMapper { /** * Set the class that each row should be mapped to. */ - public void setMappedClass(Class mappedClass) { + public void setMappedClass(Class mappedClass) { if (this.mappedClass == null) { initialize(mappedClass); } @@ -127,13 +127,12 @@ public class BeanPropertyRowMapper implements RowMapper { * Initialize the mapping metadata for the given class. * @param mappedClass the mapped class. */ - protected void initialize(Class mappedClass) { + protected void initialize(Class mappedClass) { this.mappedClass = mappedClass; - this.mappedFields = new HashMap(); - this.mappedProperties = new HashSet(); + this.mappedFields = new HashMap(); + this.mappedProperties = new HashSet(); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass); - for (int i = 0; i < pds.length; i++) { - PropertyDescriptor pd = pds[i]; + for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null) { this.mappedFields.put(pd.getName().toLowerCase(), pd); String underscoredName = underscoreName(pd.getName()); @@ -152,7 +151,7 @@ public class BeanPropertyRowMapper implements RowMapper { * @return the converted name */ private String underscoreName(String name) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); if (name != null && name.length() > 0) { result.append(name.substring(0, 1).toLowerCase()); for (int i = 1; i < name.length(); i++) { @@ -172,7 +171,7 @@ public class BeanPropertyRowMapper implements RowMapper { /** * Get the class that we are mapping to. */ - public final Class getMappedClass() { + public final Class getMappedClass() { return this.mappedClass; } @@ -200,19 +199,19 @@ public class BeanPropertyRowMapper implements RowMapper { *

Utilizes public setters and result set metadata. * @see java.sql.ResultSetMetaData */ - public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { + public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); - Object mappedObject = BeanUtils.instantiateClass(this.mappedClass); + T mappedObject = BeanUtils.instantiate(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); - Set populatedProperties = (isCheckFullyPopulated() ? new HashSet() : null); + Set populatedProperties = (isCheckFullyPopulated() ? new HashSet() : null); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase(); - PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column); + PropertyDescriptor pd = this.mappedFields.get(column); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCallback.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCallback.java index 13dedcf35f9..071f2efccd6 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCallback.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -40,7 +40,7 @@ import org.springframework.dao.DataAccessException; * @see JdbcTemplate#execute(String, CallableStatementCallback) * @see JdbcTemplate#execute(CallableStatementCreator, CallableStatementCallback) */ -public interface CallableStatementCallback { +public interface CallableStatementCallback { /** * Gets called by JdbcTemplate.execute with an active JDBC @@ -72,6 +72,6 @@ public interface CallableStatementCallback { * into a DataAccessException by a SQLExceptionTranslator * @throws DataAccessException in case of custom exceptions */ - Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException; + T doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreatorFactory.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreatorFactory.java index 6892802a887..93f68dd099f 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreatorFactory.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreatorFactory.java @@ -43,7 +43,7 @@ public class CallableStatementCreatorFactory { private final String callString; /** List of SqlParameter objects. May not be null. */ - private final List declaredParameters; + private final List declaredParameters; private int resultSetType = ResultSet.TYPE_FORWARD_ONLY; @@ -58,7 +58,7 @@ public class CallableStatementCreatorFactory { */ public CallableStatementCreatorFactory(String callString) { this.callString = callString; - this.declaredParameters = new LinkedList(); + this.declaredParameters = new LinkedList(); } /** @@ -66,7 +66,7 @@ public class CallableStatementCreatorFactory { * @param callString the SQL call string * @param declaredParameters list of {@link SqlParameter} objects */ - public CallableStatementCreatorFactory(String callString, List declaredParameters) { + public CallableStatementCreatorFactory(String callString, List declaredParameters) { this.callString = callString; this.declaredParameters = declaredParameters; } @@ -112,8 +112,8 @@ public class CallableStatementCreatorFactory { * Return a new CallableStatementCreator instance given this parameters. * @param params list of parameters (may be null) */ - public CallableStatementCreator newCallableStatementCreator(Map params) { - return new CallableStatementCreatorImpl(params != null ? params : new HashMap()); + public CallableStatementCreator newCallableStatementCreator(Map params) { + return new CallableStatementCreatorImpl(params != null ? params : new HashMap()); } /** @@ -132,7 +132,7 @@ public class CallableStatementCreatorFactory { private ParameterMapper inParameterMapper; - private Map inParameters; + private Map inParameters; /** * Create a new CallableStatementCreatorImpl. @@ -146,7 +146,7 @@ public class CallableStatementCreatorFactory { * Create a new CallableStatementCreatorImpl. * @param inParams list of SqlParameter objects */ - public CallableStatementCreatorImpl(Map inParams) { + public CallableStatementCreatorImpl(Map inParams) { this.inParameters = inParams; } @@ -178,8 +178,7 @@ public class CallableStatementCreatorFactory { } int sqlColIndx = 1; - for (int i = 0; i < declaredParameters.size(); i++) { - SqlParameter declaredParam = (SqlParameter) declaredParameters.get(i); + for (SqlParameter declaredParam : declaredParameters) { if (!declaredParam.isResultsParameter()) { // So, it's a call parameter - part of the call string. // Get the value - it may still be null. @@ -193,7 +192,7 @@ public class CallableStatementCreatorFactory { } else { if (declaredParam.getScale() != null) { - cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getScale().intValue()); + cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getScale()); } else { cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType()); @@ -231,9 +230,10 @@ public class CallableStatementCreatorFactory { @Override public String toString() { - StringBuffer buf = new StringBuffer("CallableStatementCreatorFactory.CallableStatementCreatorImpl: sql=["); - buf.append(callString).append("]; parameters=").append(this.inParameters); - return buf.toString(); + StringBuilder sb = new StringBuilder(); + sb.append("CallableStatementCreatorFactory.CallableStatementCreatorImpl: sql=["); + sb.append(callString).append("]; parameters=").append(this.inParameters); + return sb.toString(); } } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ColumnMapRowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ColumnMapRowMapper.java index 7f4b7ff4ec6..6eca5e5be55 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ColumnMapRowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ColumnMapRowMapper.java @@ -45,12 +45,12 @@ import org.springframework.jdbc.support.JdbcUtils; * @see JdbcTemplate#queryForList(String) * @see JdbcTemplate#queryForMap(String) */ -public class ColumnMapRowMapper implements RowMapper { +public class ColumnMapRowMapper implements RowMapper> { - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + public Map mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); - Map mapOfColValues = createColumnMap(columnCount); + Map mapOfColValues = createColumnMap(columnCount); for (int i = 1; i <= columnCount; i++) { String key = getColumnKey(JdbcUtils.lookupColumnName(rsmd, i)); Object obj = getColumnValue(rs, i); @@ -68,8 +68,9 @@ public class ColumnMapRowMapper implements RowMapper { * @return the new Map instance * @see org.springframework.core.CollectionFactory#createLinkedCaseInsensitiveMapIfPossible */ - protected Map createColumnMap(int columnCount) { - return CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(columnCount); + @SuppressWarnings("unchecked") + protected Map createColumnMap(int columnCount) { + return (Map) CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(columnCount); } /** diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ConnectionCallback.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ConnectionCallback.java index 4986887b4ac..87f72002d5c 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ConnectionCallback.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ConnectionCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -37,7 +37,7 @@ import org.springframework.dao.DataAccessException; * @see JdbcTemplate#query * @see JdbcTemplate#update */ -public interface ConnectionCallback { +public interface ConnectionCallback { /** * Gets called by JdbcTemplate.execute with an active JDBC @@ -64,6 +64,6 @@ public interface ConnectionCallback { * @see JdbcTemplate#queryForObject(String, Class) * @see JdbcTemplate#queryForRowSet(String) */ - Object doInConnection(Connection con) throws SQLException, DataAccessException; + T doInConnection(Connection con) throws SQLException, DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java index 6e64330cddd..29a518657fe 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ public interface JdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(ConnectionCallback action) throws DataAccessException; + T execute(ConnectionCallback action) throws DataAccessException; //------------------------------------------------------------------------- @@ -77,7 +77,7 @@ public interface JdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(StatementCallback action) throws DataAccessException; + T execute(StatementCallback action) throws DataAccessException; /** * Issue a single SQL execute, typically a DDL statement. @@ -98,7 +98,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem executing the query * @see #query(String, Object[], ResultSetExtractor) */ - Object query(String sql, ResultSetExtractor rse) throws DataAccessException; + T query(String sql, ResultSetExtractor rse) throws DataAccessException; /** * Execute a query given static SQL, reading the ResultSet on a per-row @@ -125,7 +125,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem executing the query * @see #query(String, Object[], RowMapper) */ - List query(String sql, RowMapper rowMapper) throws DataAccessException; + List query(String sql, RowMapper rowMapper) throws DataAccessException; /** * Execute a query given static SQL, mapping a single result row to a Java @@ -141,7 +141,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem executing the query * @see #queryForObject(String, Object[], RowMapper) */ - Object queryForObject(String sql, RowMapper rowMapper) throws DataAccessException; + T queryForObject(String sql, RowMapper rowMapper) throws DataAccessException; /** * Execute a query for a result object, given static SQL. @@ -159,7 +159,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem executing the query * @see #queryForObject(String, Object[], Class) */ - Object queryForObject(String sql, Class requiredType) throws DataAccessException; + T queryForObject(String sql, Class requiredType) throws DataAccessException; /** * Execute a query for a result Map, given static SQL. @@ -177,7 +177,7 @@ public interface JdbcOperations { * @see #queryForMap(String, Object[]) * @see ColumnMapRowMapper */ - Map queryForMap(String sql) throws DataAccessException; + Map queryForMap(String sql) throws DataAccessException; /** * Execute a query that results in a long value, given static SQL. @@ -228,7 +228,7 @@ public interface JdbcOperations { * @see #queryForList(String, Object[], Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Class elementType) throws DataAccessException; + List queryForList(String sql, Class elementType) throws DataAccessException; /** * Execute a query for a result list, given static SQL. @@ -244,7 +244,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem executing the query * @see #queryForList(String, Object[]) */ - List queryForList(String sql) throws DataAccessException; + List> queryForList(String sql) throws DataAccessException; /** * Execute a query for a SqlRowSet, given static SQL. @@ -303,7 +303,7 @@ public interface JdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(PreparedStatementCreator psc, PreparedStatementCallback action) + T execute(PreparedStatementCreator psc, PreparedStatementCallback action) throws DataAccessException; /** @@ -319,7 +319,7 @@ public interface JdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(String sql, PreparedStatementCallback action) throws DataAccessException; + T execute(String sql, PreparedStatementCallback action) throws DataAccessException; /** * Query using a prepared statement, reading the ResultSet with a @@ -332,7 +332,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem * @see PreparedStatementCreatorFactory */ - Object query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException; + T query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException; /** * Query using a prepared statement, reading the ResultSet with a @@ -346,7 +346,7 @@ public interface JdbcOperations { * @return an arbitrary result object, as returned by the ResultSetExtractor * @throws DataAccessException if there is any problem */ - Object query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse) + T query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse) throws DataAccessException; /** @@ -362,7 +362,7 @@ public interface JdbcOperations { * @throws DataAccessException if the query fails * @see java.sql.Types */ - Object query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse) + T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse) throws DataAccessException; /** @@ -378,7 +378,7 @@ public interface JdbcOperations { * @return an arbitrary result object, as returned by the ResultSetExtractor * @throws DataAccessException if the query fails */ - Object query(String sql, Object[] args, ResultSetExtractor rse) throws DataAccessException; + T query(String sql, Object[] args, ResultSetExtractor rse) throws DataAccessException; /** * Query using a prepared statement, reading the ResultSet on a per-row @@ -448,7 +448,7 @@ public interface JdbcOperations { * @throws DataAccessException if there is any problem * @see PreparedStatementCreatorFactory */ - List query(PreparedStatementCreator psc, RowMapper rowMapper) throws DataAccessException; + List query(PreparedStatementCreator psc, RowMapper rowMapper) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -463,7 +463,7 @@ public interface JdbcOperations { * @return the result List, containing mapped objects * @throws DataAccessException if the query fails */ - List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper) + List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper) throws DataAccessException; /** @@ -479,7 +479,7 @@ public interface JdbcOperations { * @throws DataAccessException if the query fails * @see java.sql.Types */ - List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) + List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) throws DataAccessException; /** @@ -495,7 +495,7 @@ public interface JdbcOperations { * @return the result List, containing mapped objects * @throws DataAccessException if the query fails */ - List query(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException; + List query(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list @@ -512,7 +512,7 @@ public interface JdbcOperations { * return exactly one row * @throws DataAccessException if the query fails */ - Object queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) + T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) throws DataAccessException; /** @@ -530,7 +530,7 @@ public interface JdbcOperations { * return exactly one row * @throws DataAccessException if the query fails */ - Object queryForObject(String sql, Object[] args, RowMapper rowMapper) + T queryForObject(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException; /** @@ -550,7 +550,7 @@ public interface JdbcOperations { * @see #queryForObject(String, Class) * @see java.sql.Types */ - Object queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType) + T queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType) throws DataAccessException; /** @@ -570,7 +570,7 @@ public interface JdbcOperations { * @throws DataAccessException if the query fails * @see #queryForObject(String, Class) */ - Object queryForObject(String sql, Object[] args, Class requiredType) throws DataAccessException; + T queryForObject(String sql, Object[] args, Class requiredType) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -590,7 +590,7 @@ public interface JdbcOperations { * @see ColumnMapRowMapper * @see java.sql.Types */ - Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException; + Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -613,7 +613,7 @@ public interface JdbcOperations { * @see #queryForMap(String) * @see ColumnMapRowMapper */ - Map queryForMap(String sql, Object[] args) throws DataAccessException; + Map queryForMap(String sql, Object[] args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -703,7 +703,7 @@ public interface JdbcOperations { * @see #queryForList(String, Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Object[] args, int[] argTypes, Class elementType) + List queryForList(String sql, Object[] args, int[] argTypes, Class elementType) throws DataAccessException; /** @@ -723,7 +723,7 @@ public interface JdbcOperations { * @see #queryForList(String, Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Object[] args, Class elementType) throws DataAccessException; + List queryForList(String sql, Object[] args, Class elementType) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -741,7 +741,7 @@ public interface JdbcOperations { * @see #queryForList(String) * @see java.sql.Types */ - List queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException; + List> queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -759,7 +759,7 @@ public interface JdbcOperations { * @throws DataAccessException if the query fails * @see #queryForList(String) */ - List queryForList(String sql, Object[] args) throws DataAccessException; + List> queryForList(String sql, Object[] args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -905,7 +905,7 @@ public interface JdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(CallableStatementCreator csc, CallableStatementCallback action) + T execute(CallableStatementCreator csc, CallableStatementCallback action) throws DataAccessException; /** @@ -921,7 +921,7 @@ public interface JdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(String callString, CallableStatementCallback action) throws DataAccessException; + T execute(String callString, CallableStatementCallback action) throws DataAccessException; /** * Execute a SQL call using a CallableStatementCreator to provide SQL and any @@ -931,6 +931,7 @@ public interface JdbcOperations { * @return Map of extracted out parameters * @throws DataAccessException if there is any problem issuing the update */ - Map call(CallableStatementCreator csc, List declaredParameters) throws DataAccessException; + Map call(CallableStatementCreator csc, List declaredParameters) + throws DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java index 00f9324b6f9..fa3cb7caffc 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java @@ -33,7 +33,6 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import javax.sql.DataSource; import org.springframework.core.CollectionFactory; @@ -325,7 +324,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { // Methods dealing with a plain java.sql.Connection //------------------------------------------------------------------------- - public Object execute(ConnectionCallback action) throws DataAccessException { + public T execute(ConnectionCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(getDataSource()); @@ -376,7 +375,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { // Methods dealing with static SQL (java.sql.Statement) //------------------------------------------------------------------------- - public Object execute(StatementCallback action) throws DataAccessException { + public T execute(StatementCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(getDataSource()); @@ -393,7 +392,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (this.nativeJdbcExtractor != null) { stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt); } - Object result = action.doInStatement(stmtToUse); + T result = action.doInStatement(stmtToUse); handleWarnings(stmt); return result; } @@ -416,8 +415,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (logger.isDebugEnabled()) { logger.debug("Executing SQL statement [" + sql + "]"); } - - class ExecuteStatementCallback implements StatementCallback, SqlProvider { + class ExecuteStatementCallback implements StatementCallback, SqlProvider { public Object doInStatement(Statement stmt) throws SQLException { stmt.execute(sql); return null; @@ -429,15 +427,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { execute(new ExecuteStatementCallback()); } - public Object query(final String sql, final ResultSetExtractor rse) throws DataAccessException { + public T query(final String sql, final ResultSetExtractor rse) throws DataAccessException { Assert.notNull(sql, "SQL must not be null"); Assert.notNull(rse, "ResultSetExtractor must not be null"); if (logger.isDebugEnabled()) { logger.debug("Executing SQL query [" + sql + "]"); } - - class QueryStatementCallback implements StatementCallback, SqlProvider { - public Object doInStatement(Statement stmt) throws SQLException { + class QueryStatementCallback implements StatementCallback, SqlProvider { + public T doInStatement(Statement stmt) throws SQLException { ResultSet rs = null; try { rs = stmt.executeQuery(sql); @@ -462,43 +459,43 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { query(sql, new RowCallbackHandlerResultSetExtractor(rch)); } - public List query(String sql, RowMapper rowMapper) throws DataAccessException { - return (List) query(sql, new RowMapperResultSetExtractor(rowMapper)); + public List query(String sql, RowMapper rowMapper) throws DataAccessException { + return query(sql, new RowMapperResultSetExtractor(rowMapper)); } - public Map queryForMap(String sql) throws DataAccessException { - return (Map) queryForObject(sql, getColumnMapRowMapper()); + public Map queryForMap(String sql) throws DataAccessException { + return queryForObject(sql, getColumnMapRowMapper()); } - public Object queryForObject(String sql, RowMapper rowMapper) throws DataAccessException { - List results = query(sql, rowMapper); + public T queryForObject(String sql, RowMapper rowMapper) throws DataAccessException { + List results = query(sql, rowMapper); return DataAccessUtils.requiredSingleResult(results); } - public Object queryForObject(String sql, Class requiredType) throws DataAccessException { + public T queryForObject(String sql, Class requiredType) throws DataAccessException { return queryForObject(sql, getSingleColumnRowMapper(requiredType)); } public long queryForLong(String sql) throws DataAccessException { - Number number = (Number) queryForObject(sql, Long.class); + Number number = queryForObject(sql, Long.class); return (number != null ? number.longValue() : 0); } public int queryForInt(String sql) throws DataAccessException { - Number number = (Number) queryForObject(sql, Integer.class); + Number number = queryForObject(sql, Integer.class); return (number != null ? number.intValue() : 0); } - public List queryForList(String sql, Class elementType) throws DataAccessException { + public List queryForList(String sql, Class elementType) throws DataAccessException { return query(sql, getSingleColumnRowMapper(elementType)); } - public List queryForList(String sql) throws DataAccessException { + public List> queryForList(String sql) throws DataAccessException { return query(sql, getColumnMapRowMapper()); } public SqlRowSet queryForRowSet(String sql) throws DataAccessException { - return (SqlRowSet) query(sql, new SqlRowSetResultSetExtractor()); + return query(sql, new SqlRowSetResultSetExtractor()); } public int update(final String sql) throws DataAccessException { @@ -506,20 +503,19 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (logger.isDebugEnabled()) { logger.debug("Executing SQL update [" + sql + "]"); } - - class UpdateStatementCallback implements StatementCallback, SqlProvider { - public Object doInStatement(Statement stmt) throws SQLException { + class UpdateStatementCallback implements StatementCallback, SqlProvider { + public Integer doInStatement(Statement stmt) throws SQLException { int rows = stmt.executeUpdate(sql); if (logger.isDebugEnabled()) { logger.debug("SQL update affected " + rows + " rows"); } - return new Integer(rows); + return rows; } public String getSql() { return sql; } } - return ((Integer) execute(new UpdateStatementCallback())).intValue(); + return execute(new UpdateStatementCallback()); } public int[] batchUpdate(final String[] sql) throws DataAccessException { @@ -527,15 +523,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (logger.isDebugEnabled()) { logger.debug("Executing SQL batch update of " + sql.length + " statements"); } - - class BatchUpdateStatementCallback implements StatementCallback, SqlProvider { + class BatchUpdateStatementCallback implements StatementCallback, SqlProvider { private String currSql; - public Object doInStatement(Statement stmt) throws SQLException, DataAccessException { + public int[] doInStatement(Statement stmt) throws SQLException, DataAccessException { int[] rowsAffected = new int[sql.length]; if (JdbcUtils.supportsBatchUpdates(stmt.getConnection())) { - for (int i = 0; i < sql.length; i++) { - this.currSql = sql[i]; - stmt.addBatch(sql[i]); + for (String sqlStmt : sql) { + this.currSql = sqlStmt; + stmt.addBatch(sqlStmt); } rowsAffected = stmt.executeBatch(); } @@ -553,10 +548,10 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { return rowsAffected; } public String getSql() { - return currSql; + return this.currSql; } } - return (int[]) execute(new BatchUpdateStatementCallback()); + return execute(new BatchUpdateStatementCallback()); } @@ -564,7 +559,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { // Methods dealing with prepared statements //------------------------------------------------------------------------- - public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action) + public T execute(PreparedStatementCreator psc, PreparedStatementCallback action) throws DataAccessException { Assert.notNull(psc, "PreparedStatementCreator must not be null"); @@ -588,7 +583,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (this.nativeJdbcExtractor != null) { psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps); } - Object result = action.doInPreparedStatement(psToUse); + T result = action.doInPreparedStatement(psToUse); handleWarnings(ps); return result; } @@ -615,7 +610,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { } } - public Object execute(String sql, PreparedStatementCallback action) throws DataAccessException { + public T execute(String sql, PreparedStatementCallback action) throws DataAccessException { return execute(new SimplePreparedStatementCreator(sql), action); } @@ -631,15 +626,15 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @return an arbitrary result object, as returned by the ResultSetExtractor * @throws DataAccessException if there is any problem */ - public Object query( - PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor rse) + public T query( + PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor rse) throws DataAccessException { Assert.notNull(rse, "ResultSetExtractor must not be null"); logger.debug("Executing prepared SQL query"); - return execute(psc, new PreparedStatementCallback() { - public Object doInPreparedStatement(PreparedStatement ps) throws SQLException { + return execute(psc, new PreparedStatementCallback() { + public T doInPreparedStatement(PreparedStatement ps) throws SQLException { ResultSet rs = null; try { if (pss != null) { @@ -662,19 +657,19 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { }); } - public Object query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException { + public T query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException { return query(psc, null, rse); } - public Object query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse) throws DataAccessException { + public T query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse) throws DataAccessException { return query(new SimplePreparedStatementCreator(sql), pss, rse); } - public Object query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse) throws DataAccessException { + public T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse) throws DataAccessException { return query(sql, new ArgTypePreparedStatementSetter(args, argTypes), rse); } - public Object query(String sql, Object[] args, ResultSetExtractor rse) throws DataAccessException { + public T query(String sql, Object[] args, ResultSetExtractor rse) throws DataAccessException { return query(sql, new ArgPreparedStatementSetter(args), rse); } @@ -694,103 +689,102 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { query(sql, new ArgPreparedStatementSetter(args), rch); } - public List query(PreparedStatementCreator psc, RowMapper rowMapper) throws DataAccessException { - return (List) query(psc, new RowMapperResultSetExtractor(rowMapper)); + public List query(PreparedStatementCreator psc, RowMapper rowMapper) throws DataAccessException { + return query(psc, new RowMapperResultSetExtractor(rowMapper)); } - public List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper) throws DataAccessException { - return (List) query(sql, pss, new RowMapperResultSetExtractor(rowMapper)); + public List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper) throws DataAccessException { + return query(sql, pss, new RowMapperResultSetExtractor(rowMapper)); } - public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) throws DataAccessException { - return (List) query(sql, args, argTypes, new RowMapperResultSetExtractor(rowMapper)); + public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) throws DataAccessException { + return query(sql, args, argTypes, new RowMapperResultSetExtractor(rowMapper)); } - public List query(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException { - return (List) query(sql, args, new RowMapperResultSetExtractor(rowMapper)); + public List query(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException { + return query(sql, args, new RowMapperResultSetExtractor(rowMapper)); } - public Object queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) + public T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) throws DataAccessException { - List results = (List) query(sql, args, argTypes, new RowMapperResultSetExtractor(rowMapper, 1)); + List results = query(sql, args, argTypes, new RowMapperResultSetExtractor(rowMapper, 1)); return DataAccessUtils.requiredSingleResult(results); } - public Object queryForObject(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException { - List results = (List) query(sql, args, new RowMapperResultSetExtractor(rowMapper, 1)); + public T queryForObject(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException { + List results = query(sql, args, new RowMapperResultSetExtractor(rowMapper, 1)); return DataAccessUtils.requiredSingleResult(results); } - public Object queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType) + public T queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType) throws DataAccessException { return queryForObject(sql, args, argTypes, getSingleColumnRowMapper(requiredType)); } - public Object queryForObject(String sql, Object[] args, Class requiredType) throws DataAccessException { + public T queryForObject(String sql, Object[] args, Class requiredType) throws DataAccessException { return queryForObject(sql, args, getSingleColumnRowMapper(requiredType)); } - public Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException { - return (Map) queryForObject(sql, args, argTypes, getColumnMapRowMapper()); + public Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException { + return queryForObject(sql, args, argTypes, getColumnMapRowMapper()); } - public Map queryForMap(String sql, Object[] args) throws DataAccessException { - return (Map) queryForObject(sql, args, getColumnMapRowMapper()); + public Map queryForMap(String sql, Object[] args) throws DataAccessException { + return queryForObject(sql, args, getColumnMapRowMapper()); } public long queryForLong(String sql, Object[] args, int[] argTypes) throws DataAccessException { - Number number = (Number) queryForObject(sql, args, argTypes, Long.class); + Number number = queryForObject(sql, args, argTypes, Long.class); return (number != null ? number.longValue() : 0); } public long queryForLong(String sql, Object[] args) throws DataAccessException { - Number number = (Number) queryForObject(sql, args, Long.class); + Number number = queryForObject(sql, args, Long.class); return (number != null ? number.longValue() : 0); } public int queryForInt(String sql, Object[] args, int[] argTypes) throws DataAccessException { - Number number = (Number) queryForObject(sql, args, argTypes, Integer.class); + Number number = queryForObject(sql, args, argTypes, Integer.class); return (number != null ? number.intValue() : 0); } public int queryForInt(String sql, Object[] args) throws DataAccessException { - Number number = (Number) queryForObject(sql, args, Integer.class); + Number number = queryForObject(sql, args, Integer.class); return (number != null ? number.intValue() : 0); } - public List queryForList(String sql, Object[] args, int[] argTypes, Class elementType) throws DataAccessException { + public List queryForList(String sql, Object[] args, int[] argTypes, Class elementType) throws DataAccessException { return query(sql, args, argTypes, getSingleColumnRowMapper(elementType)); } - public List queryForList(String sql, Object[] args, Class elementType) throws DataAccessException { + public List queryForList(String sql, Object[] args, Class elementType) throws DataAccessException { return query(sql, args, getSingleColumnRowMapper(elementType)); } - public List queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException { + public List> queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException { return query(sql, args, argTypes, getColumnMapRowMapper()); } - public List queryForList(String sql, Object[] args) throws DataAccessException { + public List> queryForList(String sql, Object[] args) throws DataAccessException { return query(sql, args, getColumnMapRowMapper()); } public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes) throws DataAccessException { - return (SqlRowSet) query(sql, args, argTypes, new SqlRowSetResultSetExtractor()); + return query(sql, args, argTypes, new SqlRowSetResultSetExtractor()); } public SqlRowSet queryForRowSet(String sql, Object[] args) throws DataAccessException { - return (SqlRowSet) query(sql, args, new SqlRowSetResultSetExtractor()); + return query(sql, args, new SqlRowSetResultSetExtractor()); } protected int update(final PreparedStatementCreator psc, final PreparedStatementSetter pss) throws DataAccessException { logger.debug("Executing prepared SQL update"); - - Integer result = (Integer) execute(psc, new PreparedStatementCallback() { - public Object doInPreparedStatement(PreparedStatement ps) throws SQLException { + return execute(psc, new PreparedStatementCallback() { + public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException { try { if (pss != null) { pss.setValues(ps); @@ -799,7 +793,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (logger.isDebugEnabled()) { logger.debug("SQL update affected " + rows + " rows"); } - return new Integer(rows); + return rows; } finally { if (pss instanceof ParameterDisposer) { @@ -808,7 +802,6 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { } } }); - return result.intValue(); } public int update(PreparedStatementCreator psc) throws DataAccessException { @@ -821,17 +814,17 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { Assert.notNull(generatedKeyHolder, "KeyHolder must not be null"); logger.debug("Executing SQL update and returning generated keys"); - Integer result = (Integer) execute(psc, new PreparedStatementCallback() { - public Object doInPreparedStatement(PreparedStatement ps) throws SQLException { + return execute(psc, new PreparedStatementCallback() { + public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException { int rows = ps.executeUpdate(); - List generatedKeys = generatedKeyHolder.getKeyList(); + List> generatedKeys = generatedKeyHolder.getKeyList(); generatedKeys.clear(); ResultSet keys = ps.getGeneratedKeys(); if (keys != null) { try { - RowMapper rowMapper = getColumnMapRowMapper(); - RowMapperResultSetExtractor rse = new RowMapperResultSetExtractor(rowMapper, 1); - generatedKeys.addAll((List) rse.extractData(keys)); + RowMapperResultSetExtractor> rse = + new RowMapperResultSetExtractor>(getColumnMapRowMapper(), 1); + generatedKeys.addAll(rse.extractData(keys)); } finally { JdbcUtils.closeResultSet(keys); @@ -840,10 +833,9 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (logger.isDebugEnabled()) { logger.debug("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys"); } - return new Integer(rows); + return rows; } }); - return result.intValue(); } public int update(String sql, PreparedStatementSetter pss) throws DataAccessException { @@ -863,8 +855,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { logger.debug("Executing SQL batch update [" + sql + "]"); } - return (int[]) execute(sql, new PreparedStatementCallback() { - public Object doInPreparedStatement(PreparedStatement ps) throws SQLException { + return execute(sql, new PreparedStatementCallback() { + public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException { try { int batchSize = pss.getBatchSize(); InterruptibleBatchPreparedStatementSetter ipss = @@ -881,17 +873,17 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { return ps.executeBatch(); } else { - List rowsAffected = new ArrayList(); + List rowsAffected = new ArrayList(); for (int i = 0; i < batchSize; i++) { pss.setValues(ps, i); if (ipss != null && ipss.isBatchExhausted(i)) { break; } - rowsAffected.add(new Integer(ps.executeUpdate())); + rowsAffected.add(ps.executeUpdate()); } int[] rowsAffectedArray = new int[rowsAffected.size()]; for (int i = 0; i < rowsAffectedArray.length; i++) { - rowsAffectedArray[i] = ((Integer) rowsAffected.get(i)).intValue(); + rowsAffectedArray[i] = rowsAffected.get(i); } return rowsAffectedArray; } @@ -910,7 +902,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { // Methods dealing with callable statements //------------------------------------------------------------------------- - public Object execute(CallableStatementCreator csc, CallableStatementCallback action) + public T execute(CallableStatementCreator csc, CallableStatementCallback action) throws DataAccessException { Assert.notNull(csc, "CallableStatementCreator must not be null"); @@ -933,7 +925,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (this.nativeJdbcExtractor != null) { csToUse = this.nativeJdbcExtractor.getNativeCallableStatement(cs); } - Object result = action.doInCallableStatement(csToUse); + T result = action.doInCallableStatement(csToUse); handleWarnings(cs); return result; } @@ -960,16 +952,17 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { } } - public Object execute(String callString, CallableStatementCallback action) throws DataAccessException { + public T execute(String callString, CallableStatementCallback action) throws DataAccessException { return execute(new SimpleCallableStatementCreator(callString), action); } - public Map call(CallableStatementCreator csc, List declaredParameters) throws DataAccessException { - final List updateCountParameters = new ArrayList(); - final List resultSetParameters = new ArrayList(); - final List callParameters = new ArrayList(); - for (int i = 0; i < declaredParameters.size(); i++) { - SqlParameter parameter = (SqlParameter) declaredParameters.get(i); + public Map call(CallableStatementCreator csc, List declaredParameters) + throws DataAccessException { + + final List updateCountParameters = new ArrayList(); + final List resultSetParameters = new ArrayList(); + final List callParameters = new ArrayList(); + for (SqlParameter parameter : declaredParameters) { if (parameter.isResultsParameter()) { if (parameter instanceof SqlReturnResultSet) { resultSetParameters.add(parameter); @@ -982,15 +975,15 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { callParameters.add(parameter); } } - return (Map) execute(csc, new CallableStatementCallback() { - public Object doInCallableStatement(CallableStatement cs) throws SQLException { + return execute(csc, new CallableStatementCallback>() { + public Map doInCallableStatement(CallableStatement cs) throws SQLException { boolean retVal = cs.execute(); int updateCount = cs.getUpdateCount(); if (logger.isDebugEnabled()) { logger.debug("CallableStatement.execute() returned '" + retVal + "'"); logger.debug("CallableStatement.getUpdateCount() returned " + updateCount); } - Map returnedResults = createResultsMap(); + Map returnedResults = createResultsMap(); if (retVal || updateCount != -1) { returnedResults.putAll(extractReturnedResults(cs, updateCountParameters, resultSetParameters, updateCount)); } @@ -1007,11 +1000,11 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @param resultSetParameters Parameter list of declared resturn resultSet parameters for the stored procedure * @return Map that contains returned results */ - protected Map extractReturnedResults( + protected Map extractReturnedResults( CallableStatement cs, List updateCountParameters, List resultSetParameters, int updateCount) throws SQLException { - Map returnedResults = new HashMap(); + Map returnedResults = new HashMap(); int rsIndex = 0; int updateIndex = 0; boolean moreResults; @@ -1037,14 +1030,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { if (updateCountParameters != null && updateCountParameters.size() > updateIndex) { SqlReturnUpdateCount ucParam = (SqlReturnUpdateCount)updateCountParameters.get(updateIndex); String declaredUcName = ucParam.getName(); - returnedResults.put(declaredUcName, new Integer(updateCount)); + returnedResults.put(declaredUcName, updateCount); updateIndex++; } else { if (!skipUndeclaredResults) { String undeclaredUcName = RETURN_UPDATE_COUNT_PREFIX + (updateIndex + 1); logger.info("Added default SqlReturnUpdateCount parameter named " + undeclaredUcName); - returnedResults.put(undeclaredUcName, new Integer(updateCount)); + returnedResults.put(undeclaredUcName, updateCount); updateIndex++; } } @@ -1066,11 +1059,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @param parameters parameter list for the stored procedure * @return Map that contains returned results */ - protected Map extractOutputParameters(CallableStatement cs, List parameters) throws SQLException { - Map returnedResults = new HashMap(); + protected Map extractOutputParameters(CallableStatement cs, List parameters) + throws SQLException { + + Map returnedResults = new HashMap(); int sqlColIndex = 1; - for (int i = 0; i < parameters.size(); i++) { - SqlParameter param = (SqlParameter) parameters.get(i); + for (SqlParameter param : parameters) { if (param instanceof SqlOutParameter) { SqlOutParameter outParam = (SqlOutParameter) param; if (outParam.isReturnTypeSupported()) { @@ -1109,11 +1103,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @param param the corresponding stored procedure parameter * @return Map that contains returned results */ - protected Map processResultSet(ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException { + @SuppressWarnings("unchecked") + protected Map processResultSet(ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException { if (rs == null) { - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } - Map returnedResults = new HashMap(); + Map returnedResults = new HashMap(); try { ResultSet rsToUse = rs; if (this.nativeJdbcExtractor != null) { @@ -1150,7 +1145,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @return the RowMapper to use * @see ColumnMapRowMapper */ - protected RowMapper getColumnMapRowMapper() { + protected RowMapper> getColumnMapRowMapper() { return new ColumnMapRowMapper(); } @@ -1160,8 +1155,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @return the RowMapper to use * @see SingleColumnRowMapper */ - protected RowMapper getSingleColumnRowMapper(Class requiredType) { - return new SingleColumnRowMapper(requiredType); + protected RowMapper getSingleColumnRowMapper(Class requiredType) { + return new SingleColumnRowMapper(requiredType); } /** @@ -1172,12 +1167,13 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { * @see #setResultsMapCaseInsensitive * @see org.springframework.core.CollectionFactory#createLinkedCaseInsensitiveMapIfPossible */ - protected Map createResultsMap() { + @SuppressWarnings("unchecked") + protected Map createResultsMap() { if (isResultsMapCaseInsensitive()) { - return CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(10); + return (Map) CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(16); } else { - return new LinkedHashMap(); + return new LinkedHashMap(); } } @@ -1280,7 +1276,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { } else if (method.getName().equals("hashCode")) { // Use hashCode of PersistenceManager proxy. - return new Integer(System.identityHashCode(proxy)); + return System.identityHashCode(proxy); } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. @@ -1355,7 +1351,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { *

Uses a regular ResultSet, so we have to be careful when using it: * We don't use it for navigating since this could lead to unpredictable consequences. */ - private static class RowCallbackHandlerResultSetExtractor implements ResultSetExtractor { + private static class RowCallbackHandlerResultSetExtractor implements ResultSetExtractor { private final RowCallbackHandler rch; diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ParameterMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ParameterMapper.java index a7a9928dea1..46a78377c06 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ParameterMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ParameterMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,6 +42,6 @@ public interface ParameterMapper { * parameter values (that is, there's no need to catch SQLException) * @return Map of input parameters, keyed by name (never null) */ - Map createMap(Connection con) throws SQLException; + Map createMap(Connection con) throws SQLException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCallback.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCallback.java index 0e528d85ce3..5ef02826b43 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCallback.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -40,7 +40,7 @@ import org.springframework.dao.DataAccessException; * @see JdbcTemplate#execute(String, PreparedStatementCallback) * @see JdbcTemplate#execute(PreparedStatementCreator, PreparedStatementCallback) */ -public interface PreparedStatementCallback { +public interface PreparedStatementCallback { /** * Gets called by JdbcTemplate.execute with an active JDBC @@ -75,6 +75,6 @@ public interface PreparedStatementCallback { * @see JdbcTemplate#queryForObject(String, Object[], Class) * @see JdbcTemplate#queryForList(String, Object[]) */ - Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException; + T doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java index e0daa5f044e..192a9a267bd 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java @@ -25,7 +25,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -50,7 +49,7 @@ public class PreparedStatementCreatorFactory { private final String sql; /** List of SqlParameter objects. May not be null. */ - private final List declaredParameters; + private final List declaredParameters; private int resultSetType = ResultSet.TYPE_FORWARD_ONLY; @@ -69,7 +68,7 @@ public class PreparedStatementCreatorFactory { */ public PreparedStatementCreatorFactory(String sql) { this.sql = sql; - this.declaredParameters = new LinkedList(); + this.declaredParameters = new LinkedList(); } /** @@ -88,7 +87,7 @@ public class PreparedStatementCreatorFactory { * @param declaredParameters list of {@link SqlParameter} objects * @see SqlParameter */ - public PreparedStatementCreatorFactory(String sql, List declaredParameters) { + public PreparedStatementCreatorFactory(String sql, List declaredParameters) { this.sql = sql; this.declaredParameters = declaredParameters; } @@ -148,7 +147,7 @@ public class PreparedStatementCreatorFactory { * @param params list of parameters (may be null) */ public PreparedStatementSetter newPreparedStatementSetter(List params) { - return new PreparedStatementCreatorImpl(params != null ? params : Collections.EMPTY_LIST); + return new PreparedStatementCreatorImpl(params != null ? params : Collections.emptyList()); } /** @@ -156,15 +155,15 @@ public class PreparedStatementCreatorFactory { * @param params the parameter array (may be null) */ public PreparedStatementSetter newPreparedStatementSetter(Object[] params) { - return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.EMPTY_LIST); + return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.emptyList()); } /** * Return a new PreparedStatementCreator for the given parameters. * @param params list of parameters (may be null) */ - public PreparedStatementCreator newPreparedStatementCreator(List params) { - return new PreparedStatementCreatorImpl(params != null ? params : Collections.EMPTY_LIST); + public PreparedStatementCreator newPreparedStatementCreator(List params) { + return new PreparedStatementCreatorImpl(params != null ? params : Collections.emptyList()); } /** @@ -172,7 +171,7 @@ public class PreparedStatementCreatorFactory { * @param params the parameter array (may be null) */ public PreparedStatementCreator newPreparedStatementCreator(Object[] params) { - return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.EMPTY_LIST); + return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.emptyList()); } /** @@ -183,7 +182,7 @@ public class PreparedStatementCreatorFactory { */ public PreparedStatementCreator newPreparedStatementCreator(String sqlToUse, Object[] params) { return new PreparedStatementCreatorImpl( - sqlToUse, params != null ? Arrays.asList(params) : Collections.EMPTY_LIST); + sqlToUse, params != null ? Arrays.asList(params) : Collections.emptyList()); } @@ -197,7 +196,7 @@ public class PreparedStatementCreatorFactory { private final List parameters; - public PreparedStatementCreatorImpl(List parameters) { + public PreparedStatementCreatorImpl(List parameters) { this(sql, parameters); } @@ -207,11 +206,11 @@ public class PreparedStatementCreatorFactory { this.parameters = parameters; if (this.parameters.size() != declaredParameters.size()) { // account for named parameters being used multiple times - Set names = new HashSet(); + Set names = new HashSet(); for (int i = 0; i < parameters.size(); i++) { - Object o = parameters.get(i); - if (o instanceof SqlParameterValue) { - names.add(((SqlParameterValue)o).getName()); + Object param = parameters.get(i); + if (param instanceof SqlParameterValue) { + names.add(((SqlParameterValue) param).getName()); } else { names.add("Parameter #" + i); @@ -279,16 +278,14 @@ public class PreparedStatementCreatorFactory { " given only " + declaredParameters.size() + " parameters"); } - declaredParameter = (SqlParameter) declaredParameters.get(i); + declaredParameter = declaredParameters.get(i); } if (in instanceof Collection && declaredParameter.getSqlType() != Types.ARRAY) { Collection entries = (Collection) in; - for (Iterator it = entries.iterator(); it.hasNext();) { - Object entry = it.next(); + for (Object entry : entries) { if (entry instanceof Object[]) { Object[] valueArray = ((Object[])entry); - for (int k = 0; k < valueArray.length; k++) { - Object argValue = valueArray[k]; + for (Object argValue : valueArray) { StatementCreatorUtils.setParameterValue(psToUse, sqlColIndx++, declaredParameter, argValue); } } @@ -313,9 +310,10 @@ public class PreparedStatementCreatorFactory { @Override public String toString() { - StringBuffer buf = new StringBuffer("PreparedStatementCreatorFactory.PreparedStatementCreatorImpl: sql=["); - buf.append(sql).append("]; parameters=").append(this.parameters); - return buf.toString(); + StringBuilder sb = new StringBuilder(); + sb.append("PreparedStatementCreatorFactory.PreparedStatementCreatorImpl: sql=["); + sb.append(sql).append("]; parameters=").append(this.parameters); + return sb.toString(); } } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetExtractor.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetExtractor.java index 118bc9d0b24..76ddcd1b233 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetExtractor.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ import org.springframework.dao.DataAccessException; * @see RowMapper * @see org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor */ -public interface ResultSetExtractor { +public interface ResultSetExtractor { /** * Implementations must implement this method to process the entire ResultSet. @@ -58,6 +58,6 @@ public interface ResultSetExtractor { * values or navigating (that is, there's no need to catch SQLException) * @throws DataAccessException in case of custom exceptions */ - Object extractData(ResultSet rs) throws SQLException, DataAccessException; + T extractData(ResultSet rs) throws SQLException, DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetSupportingSqlParameter.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetSupportingSqlParameter.java index 9cb2cd0c7de..5dc54b2dc1e 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetSupportingSqlParameter.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/ResultSetSupportingSqlParameter.java @@ -108,7 +108,7 @@ public class ResultSetSupportingSqlParameter extends SqlParameter { * Return the ResultSetExtractor held by this parameter, if any. */ public ResultSetExtractor getResultSetExtractor() { - return resultSetExtractor; + return this.resultSetExtractor; } /** diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java index 1b439c9048f..680e904ed29 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java @@ -45,7 +45,7 @@ import java.sql.SQLException; * @see ResultSetExtractor * @see org.springframework.jdbc.object.MappingSqlQuery */ -public interface RowMapper { +public interface RowMapper { /** * Implementations must implement this method to map each row of data @@ -57,7 +57,7 @@ public interface RowMapper { * @throws SQLException if a SQLException is encountered getting * column values (that is, there's no need to catch SQLException) */ - Object mapRow(ResultSet rs, int rowNum) throws SQLException; + T mapRow(ResultSet rs, int rowNum) throws SQLException; } \ No newline at end of file diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapperResultSetExtractor.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapperResultSetExtractor.java index 989fc5b57f9..8e8b7f7e08b 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapperResultSetExtractor.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/RowMapperResultSetExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,9 +57,9 @@ import org.springframework.util.Assert; * @see JdbcTemplate * @see org.springframework.jdbc.object.MappingSqlQuery */ -public class RowMapperResultSetExtractor implements ResultSetExtractor { +public class RowMapperResultSetExtractor implements ResultSetExtractor> { - private final RowMapper rowMapper; + private final RowMapper rowMapper; private final int rowsExpected; @@ -68,7 +68,7 @@ public class RowMapperResultSetExtractor implements ResultSetExtractor { * Create a new RowMapperResultSetExtractor. * @param rowMapper the RowMapper which creates an object for each row */ - public RowMapperResultSetExtractor(RowMapper rowMapper) { + public RowMapperResultSetExtractor(RowMapper rowMapper) { this(rowMapper, 0); } @@ -78,15 +78,15 @@ public class RowMapperResultSetExtractor implements ResultSetExtractor { * @param rowsExpected the number of expected rows * (just used for optimized collection handling) */ - public RowMapperResultSetExtractor(RowMapper rowMapper, int rowsExpected) { + public RowMapperResultSetExtractor(RowMapper rowMapper, int rowsExpected) { Assert.notNull(rowMapper, "RowMapper is required"); this.rowMapper = rowMapper; this.rowsExpected = rowsExpected; } - public Object extractData(ResultSet rs) throws SQLException { - List results = (this.rowsExpected > 0 ? new ArrayList(this.rowsExpected) : new ArrayList()); + public List extractData(ResultSet rs) throws SQLException { + List results = (this.rowsExpected > 0 ? new ArrayList(this.rowsExpected) : new ArrayList()); int rowNum = 0; while (rs.next()) { results.add(this.rowMapper.mapRow(rs, rowNum++)); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SingleColumnRowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SingleColumnRowMapper.java index 87eab93d2a3..a7b440fc48a 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SingleColumnRowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SingleColumnRowMapper.java @@ -39,9 +39,9 @@ import org.springframework.util.NumberUtils; * @see JdbcTemplate#queryForList(String, Class) * @see JdbcTemplate#queryForObject(String, Class) */ -public class SingleColumnRowMapper implements RowMapper { +public class SingleColumnRowMapper implements RowMapper { - private Class requiredType; + private Class requiredType; /** @@ -55,7 +55,7 @@ public class SingleColumnRowMapper implements RowMapper { * Create a new SingleColumnRowMapper. * @param requiredType the type that each result object is expected to match */ - public SingleColumnRowMapper(Class requiredType) { + public SingleColumnRowMapper(Class requiredType) { this.requiredType = requiredType; } @@ -64,7 +64,7 @@ public class SingleColumnRowMapper implements RowMapper { *

If not specified, the column value will be exposed as * returned by the JDBC driver. */ - public void setRequiredType(Class requiredType) { + public void setRequiredType(Class requiredType) { this.requiredType = requiredType; } @@ -78,7 +78,8 @@ public class SingleColumnRowMapper implements RowMapper { * @see #getColumnValue(java.sql.ResultSet, int, Class) * @see #convertValueToRequiredType(Object, Class) */ - public Object mapRow(ResultSet rs, int rowNum) throws SQLException { + @SuppressWarnings("unchecked") + public T mapRow(ResultSet rs, int rowNum) throws SQLException { // Validate column count. ResultSetMetaData rsmd = rs.getMetaData(); int nrOfColumns = rsmd.getColumnCount(); @@ -91,7 +92,7 @@ public class SingleColumnRowMapper implements RowMapper { if (result != null && this.requiredType != null && !this.requiredType.isInstance(result)) { // Extracted value does not match already: try to convert it. try { - return convertValueToRequiredType(result, this.requiredType); + return (T) convertValueToRequiredType(result, this.requiredType); } catch (IllegalArgumentException ex) { throw new TypeMismatchDataAccessException( @@ -99,7 +100,7 @@ public class SingleColumnRowMapper implements RowMapper { rsmd.getColumnTypeName(1) + "': " + ex.getMessage()); } } - return result; + return (T) result; } /** diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlParameter.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlParameter.java index b2f86e37bde..8b9485e658f 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlParameter.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlParameter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ public class SqlParameter { */ public SqlParameter(int sqlType, int scale) { this.sqlType = sqlType; - this.scale = new Integer(scale); + this.scale = scale; } /** @@ -109,7 +109,7 @@ public class SqlParameter { public SqlParameter(String name, int sqlType, int scale) { this.name = name; this.sqlType = sqlType; - this.scale = new Integer(scale); + this.scale = scale; } /** @@ -177,11 +177,11 @@ public class SqlParameter { * Convert a list of JDBC types, as defined in java.sql.Types, * to a List of SqlParameter objects as used in this package. */ - public static List sqlTypesToAnonymousParameterList(int[] types) { - List result = new LinkedList(); + public static List sqlTypesToAnonymousParameterList(int[] types) { + List result = new LinkedList(); if (types != null) { - for (int i = 0; i < types.length; i++) { - result.add(new SqlParameter(types[i])); + for (int type : types) { + result.add(new SqlParameter(type)); } } return result; diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlRowSetResultSetExtractor.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlRowSetResultSetExtractor.java index c17038027f1..6d94175b1ad 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlRowSetResultSetExtractor.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/SqlRowSetResultSetExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.jdbc.core; import java.sql.ResultSet; import java.sql.SQLException; - import javax.sql.rowset.CachedRowSet; import com.sun.rowset.CachedRowSetImpl; @@ -32,9 +31,7 @@ import org.springframework.jdbc.support.rowset.SqlRowSet; * *

The default implementation uses a standard JDBC CachedRowSet underneath. * This means that JDBC RowSet support needs to be available at runtime: - * by default, Sun's com.sun.rowset.CachedRowSetImpl class is - * used, which is part of JDK 1.5+ and also available separately as part of - * Sun's JDBC RowSet Implementations download (rowset.jar). + * by default, Sun's com.sun.rowset.CachedRowSetImpl class. * * @author Juergen Hoeller * @since 1.2 @@ -43,9 +40,9 @@ import org.springframework.jdbc.support.rowset.SqlRowSet; * @see JdbcTemplate#queryForRowSet(String) * @see javax.sql.rowset.CachedRowSet */ -public class SqlRowSetResultSetExtractor implements ResultSetExtractor { +public class SqlRowSetResultSetExtractor implements ResultSetExtractor { - public Object extractData(ResultSet rs) throws SQLException { + public SqlRowSet extractData(ResultSet rs) throws SQLException { return createSqlRowSet(rs); } @@ -71,9 +68,7 @@ public class SqlRowSetResultSetExtractor implements ResultSetExtractor { * Create a new CachedRowSet instance, to be populated by * the createSqlRowSet implementation. *

The default implementation creates a new instance of - * Sun's com.sun.rowset.CachedRowSetImpl class, - * which is part of JDK 1.5+ and also available separately - * as part of Sun's JDBC RowSet Implementations download. + * Sun's com.sun.rowset.CachedRowSetImpl class. * @return a new CachedRowSet instance * @throws SQLException if thrown by JDBC methods * @see #createSqlRowSet diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCallback.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCallback.java index bcda002ec23..b3837c2ddc4 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCallback.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,7 @@ import org.springframework.dao.DataAccessException; * @since 16.03.2004 * @see JdbcTemplate#execute(StatementCallback) */ -public interface StatementCallback { +public interface StatementCallback { /** * Gets called by JdbcTemplate.execute with an active JDBC @@ -68,6 +68,6 @@ public interface StatementCallback { * @see JdbcTemplate#queryForObject(String, Class) * @see JdbcTemplate#queryForRowSet(String) */ - Object doInStatement(Statement stmt) throws SQLException, DataAccessException; + T doInStatement(Statement stmt) throws SQLException, DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java index 8c2ee40322f..197e0da4d33 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java @@ -61,32 +61,32 @@ public abstract class StatementCreatorUtils { private static final Log logger = LogFactory.getLog(StatementCreatorUtils.class); - private static Map javaTypeToSqlTypeMap = new HashMap(32); + private static Map javaTypeToSqlTypeMap = new HashMap(32); static { /* JDBC 3.0 only - not compatible with e.g. MySQL at present javaTypeToSqlTypeMap.put(boolean.class, new Integer(Types.BOOLEAN)); javaTypeToSqlTypeMap.put(Boolean.class, new Integer(Types.BOOLEAN)); */ - javaTypeToSqlTypeMap.put(byte.class, new Integer(Types.TINYINT)); - javaTypeToSqlTypeMap.put(Byte.class, new Integer(Types.TINYINT)); - javaTypeToSqlTypeMap.put(short.class, new Integer(Types.SMALLINT)); - javaTypeToSqlTypeMap.put(Short.class, new Integer(Types.SMALLINT)); - javaTypeToSqlTypeMap.put(int.class, new Integer(Types.INTEGER)); - javaTypeToSqlTypeMap.put(Integer.class, new Integer(Types.INTEGER)); - javaTypeToSqlTypeMap.put(long.class, new Integer(Types.BIGINT)); - javaTypeToSqlTypeMap.put(Long.class, new Integer(Types.BIGINT)); - javaTypeToSqlTypeMap.put(BigInteger.class, new Integer(Types.BIGINT)); - javaTypeToSqlTypeMap.put(float.class, new Integer(Types.FLOAT)); - javaTypeToSqlTypeMap.put(Float.class, new Integer(Types.FLOAT)); - javaTypeToSqlTypeMap.put(double.class, new Integer(Types.DOUBLE)); - javaTypeToSqlTypeMap.put(Double.class, new Integer(Types.DOUBLE)); - javaTypeToSqlTypeMap.put(BigDecimal.class, new Integer(Types.DECIMAL)); - javaTypeToSqlTypeMap.put(java.sql.Date.class, new Integer(Types.DATE)); - javaTypeToSqlTypeMap.put(java.sql.Time.class, new Integer(Types.TIME)); - javaTypeToSqlTypeMap.put(java.sql.Timestamp.class, new Integer(Types.TIMESTAMP)); - javaTypeToSqlTypeMap.put(Blob.class, new Integer(Types.BLOB)); - javaTypeToSqlTypeMap.put(Clob.class, new Integer(Types.CLOB)); + javaTypeToSqlTypeMap.put(byte.class, Types.TINYINT); + javaTypeToSqlTypeMap.put(Byte.class, Types.TINYINT); + javaTypeToSqlTypeMap.put(short.class, Types.SMALLINT); + javaTypeToSqlTypeMap.put(Short.class, Types.SMALLINT); + javaTypeToSqlTypeMap.put(int.class, Types.INTEGER); + javaTypeToSqlTypeMap.put(Integer.class, Types.INTEGER); + javaTypeToSqlTypeMap.put(long.class, Types.BIGINT); + javaTypeToSqlTypeMap.put(Long.class, Types.BIGINT); + javaTypeToSqlTypeMap.put(BigInteger.class, Types.BIGINT); + javaTypeToSqlTypeMap.put(float.class, Types.FLOAT); + javaTypeToSqlTypeMap.put(Float.class, Types.FLOAT); + javaTypeToSqlTypeMap.put(double.class, Types.DOUBLE); + javaTypeToSqlTypeMap.put(Double.class, Types.DOUBLE); + javaTypeToSqlTypeMap.put(BigDecimal.class, Types.DECIMAL); + javaTypeToSqlTypeMap.put(java.sql.Date.class, Types.DATE); + javaTypeToSqlTypeMap.put(java.sql.Time.class, Types.TIME); + javaTypeToSqlTypeMap.put(java.sql.Timestamp.class, Types.TIMESTAMP); + javaTypeToSqlTypeMap.put(Blob.class, Types.BLOB); + javaTypeToSqlTypeMap.put(Clob.class, Types.CLOB); } @@ -96,9 +96,9 @@ public abstract class StatementCreatorUtils { * @return the corresponding SQL type, or null if none found */ public static int javaTypeToSqlParameterType(Class javaType) { - Integer sqlType = (Integer) javaTypeToSqlTypeMap.get(javaType); + Integer sqlType = javaTypeToSqlTypeMap.get(javaType); if (sqlType != null) { - return sqlType.intValue(); + return sqlType; } if (Number.class.isAssignableFrom(javaType)) { return Types.NUMERIC; @@ -273,7 +273,7 @@ public abstract class StatementCreatorUtils { ps.setBigDecimal(paramIndex, (BigDecimal) inValue); } else if (scale != null) { - ps.setObject(paramIndex, inValue, sqlType, scale.intValue()); + ps.setObject(paramIndex, inValue, sqlType, scale); } else { ps.setObject(paramIndex, inValue, sqlType); @@ -394,8 +394,7 @@ public abstract class StatementCreatorUtils { */ public static void cleanupParameters(Collection paramValues) { if (paramValues != null) { - for (Iterator it = paramValues.iterator(); it.hasNext();) { - Object inValue = it.next(); + for (Object inValue : paramValues) { if (inValue instanceof DisposableSqlTypeValue) { ((DisposableSqlTypeValue) inValue).cleanup(); } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSource.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSource.java index 492c036e346..cd048908b5a 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSource.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSource.java @@ -69,7 +69,7 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource { * Create a new MapSqlParameterSource based on a Map. * @param values a Map holding existing parameter values (can be null) */ - public MapSqlParameterSource(Map values) { + public MapSqlParameterSource(Map values) { addValues(values); } @@ -128,9 +128,9 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource { * @return a reference to this parameter source, * so it's possible to chain several calls together */ - public MapSqlParameterSource addValues(Map values) { + public MapSqlParameterSource addValues(Map values) { if (values != null) { - for (Map.Entry entry : values.entrySet()) { + for (Map.Entry entry : values.entrySet()) { this.values.put(entry.getKey(), entry.getValue()); if (entry.getValue() instanceof SqlParameterValue) { SqlParameterValue value = (SqlParameterValue) entry.getValue(); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java index 5d897a3e199..74bfb970b61 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,7 @@ public interface NamedParameterJdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback action) + T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback action) throws DataAccessException; /** @@ -85,7 +85,7 @@ public interface NamedParameterJdbcOperations { * @return a result object returned by the action, or null * @throws DataAccessException if there is any problem */ - Object execute(String sql, Map paramMap, PreparedStatementCallback action) + T execute(String sql, Map paramMap, PreparedStatementCallback action) throws DataAccessException; /** @@ -98,7 +98,7 @@ public interface NamedParameterJdbcOperations { * @return an arbitrary result object, as returned by the ResultSetExtractor * @throws DataAccessException if the query fails */ - Object query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse) + T query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse) throws DataAccessException; /** @@ -112,7 +112,8 @@ public interface NamedParameterJdbcOperations { * @return an arbitrary result object, as returned by the ResultSetExtractor * @throws org.springframework.dao.DataAccessException if the query fails */ - Object query(String sql, Map paramMap, ResultSetExtractor rse) throws DataAccessException; + T query(String sql, Map paramMap, ResultSetExtractor rse) + throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -136,7 +137,7 @@ public interface NamedParameterJdbcOperations { * @param rch object that will extract results, one row at a time * @throws org.springframework.dao.DataAccessException if the query fails */ - void query(String sql, Map paramMap, RowCallbackHandler rch) throws DataAccessException; + void query(String sql, Map paramMap, RowCallbackHandler rch) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list @@ -148,7 +149,7 @@ public interface NamedParameterJdbcOperations { * @return the result List, containing mapped objects * @throws org.springframework.dao.DataAccessException if the query fails */ - List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper) + List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper) throws DataAccessException; /** @@ -162,7 +163,8 @@ public interface NamedParameterJdbcOperations { * @return the result List, containing mapped objects * @throws org.springframework.dao.DataAccessException if the query fails */ - List query(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException; + List query(String sql, Map paramMap, RowMapper rowMapper) + throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list @@ -177,7 +179,7 @@ public interface NamedParameterJdbcOperations { * one column in that row * @throws org.springframework.dao.DataAccessException if the query fails */ - Object queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper) + T queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper) throws DataAccessException; /** @@ -194,7 +196,8 @@ public interface NamedParameterJdbcOperations { * one column in that row * @throws org.springframework.dao.DataAccessException if the query fails */ - Object queryForObject(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException; + T queryForObject(String sql, Map paramMap, RowMapper rowMapper) + throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -211,7 +214,7 @@ public interface NamedParameterJdbcOperations { * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForObject(String, Class) */ - Object queryForObject(String sql, SqlParameterSource paramSource, Class requiredType) + T queryForObject(String sql, SqlParameterSource paramSource, Class requiredType) throws DataAccessException; /** @@ -230,7 +233,8 @@ public interface NamedParameterJdbcOperations { * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForObject(String, Class) */ - Object queryForObject(String sql, Map paramMap, Class requiredType) throws DataAccessException; + T queryForObject(String sql, Map paramMap, Class requiredType) + throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -247,7 +251,7 @@ public interface NamedParameterJdbcOperations { * @see org.springframework.jdbc.core.JdbcTemplate#queryForMap(String) * @see org.springframework.jdbc.core.ColumnMapRowMapper */ - Map queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException; + Map queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -268,7 +272,7 @@ public interface NamedParameterJdbcOperations { * @see org.springframework.jdbc.core.JdbcTemplate#queryForMap(String) * @see org.springframework.jdbc.core.ColumnMapRowMapper */ - Map queryForMap(String sql, Map paramMap) throws DataAccessException; + Map queryForMap(String sql, Map paramMap) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -301,7 +305,7 @@ public interface NamedParameterJdbcOperations { * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForLong(String) */ - long queryForLong(String sql, Map paramMap) throws DataAccessException; + long queryForLong(String sql, Map paramMap) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -332,7 +336,7 @@ public interface NamedParameterJdbcOperations { * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForInt(String) */ - int queryForInt(String sql, Map paramMap) throws DataAccessException; + int queryForInt(String sql, Map paramMap) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -348,7 +352,7 @@ public interface NamedParameterJdbcOperations { * @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String, Class) * @see org.springframework.jdbc.core.SingleColumnRowMapper */ - List queryForList(String sql, SqlParameterSource paramSource, Class elementType) + List queryForList(String sql, SqlParameterSource paramSource, Class elementType) throws DataAccessException; /** @@ -366,7 +370,8 @@ public interface NamedParameterJdbcOperations { * @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String, Class) * @see org.springframework.jdbc.core.SingleColumnRowMapper */ - List queryForList(String sql, Map paramMap, Class elementType) throws DataAccessException; + List queryForList(String sql, Map paramMap, Class elementType) + throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -381,7 +386,7 @@ public interface NamedParameterJdbcOperations { * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String) */ - List queryForList(String sql, SqlParameterSource paramSource) throws DataAccessException; + List> queryForList(String sql, SqlParameterSource paramSource) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -397,7 +402,7 @@ public interface NamedParameterJdbcOperations { * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String) */ - List queryForList(String sql, Map paramMap) throws DataAccessException; + List> queryForList(String sql, Map paramMap) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -438,7 +443,7 @@ public interface NamedParameterJdbcOperations { * @see org.springframework.jdbc.core.SqlRowSetResultSetExtractor * @see javax.sql.rowset.CachedRowSet */ - SqlRowSet queryForRowSet(String sql, Map paramMap) throws DataAccessException; + SqlRowSet queryForRowSet(String sql, Map paramMap) throws DataAccessException; /** * Issue an update via a prepared statement, binding the given arguments. @@ -457,7 +462,7 @@ public interface NamedParameterJdbcOperations { * @return the number of rows affected * @throws org.springframework.dao.DataAccessException if there is any problem issuing the update */ - int update(String sql, Map paramMap) throws DataAccessException; + int update(String sql, Map paramMap) throws DataAccessException; /** * Issue an update via a prepared statement, binding the given arguments, @@ -485,8 +490,7 @@ public interface NamedParameterJdbcOperations { * @see MapSqlParameterSource * @see org.springframework.jdbc.support.GeneratedKeyHolder */ - int update( - String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames) + int update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames) throws DataAccessException; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java index bd93fce0d8e..f8b13d63de8 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations private final JdbcOperations classicJdbcTemplate; /** Map of original SQL String to ParsedSql representation */ - private final Map parsedSqlCache = new HashMap(); + private final Map parsedSqlCache = new HashMap(); /** @@ -97,23 +97,27 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations } - public Object execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback action) + public T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback action) throws DataAccessException { return getJdbcOperations().execute(getPreparedStatementCreator(sql, paramSource), action); } - public Object execute(String sql, Map paramMap, PreparedStatementCallback action) throws DataAccessException { + public T execute(String sql, Map paramMap, PreparedStatementCallback action) + throws DataAccessException { + return execute(sql, new MapSqlParameterSource(paramMap), action); } - public Object query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse) + public T query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse) throws DataAccessException { return getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rse); } - public Object query(String sql, Map paramMap, ResultSetExtractor rse) throws DataAccessException { + public T query(String sql, Map paramMap, ResultSetExtractor rse) + throws DataAccessException { + return query(sql, new MapSqlParameterSource(paramMap), rse); } @@ -123,90 +127,105 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rch); } - public void query(String sql, Map paramMap, RowCallbackHandler rch) throws DataAccessException { + public void query(String sql, Map paramMap, RowCallbackHandler rch) + throws DataAccessException { + query(sql, new MapSqlParameterSource(paramMap), rch); } - public List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper) + public List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper) throws DataAccessException { return getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper); } - public List query(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException { + public List query(String sql, Map paramMap, RowMapper rowMapper) + throws DataAccessException { + return query(sql, new MapSqlParameterSource(paramMap), rowMapper); } - public Object queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper) + public T queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper) throws DataAccessException { - List results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper); + List results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper); return DataAccessUtils.requiredSingleResult(results); } - public Object queryForObject(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException { + public T queryForObject(String sql, Map paramMap, RowMapperrowMapper) + throws DataAccessException { + return queryForObject(sql, new MapSqlParameterSource(paramMap), rowMapper); } - public Object queryForObject(String sql, SqlParameterSource paramSource, Class requiredType) + public T queryForObject(String sql, SqlParameterSource paramSource, Class requiredType) throws DataAccessException { - return queryForObject(sql, paramSource, new SingleColumnRowMapper(requiredType)); + return queryForObject(sql, paramSource, new SingleColumnRowMapper(requiredType)); } - public Object queryForObject(String sql, Map paramMap, Class requiredType) throws DataAccessException { - return queryForObject(sql, paramMap, new SingleColumnRowMapper(requiredType)); + public T queryForObject(String sql, Map paramMap, Class requiredType) + throws DataAccessException { + + return queryForObject(sql, paramMap, new SingleColumnRowMapper(requiredType)); } - public Map queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException { - return (Map) queryForObject(sql, paramSource, new ColumnMapRowMapper()); + public Map queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException { + return queryForObject(sql, paramSource, new ColumnMapRowMapper()); } - public Map queryForMap(String sql, Map paramMap) throws DataAccessException { - return (Map) queryForObject(sql, paramMap, new ColumnMapRowMapper()); + public Map queryForMap(String sql, Map paramMap) throws DataAccessException { + return queryForObject(sql, paramMap, new ColumnMapRowMapper()); } public long queryForLong(String sql, SqlParameterSource paramSource) throws DataAccessException { - Number number = (Number) queryForObject(sql, paramSource, Number.class); + Number number = queryForObject(sql, paramSource, Number.class); return (number != null ? number.longValue() : 0); } - public long queryForLong(String sql, Map paramMap) throws DataAccessException { + public long queryForLong(String sql, Map paramMap) throws DataAccessException { return queryForLong(sql, new MapSqlParameterSource(paramMap)); } public int queryForInt(String sql, SqlParameterSource paramSource) throws DataAccessException { - Number number = (Number) queryForObject(sql, paramSource, Number.class); + Number number = queryForObject(sql, paramSource, Number.class); return (number != null ? number.intValue() : 0); } - public int queryForInt(String sql, Map paramMap) throws DataAccessException { + public int queryForInt(String sql, Map paramMap) throws DataAccessException { return queryForInt(sql, new MapSqlParameterSource(paramMap)); } - public List queryForList(String sql, SqlParameterSource paramSource, Class elementType) + public List queryForList(String sql, SqlParameterSource paramSource, Class elementType) throws DataAccessException { - return query(sql, paramSource, new SingleColumnRowMapper(elementType)); + + return query(sql, paramSource, new SingleColumnRowMapper(elementType)); } - public List queryForList(String sql, Map paramMap, Class elementType) throws DataAccessException { + public List queryForList(String sql, Map paramMap, Class elementType) + throws DataAccessException { + return queryForList(sql, new MapSqlParameterSource(paramMap), elementType); } - public List queryForList(String sql, SqlParameterSource paramSource) throws DataAccessException { + public List> queryForList(String sql, SqlParameterSource paramSource) + throws DataAccessException { + return query(sql, paramSource, new ColumnMapRowMapper()); } - public List queryForList(String sql, Map paramMap) throws DataAccessException { + public List> queryForList(String sql, Map paramMap) + throws DataAccessException { + return queryForList(sql, new MapSqlParameterSource(paramMap)); } public SqlRowSet queryForRowSet(String sql, SqlParameterSource paramSource) throws DataAccessException { - return (SqlRowSet) getJdbcOperations().query( + return getJdbcOperations().query( getPreparedStatementCreator(sql, paramSource), new SqlRowSetResultSetExtractor()); } - public SqlRowSet queryForRowSet(String sql, Map paramMap) throws DataAccessException { + public SqlRowSet queryForRowSet(String sql, Map paramMap) throws DataAccessException { return queryForRowSet(sql, new MapSqlParameterSource(paramMap)); } @@ -214,7 +233,7 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations return getJdbcOperations().update(getPreparedStatementCreator(sql, paramSource)); } - public int update(String sql, Map paramMap) throws DataAccessException { + public int update(String sql, Map paramMap) throws DataAccessException { return update(sql, new MapSqlParameterSource(paramMap)); } @@ -266,7 +285,7 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations */ protected ParsedSql getParsedSql(String sql) { synchronized (this.parsedSqlCache) { - ParsedSql parsedSql = (ParsedSql) this.parsedSqlCache.get(sql); + ParsedSql parsedSql = this.parsedSqlCache.get(sql); if (parsedSql == null) { parsedSql = NamedParameterUtils.parseSqlStatement(sql); this.parsedSqlCache.put(sql, parsedSql); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java index 121ffc1f494..7a34f412c61 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterUtils.java @@ -191,7 +191,7 @@ public abstract class NamedParameterUtils { */ public static String substituteNamedParameters(ParsedSql parsedSql, SqlParameterSource paramSource) { String originalSql = parsedSql.getOriginalSql(); - StringBuffer actualSql = new StringBuffer(); + StringBuilder actualSql = new StringBuilder(); List paramNames = parsedSql.getParameterNames(); int lastIndex = 0; for (int i = 0; i < paramNames.size(); i++) { @@ -379,7 +379,7 @@ public abstract class NamedParameterUtils { * @param paramMap the Map of parameters * @return the array of values */ - public static Object[] buildValueArray(String sql, Map paramMap) { + public static Object[] buildValueArray(String sql, Map paramMap) { ParsedSql parsedSql = parseSqlStatement(sql); return buildValueArray(parsedSql, new MapSqlParameterSource(paramMap), null); } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedBeanPropertyRowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedBeanPropertyRowMapper.java index 01493faa035..982ca8ea3e7 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedBeanPropertyRowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedBeanPropertyRowMapper.java @@ -16,9 +16,6 @@ package org.springframework.jdbc.core.simple; -import java.sql.ResultSet; -import java.sql.SQLException; - import org.springframework.jdbc.core.BeanPropertyRowMapper; /** @@ -49,25 +46,9 @@ import org.springframework.jdbc.core.BeanPropertyRowMapper; * @since 2.5 * @see ParameterizedRowMapper */ -public class ParameterizedBeanPropertyRowMapper extends BeanPropertyRowMapper +public class ParameterizedBeanPropertyRowMapper extends BeanPropertyRowMapper implements ParameterizedRowMapper { - /** - * Create a new ParameterizedBeanPropertyRowMapper. - *

Generally prefer the {@link #newInstance(Class)} method instead, - * which avoids the need for specifying the mapped type twice. - * @see #setMappedClass - */ - public ParameterizedBeanPropertyRowMapper() { - } - - @Override - @SuppressWarnings("unchecked") - public T mapRow(ResultSet rs, int rowNumber) throws SQLException { - return (T) super.mapRow(rs, rowNumber); - } - - /** * Static factory method to create a new ParameterizedBeanPropertyRowMapper * (with the mapped class specified only once). diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedRowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedRowMapper.java index fa9d6ee8a2c..b6c75187d24 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedRowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedRowMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +16,18 @@ package org.springframework.jdbc.core.simple; -import java.sql.ResultSet; -import java.sql.SQLException; - import org.springframework.jdbc.core.RowMapper; /** * Extension of the {@link org.springframework.jdbc.core.RowMapper} interface, - * adding type parameterization. Uses Java 5 covariant return types to override - * the return type of the {@link #mapRow} method to be the type parameter - * T. + * adding type parameterization. As of Spring 3.0, this is equivalent to + * using the RowMapper interface directly. * * @author Rob Harrop + * @author Juergen Hoeller * @since 2.0 * @see org.springframework.jdbc.core.simple.SimpleJdbcOperations */ -public interface ParameterizedRowMapper extends RowMapper { - - /** - * Implementations should return the object representation of - * the current row in the supplied {@link ResultSet}. - * @see org.springframework.jdbc.core.RowMapper#mapRow - */ - T mapRow(ResultSet rs, int rowNum) throws SQLException; +public interface ParameterizedRowMapper extends RowMapper { } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedSingleColumnRowMapper.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedSingleColumnRowMapper.java index b31636a46b8..8522d394268 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedSingleColumnRowMapper.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/ParameterizedSingleColumnRowMapper.java @@ -16,9 +16,6 @@ package org.springframework.jdbc.core.simple; -import java.sql.ResultSet; -import java.sql.SQLException; - import org.springframework.jdbc.core.SingleColumnRowMapper; /** @@ -36,25 +33,9 @@ import org.springframework.jdbc.core.SingleColumnRowMapper; * @author Juergen Hoeller * @since 2.5.2 */ -public class ParameterizedSingleColumnRowMapper extends SingleColumnRowMapper +public class ParameterizedSingleColumnRowMapper extends SingleColumnRowMapper implements ParameterizedRowMapper { - /** - * Create a new ParameterizedSingleColumnRowMapper. - *

Generally prefer the {@link #newInstance(Class)} method instead, - * which avoids the need for specifying the mapped type twice. - * @see #setRequiredType - */ - public ParameterizedSingleColumnRowMapper() { - } - - @Override - @SuppressWarnings("unchecked") - public T mapRow(ResultSet rs, int rowNumber) throws SQLException { - return (T) super.mapRow(rs, rowNumber); - } - - /** * Static factory method to create a new ParameterizedSingleColumnRowMapper * (with the required type specified only once). diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcOperations.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcOperations.java index dbd22909a5b..e7aac3aeabb 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcOperations.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,9 +58,9 @@ public interface SimpleJdbcOperations { * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} * and a map containing the arguments. * @param sql the SQL query to run. - * @param args the map containing the arguments for the query. + * @param args the map containing the arguments for the query */ - int queryForInt(String sql, Map args) throws DataAccessException; + int queryForInt(String sql, Map args) throws DataAccessException; /** * Query for an int passing in a SQL query @@ -77,7 +77,7 @@ public interface SimpleJdbcOperations { * using the standard '?' placeholders for parameters * and a variable number of arguments. * @param sql the SQL query to run. - * @param args the variable number of arguments for the query. + * @param args the variable number of arguments for the query */ int queryForInt(String sql, Object... args) throws DataAccessException; @@ -87,9 +87,9 @@ public interface SimpleJdbcOperations { * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} * and a map containing the arguments. * @param sql the SQL query to run. - * @param args the map containing the arguments for the query. + * @param args the map containing the arguments for the query */ - long queryForLong(String sql, Map args) throws DataAccessException; + long queryForLong(String sql, Map args) throws DataAccessException; /** * Query for an long passing in a SQL query @@ -97,7 +97,7 @@ public interface SimpleJdbcOperations { * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} * and a SqlParameterSource containing the arguments. * @param sql the SQL query to run. - * @param args the SqlParameterSource containing the arguments for the query. + * @param args the SqlParameterSource containing the arguments for the query */ long queryForLong(String sql, SqlParameterSource args) throws DataAccessException; @@ -106,7 +106,7 @@ public interface SimpleJdbcOperations { * using the standard '?' placeholders for parameters * and a variable number of arguments. * @param sql the SQL query to run. - * @param args the variable number of arguments for the query. + * @param args the variable number of arguments for the query */ long queryForLong(String sql, Object... args) throws DataAccessException; @@ -114,22 +114,22 @@ public interface SimpleJdbcOperations { * Query for an object of type T identified by the supplied @{@link Class}. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. - * @param requiredType the required type of the return value. - * @param args the map containing the arguments for the query. + * @param sql the SQL query to run + * @param requiredType the required type of the return value + * @param args the map containing the arguments for the query * @see JdbcOperations#queryForObject(String, Class) * @see JdbcOperations#queryForObject(String, Object[], Class) */ - T queryForObject(String sql, Class requiredType, Map args) + T queryForObject(String sql, Class requiredType, Map args) throws DataAccessException; /** * Query for an object of type T identified by the supplied @{@link Class}. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. - * @param requiredType the required type of the return value. - * @param args the SqlParameterSource containing the arguments for the query. + * @param sql the SQL query to run + * @param requiredType the required type of the return value + * @param args the SqlParameterSource containing the arguments for the query * @see JdbcOperations#queryForObject(String, Class) * @see JdbcOperations#queryForObject(String, Object[], Class) */ @@ -139,9 +139,9 @@ public interface SimpleJdbcOperations { /** * Query for an object of type T identified by the supplied @{@link Class}. * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL query to run. - * @param requiredType the required type of the return value. - * @param args the variable number of arguments for the query. + * @param sql the SQL query to run + * @param requiredType the required type of the return value + * @param args the variable number of arguments for the query * @see JdbcOperations#queryForObject(String, Class) * @see JdbcOperations#queryForObject(String, Object[], Class) */ @@ -153,13 +153,13 @@ public interface SimpleJdbcOperations { * {@link ParameterizedRowMapper} to the query results to the object. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. + * @param sql the SQL query to run * @param rm the @{@link ParameterizedRowMapper} to use for result mapping - * @param args the map containing the arguments for the query. + * @param args the map containing the arguments for the query * @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper) * @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper) */ - T queryForObject(String sql, ParameterizedRowMapper rm, Map args) + T queryForObject(String sql, ParameterizedRowMapper rm, Map args) throws DataAccessException; /** @@ -167,9 +167,9 @@ public interface SimpleJdbcOperations { * {@link ParameterizedRowMapper} to the query results to the object. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. + * @param sql the SQL query to run * @param rm the @{@link ParameterizedRowMapper} to use for result mapping - * @param args the SqlParameterSource containing the arguments for the query. + * @param args the SqlParameterSource containing the arguments for the query * @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper) * @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper) */ @@ -180,9 +180,9 @@ public interface SimpleJdbcOperations { * Query for an object of type T using the supplied * {@link ParameterizedRowMapper} to the query results to the object. * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL query to run. + * @param sql the SQL query to run * @param rm the @{@link ParameterizedRowMapper} to use for result mapping - * @param args the variable number of arguments for the query. + * @param args the variable number of arguments for the query * @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper) * @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper) */ @@ -194,13 +194,13 @@ public interface SimpleJdbcOperations { * the supplied {@link ParameterizedRowMapper} to the query results to the object. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. + * @param sql the SQL query to run * @param rm the @{@link ParameterizedRowMapper} to use for result mapping - * @param args the map containing the arguments for the query. + * @param args the map containing the arguments for the query * @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper) * @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper) */ - List query(String sql, ParameterizedRowMapper rm, Map args) + List query(String sql, ParameterizedRowMapper rm, Map args) throws DataAccessException; /** @@ -208,9 +208,9 @@ public interface SimpleJdbcOperations { * the supplied {@link ParameterizedRowMapper} to the query results to the object. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. + * @param sql the SQL query to run * @param rm the @{@link ParameterizedRowMapper} to use for result mapping - * @param args the SqlParameterSource containing the arguments for the query. + * @param args the SqlParameterSource containing the arguments for the query * @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper) * @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper) */ @@ -221,9 +221,9 @@ public interface SimpleJdbcOperations { * Query for a {@link List} of Objects of type T using * the supplied {@link ParameterizedRowMapper} to the query results to the object. * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL query to run. + * @param sql the SQL query to run * @param rm the @{@link ParameterizedRowMapper} to use for result mapping - * @param args the variable number of arguments for the query. + * @param args the variable number of arguments for the query * @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper) * @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper) */ @@ -233,25 +233,25 @@ public interface SimpleJdbcOperations { /** * Execute the supplied query with the supplied arguments. *

The query is expected to be a single row query; the result row will be - * mapped to a Map (one entry for each column, using the column name as the key). + * mapped to a Map (one entry for each column, using the column name as the key). * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. - * @param args the map containing the arguments for the query. + * @param sql the SQL query to run + * @param args the map containing the arguments for the query * @see JdbcOperations#queryForMap(String) * @see JdbcOperations#queryForMap(String, Object[]) */ - Map queryForMap(String sql, Map args) + Map queryForMap(String sql, Map args) throws DataAccessException; /** * Execute the supplied query with the supplied arguments. *

The query is expected to be a single row query; the result row will be - * mapped to a Map (one entry for each column, using the column name as the key). + * mapped to a Map (one entry for each column, using the column name as the key). * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. - * @param args the SqlParameterSource containing the arguments for the query. + * @param sql the SQL query to run + * @param args the SqlParameterSource containing the arguments for the query * @see JdbcOperations#queryForMap(String) * @see JdbcOperations#queryForMap(String, Object[]) */ @@ -261,10 +261,10 @@ public interface SimpleJdbcOperations { /** * Execute the supplied query with the (optional) supplied arguments. *

The query is expected to be a single row query; the result row will be - * mapped to a Map (one entry for each column, using the column name as the key). + * mapped to a Map (one entry for each column, using the column name as the key). * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL query to run. - * @param args the variable number of arguments for the query. + * @param sql the SQL query to run + * @param args the variable number of arguments for the query * @see JdbcOperations#queryForMap(String) * @see JdbcOperations#queryForMap(String, Object[]) */ @@ -277,12 +277,12 @@ public interface SimpleJdbcOperations { * as described in {@link #queryForMap} * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. - * @param args the map containing the arguments for the query. + * @param sql the SQL query to run + * @param args the map containing the arguments for the query * @see JdbcOperations#queryForList(String) * @see JdbcOperations#queryForList(String, Object[]) */ - List> queryForList(String sql, Map args) + List> queryForList(String sql, Map args) throws DataAccessException; /** @@ -291,8 +291,8 @@ public interface SimpleJdbcOperations { * as described in {@link #queryForMap} * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL query to run. - * @param args the SqlParameterSource containing the arguments for the query. + * @param sql the SQL query to run + * @param args the SqlParameterSource containing the arguments for the query * @see JdbcOperations#queryForList(String) * @see JdbcOperations#queryForList(String, Object[]) */ @@ -304,8 +304,8 @@ public interface SimpleJdbcOperations { *

Each element in the returned {@link List} is constructed as a {@link Map} * as described in {@link #queryForMap} * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL query to run. - * @param args the variable number of arguments for the query. + * @param sql the SQL query to run + * @param args the variable number of arguments for the query * @see JdbcOperations#queryForList(String) * @see JdbcOperations#queryForList(String, Object[]) */ @@ -316,20 +316,20 @@ public interface SimpleJdbcOperations { * Execute the supplied SQL statement with (optional) supplied arguments. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL statement to execute. - * @param args the map containing the arguments for the query. - * @return the numbers of rows affected by the update. + * @param sql the SQL statement to execute + * @param args the map containing the arguments for the query + * @return the numbers of rows affected by the update * @see NamedParameterJdbcOperations#update(String, Map) */ - int update(String sql, Map args) throws DataAccessException; + int update(String sql, Map args) throws DataAccessException; /** * Execute the supplied SQL statement with supplied arguments. * Uses sql with the named parameter support provided by the * {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate} - * @param sql the SQL statement to execute. - * @param args the SqlParameterSource containing the arguments for the statement. - * @return the numbers of rows affected by the update. + * @param sql the SQL statement to execute + * @param args the SqlParameterSource containing the arguments for the statement + * @return the numbers of rows affected by the update * @see NamedParameterJdbcOperations#update(String, SqlParameterSource) */ int update(String sql, SqlParameterSource args) throws DataAccessException; @@ -337,9 +337,9 @@ public interface SimpleJdbcOperations { /** * Execute the supplied SQL statement with supplied arguments. * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL statement to execute. - * @param args the variable number of arguments for the query. - * @return the numbers of rows affected by the update. + * @param sql the SQL statement to execute + * @param args the variable number of arguments for the query + * @return the numbers of rows affected by the update * @see JdbcOperations#update(String) * @see JdbcOperations#update(String, Object[]) */ @@ -348,27 +348,27 @@ public interface SimpleJdbcOperations { /** * Executes a batch using the supplied SQL statement with the batch of supplied arguments. * Uses sql with the named parameter support. - * @param sql the SQL statement to execute. - * @param batchValues the array of Maps containing the batch of arguments for the query. - * @return an array containing the numbers of rows affected by each update in the batch. + * @param sql the SQL statement to execute + * @param batchValues the array of Maps containing the batch of arguments for the query + * @return an array containing the numbers of rows affected by each update in the batch */ - public int[] batchUpdate(String sql, Map[] batchValues); + public int[] batchUpdate(String sql, Map[] batchValues); /** * Execute a batch using the supplied SQL statement with the batch of supplied arguments. * Uses sql with the named parameter support. - * @param sql the SQL statement to execute. - * @param batchArgs the array of {@link SqlParameterSource} containing the batch of arguments for the query. - * @return an array containing the numbers of rows affected by each update in the batch. + * @param sql the SQL statement to execute + * @param batchArgs the array of {@link SqlParameterSource} containing the batch of arguments for the query + * @return an array containing the numbers of rows affected by each update in the batch */ public int[] batchUpdate(String sql, SqlParameterSource[] batchArgs); /** * Execute a batch using the supplied SQL statement with the batch of supplied arguments. * Uses sql with the standard '?' placeholders for parameters - * @param sql the SQL statement to execute. - * @param batchArgs the List of Object arrays containing the batch of arguments for the query. - * @return an array containing the numbers of rows affected by each update in the batch. + * @param sql the SQL statement to execute + * @param batchArgs the List of Object arrays containing the batch of arguments for the query + * @return an array containing the numbers of rows affected by each update in the batch */ public int[] batchUpdate(String sql, List batchArgs); @@ -376,10 +376,10 @@ public interface SimpleJdbcOperations { * Execute a batch using the supplied SQL statement with the batch of supplied arguments. * Uses sql with the standard '?' placeholders for parameters * @param sql the SQL statement to execute. - * @param batchArgs the List of Object arrays containing the batch of arguments for the query. + * @param batchArgs the List of Object arrays containing the batch of arguments for the query * @param argTypes SQL types of the arguments * (constants from java.sql.Types) - * @return an array containing the numbers of rows affected by each update in the batch. + * @return an array containing the numbers of rows affected by each update in the batch */ public int[] batchUpdate(String sql, List batchArgs, int[] argTypes); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.java index 0688de0d671..a4866b8b800 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations { } - public int queryForInt(String sql, Map args) throws DataAccessException { + public int queryForInt(String sql, Map args) throws DataAccessException { return getNamedParameterJdbcOperations().queryForInt(sql, args); } @@ -121,7 +121,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations { getJdbcOperations().queryForInt(sql, getArguments(args))); } - public long queryForLong(String sql, Map args) throws DataAccessException { + public long queryForLong(String sql, Map args) throws DataAccessException { return getNamedParameterJdbcOperations().queryForLong(sql, args); } @@ -136,61 +136,61 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations { } @SuppressWarnings("unchecked") - public T queryForObject(String sql, Class requiredType, Map args) throws DataAccessException { - return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType); + public T queryForObject(String sql, Class requiredType, Map args) throws DataAccessException { + return getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType); } @SuppressWarnings("unchecked") public T queryForObject(String sql, Class requiredType, SqlParameterSource args) throws DataAccessException { - return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType); + return getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType); } @SuppressWarnings("unchecked") public T queryForObject(String sql, Class requiredType, Object... args) throws DataAccessException { - return (T) (ObjectUtils.isEmpty(args) ? + return (ObjectUtils.isEmpty(args) ? getJdbcOperations().queryForObject(sql, requiredType) : getJdbcOperations().queryForObject(sql, getArguments(args), requiredType)); } @SuppressWarnings("unchecked") - public T queryForObject(String sql, ParameterizedRowMapper rm, Map args) throws DataAccessException { - return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, rm); + public T queryForObject(String sql, ParameterizedRowMapper rm, Map args) throws DataAccessException { + return getNamedParameterJdbcOperations().queryForObject(sql, args, rm); } @SuppressWarnings("unchecked") public T queryForObject(String sql, ParameterizedRowMapper rm, SqlParameterSource args) throws DataAccessException { - return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, rm); + return getNamedParameterJdbcOperations().queryForObject(sql, args, rm); } @SuppressWarnings("unchecked") public T queryForObject(String sql, ParameterizedRowMapper rm, Object... args) throws DataAccessException { - return (T) (ObjectUtils.isEmpty(args) ? + return (ObjectUtils.isEmpty(args) ? getJdbcOperations().queryForObject(sql, rm): getJdbcOperations().queryForObject(sql, getArguments(args), rm)); } @SuppressWarnings("unchecked") - public List query(String sql, ParameterizedRowMapper rm, Map args) throws DataAccessException { - return (List) getNamedParameterJdbcOperations().query(sql, args, rm); + public List query(String sql, ParameterizedRowMapper rm, Map args) throws DataAccessException { + return getNamedParameterJdbcOperations().query(sql, args, rm); } @SuppressWarnings("unchecked") public List query(String sql, ParameterizedRowMapper rm, SqlParameterSource args) throws DataAccessException { - return (List) getNamedParameterJdbcOperations().query(sql, args, rm); + return getNamedParameterJdbcOperations().query(sql, args, rm); } @SuppressWarnings("unchecked") public List query(String sql, ParameterizedRowMapper rm, Object... args) throws DataAccessException { - return (List) (ObjectUtils.isEmpty(args) ? + return (ObjectUtils.isEmpty(args) ? getJdbcOperations().query(sql, rm) : getJdbcOperations().query(sql, getArguments(args), rm)); } @SuppressWarnings("unchecked") - public Map queryForMap(String sql, Map args) throws DataAccessException { + public Map queryForMap(String sql, Map args) throws DataAccessException { return getNamedParameterJdbcOperations().queryForMap(sql, args); } @@ -208,7 +208,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations { } @SuppressWarnings("unchecked") - public List> queryForList(String sql, Map args) throws DataAccessException { + public List> queryForList(String sql, Map args) throws DataAccessException { return getNamedParameterJdbcOperations().queryForList(sql, args); } @@ -225,7 +225,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations { getJdbcOperations().queryForList(sql, getArguments(args))); } - public int update(String sql, Map args) throws DataAccessException { + public int update(String sql, Map args) throws DataAccessException { return getNamedParameterJdbcOperations().update(sql, args); } @@ -247,10 +247,10 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations { return doExecuteBatchUpdate(sql, batchArgs, argTypes); } - public int[] batchUpdate(String sql, Map[] batchValues) { + public int[] batchUpdate(String sql, Map[] batchValues) { SqlParameterSource[] batchArgs = new SqlParameterSource[batchValues.length]; int i = 0; - for (Map values : batchValues) { + for (Map values : batchValues) { batchArgs[i] = new MapSqlParameterSource(values); i++; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractSqlTypeValue.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractSqlTypeValue.java index 0f5a808ad92..d28df9d4122 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractSqlTypeValue.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractSqlTypeValue.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import org.springframework.jdbc.core.SqlTypeValue; *

proc.declareParameter(new SqlParameter("myarray", Types.ARRAY, "NUMBERS"));
  * ...
  *
- * Map in = new HashMap();
+ * Map<String, Object> in = new HashMap<String, Object>();
  * in.put("myarray", new AbstractSqlTypeValue() {
  *   public Object createTypeValue(Connection con, int sqlType, String typeName) throws SQLException {
  *	   oracle.sql.ArrayDescriptor desc = new oracle.sql.ArrayDescriptor(typeName, con);
diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java
index f2a4e754f94..646d59460af 100644
--- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java
+++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java
@@ -188,12 +188,12 @@ public class TransactionAwareDataSourceProxy extends DelegatingDataSource {
 			}
 			else if (method.getName().equals("toString")) {
 				// Allow for differentiating between the proxy and the raw Connection.
-				StringBuffer buf = new StringBuffer("Transaction-aware proxy for target Connection ");
+				StringBuilder sb = new StringBuilder("Transaction-aware proxy for target Connection ");
 				if (this.target != null) {
-					buf.append("[").append(this.target.toString()).append("]");
+					sb.append("[").append(this.target.toString()).append("]");
 				}
 				else {
-					buf.append(" from DataSource [").append(this.targetDataSource).append("]");
+					sb.append(" from DataSource [").append(this.targetDataSource).append("]");
 				}
 			}
 			else if (method.getName().equals("close")) {
diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookup.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookup.java
index e91852651b7..d09dacf8fe0 100644
--- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookup.java
+++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookup.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2006 the original author or authors.
+ * Copyright 2002-2008 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ package org.springframework.jdbc.datasource.lookup;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
-
 import javax.sql.DataSource;
 
 import org.springframework.util.Assert;
@@ -37,7 +36,7 @@ import org.springframework.util.Assert;
  */
 public class MapDataSourceLookup implements DataSourceLookup {
 
-	private final Map dataSources = new HashMap(4);
+	private final Map dataSources = new HashMap(4);
 
 
 	/**
@@ -51,7 +50,7 @@ public class MapDataSourceLookup implements DataSourceLookup {
 	 * @param dataSources the {@link Map} of {@link DataSource DataSources}; the keys
 	 * are {@link String Strings}, the values are actual {@link DataSource} instances.
 	 */
-	public MapDataSourceLookup(Map dataSources) {
+	public MapDataSourceLookup(Map dataSources) {
 		setDataSources(dataSources);
 	}
 
@@ -72,7 +71,7 @@ public class MapDataSourceLookup implements DataSourceLookup {
 	 * call effectively has no effect. 
 	 * @param dataSources said {@link Map} of {@link DataSource DataSources}
 	 */
-	public void setDataSources(Map dataSources) {
+	public void setDataSources(Map dataSources) {
 		if (dataSources != null) {
 			this.dataSources.putAll(dataSources);
 		}
@@ -83,7 +82,7 @@ public class MapDataSourceLookup implements DataSourceLookup {
 	 * 

The returned {@link Map} is {@link Collections#unmodifiableMap(java.util.Map) unmodifiable}. * @return said {@link Map} of {@link DataSource DataSources} (never null) */ - public Map getDataSources() { + public Map getDataSources() { return Collections.unmodifiableMap(this.dataSources); } @@ -101,17 +100,12 @@ public class MapDataSourceLookup implements DataSourceLookup { public DataSource getDataSource(String dataSourceName) throws DataSourceLookupFailureException { Assert.notNull(dataSourceName, "DataSource name must not be null"); - Object value = this.dataSources.get(dataSourceName); - if (value == null) { + DataSource dataSource = this.dataSources.get(dataSourceName); + if (dataSource == null) { throw new DataSourceLookupFailureException( "No DataSource with name '" + dataSourceName + "' registered"); } - if (!(value instanceof DataSource)) { - throw new DataSourceLookupFailureException( - "The object [" + value + "] with name '" + dataSourceName + - "' in the DataSource map is not a [javax.sql.DataSource]"); - } - return (DataSource) value; + return dataSource; } } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/GeneratedKeyHolder.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/GeneratedKeyHolder.java index cc0f52a5bba..a624e3fa3d6 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/GeneratedKeyHolder.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/GeneratedKeyHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,21 +38,21 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; */ public class GeneratedKeyHolder implements KeyHolder { - private final List keyList; + private final List> keyList; /** * Create a new GeneratedKeyHolder with a default list. */ public GeneratedKeyHolder() { - this.keyList = new LinkedList(); + this.keyList = new LinkedList>(); } /** * Create a new GeneratedKeyHolder with a given list. * @param keyList a list to hold maps of keys */ - public GeneratedKeyHolder(List keyList) { + public GeneratedKeyHolder(List> keyList) { this.keyList = keyList; } @@ -61,12 +61,12 @@ public class GeneratedKeyHolder implements KeyHolder { if (this.keyList.size() == 0) { return null; } - if (this.keyList.size() > 1 || ((Map) this.keyList.get(0)).size() > 1) { + if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) { throw new InvalidDataAccessApiUsageException( "The getKey method should only be used when a single key is returned. " + "The current key entry contains multiple keys: " + this.keyList); } - Iterator keyIter = ((Map) this.keyList.get(0)).values().iterator(); + Iterator keyIter = this.keyList.get(0).values().iterator(); if (keyIter.hasNext()) { Object key = keyIter.next(); if (!(key instanceof Number)) { @@ -83,7 +83,7 @@ public class GeneratedKeyHolder implements KeyHolder { } } - public Map getKeys() throws InvalidDataAccessApiUsageException { + public Map getKeys() throws InvalidDataAccessApiUsageException { if (this.keyList.size() == 0) { return null; } @@ -91,10 +91,10 @@ public class GeneratedKeyHolder implements KeyHolder { throw new InvalidDataAccessApiUsageException( "The getKeys method should only be used when keys for a single row are returned. " + "The current key list contains keys for multiple rows: " + this.keyList); - return (Map) this.keyList.get(0); + return this.keyList.get(0); } - public List getKeyList() { + public List> getKeyList() { return this.keyList; } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/JdbcUtils.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/JdbcUtils.java index 33947f96297..38fdc351b1d 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/JdbcUtils.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/JdbcUtils.java @@ -432,7 +432,7 @@ public abstract class JdbcUtils { * @return the name using "camel case" */ public static String convertUnderscoreNameToPropertyName(String name) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); boolean nextIsUpper = false; if (name != null && name.length() > 0) { if (name.length() > 1 && name.substring(1,2).equals("_")) { diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/KeyHolder.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/KeyHolder.java index a2b8d4c6cf4..481623c4321 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/KeyHolder.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/KeyHolder.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,6 +35,7 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; * usual type for auto-generated keys. * * @author Thomas Risberg + * @author Juergen Hoeller * @since 1.1 * @see org.springframework.jdbc.core.JdbcTemplate * @see org.springframework.jdbc.object.SqlUpdate @@ -62,7 +63,7 @@ public interface KeyHolder { * @return the Map of generated keys * @throws InvalidDataAccessApiUsageException if keys for multiple rows are encountered */ - Map getKeys() throws InvalidDataAccessApiUsageException; + Map getKeys() throws InvalidDataAccessApiUsageException; /** * Return a reference to the List that contains the keys. @@ -71,6 +72,6 @@ public interface KeyHolder { * @return the List for the generated keys, with each entry being a Map * of column names and key values */ - List getKeyList(); + List> getKeyList(); } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/incrementer/AbstractDataFieldMaxValueIncrementer.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/incrementer/AbstractDataFieldMaxValueIncrementer.java index 6e3a1090502..b0e62847f86 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/incrementer/AbstractDataFieldMaxValueIncrementer.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/support/incrementer/AbstractDataFieldMaxValueIncrementer.java @@ -129,12 +129,12 @@ public abstract class AbstractDataFieldMaxValueIncrementer implements DataFieldM String s = Long.toString(getNextKey()); int len = s.length(); if (len < this.paddingLength) { - StringBuffer buf = new StringBuffer(this.paddingLength); + StringBuilder sb = new StringBuilder(this.paddingLength); for (int i = 0; i < this.paddingLength - len; i++) { - buf.append('0'); + sb.append('0'); } - buf.append(s); - s = buf.toString(); + sb.append(s); + s = sb.toString(); } return s; } diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/core/BrowserCallback.java b/org.springframework.jms/src/main/java/org/springframework/jms/core/BrowserCallback.java index 88ab1674393..2ca94fd6bb9 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/core/BrowserCallback.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/core/BrowserCallback.java @@ -31,7 +31,7 @@ import javax.jms.Session; * @see JmsTemplate#browse(BrowserCallback) * @see JmsTemplate#browseSelected(String, BrowserCallback) */ -public interface BrowserCallback { +public interface BrowserCallback { /** * Perform operations on the given {@link javax.jms.Session} and {@link javax.jms.QueueBrowser}. @@ -41,6 +41,6 @@ public interface BrowserCallback { * @return a result object from working with the Session, if any (can be null) * @throws javax.jms.JMSException if thrown by JMS API methods */ - Object doInJms(Session session, QueueBrowser browser) throws JMSException; + T doInJms(Session session, QueueBrowser browser) throws JMSException; } diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsOperations.java b/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsOperations.java index e01d371b0e6..6ea64fcb324 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsOperations.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsOperations.java @@ -52,7 +52,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException if there is any problem */ - Object execute(SessionCallback action) throws JmsException; + T execute(SessionCallback action) throws JmsException; /** * Send messages to the default JMS destination (or one specified @@ -62,7 +62,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object execute(ProducerCallback action) throws JmsException; + T execute(ProducerCallback action) throws JmsException; /** * Send messages to a JMS destination. The callback gives access to the JMS Session @@ -72,7 +72,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object execute(Destination destination, ProducerCallback action) throws JmsException; + T execute(Destination destination, ProducerCallback action) throws JmsException; /** * Send messages to a JMS destination. The callback gives access to the JMS Session @@ -83,7 +83,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object execute(String destinationName, ProducerCallback action) throws JmsException; + T execute(String destinationName, ProducerCallback action) throws JmsException; //------------------------------------------------------------------------- @@ -363,7 +363,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object browse(BrowserCallback action) throws JmsException; + T browse(BrowserCallback action) throws JmsException; /** * Browse messages in a JMS queue. The callback gives access to the JMS Session @@ -373,7 +373,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object browse(Queue queue, BrowserCallback action) throws JmsException; + T browse(Queue queue, BrowserCallback action) throws JmsException; /** * Browse messages in a JMS queue. The callback gives access to the JMS Session @@ -384,7 +384,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object browse(String queueName, BrowserCallback action) throws JmsException; + T browse(String queueName, BrowserCallback action) throws JmsException; /** * Browse selected messages in a JMS queue. The callback gives access to the JMS @@ -395,7 +395,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object browseSelected(String messageSelector, BrowserCallback action) throws JmsException; + T browseSelected(String messageSelector, BrowserCallback action) throws JmsException; /** * Browse selected messages in a JMS queue. The callback gives access to the JMS @@ -407,7 +407,7 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object browseSelected(Queue queue, String messageSelector, BrowserCallback action) throws JmsException; + T browseSelected(Queue queue, String messageSelector, BrowserCallback action) throws JmsException; /** * Browse selected messages in a JMS queue. The callback gives access to the JMS @@ -420,6 +420,6 @@ public interface JmsOperations { * @return the result object from working with the session * @throws JmsException checked JMSException converted to unchecked */ - Object browseSelected(String queueName, String messageSelector, BrowserCallback action) throws JmsException; + T browseSelected(String queueName, String messageSelector, BrowserCallback action) throws JmsException; } diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsTemplate.java b/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsTemplate.java index bd2468fa901..61cd8fb4a3b 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsTemplate.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/core/JmsTemplate.java @@ -432,7 +432,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations // JmsOperations execute methods //------------------------------------------------------------------------- - public Object execute(SessionCallback action) throws JmsException { + public T execute(SessionCallback action) throws JmsException { return execute(action, false); } @@ -450,7 +450,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations * @see #execute(SessionCallback) * @see #receive */ - public Object execute(SessionCallback action, boolean startConnection) throws JmsException { + public T execute(SessionCallback action, boolean startConnection) throws JmsException { Assert.notNull(action, "Callback object must not be null"); Connection conToClose = null; Session sessionToClose = null; @@ -479,7 +479,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations } } - public Object execute(ProducerCallback action) throws JmsException { + public T execute(ProducerCallback action) throws JmsException { String defaultDestinationName = getDefaultDestinationName(); if (defaultDestinationName != null) { return execute(defaultDestinationName, action); @@ -489,10 +489,10 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations } } - public Object execute(final Destination destination, final ProducerCallback action) throws JmsException { + public T execute(final Destination destination, final ProducerCallback action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); - return execute(new SessionCallback() { - public Object doInJms(Session session) throws JMSException { + return execute(new SessionCallback() { + public T doInJms(Session session) throws JMSException { MessageProducer producer = createProducer(session, destination); try { return action.doInJms(session, producer); @@ -504,10 +504,10 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations }, false); } - public Object execute(final String destinationName, final ProducerCallback action) throws JmsException { + public T execute(final String destinationName, final ProducerCallback action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); - return execute(new SessionCallback() { - public Object doInJms(Session session) throws JMSException { + return execute(new SessionCallback() { + public T doInJms(Session session) throws JMSException { Destination destination = resolveDestinationName(session, destinationName); MessageProducer producer = createProducer(session, destination); try { @@ -826,7 +826,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations // Convenience methods for browsing messages //------------------------------------------------------------------------- - public Object browse(BrowserCallback action) throws JmsException { + public T browse(BrowserCallback action) throws JmsException { Queue defaultQueue = getDefaultQueue(); if (defaultQueue != null) { return browse(defaultQueue, action); @@ -836,15 +836,15 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations } } - public Object browse(Queue queue, BrowserCallback action) throws JmsException { + public T browse(Queue queue, BrowserCallback action) throws JmsException { return browseSelected(queue, null, action); } - public Object browse(String queueName, BrowserCallback action) throws JmsException { + public T browse(String queueName, BrowserCallback action) throws JmsException { return browseSelected(queueName, null, action); } - public Object browseSelected(String messageSelector, BrowserCallback action) throws JmsException { + public T browseSelected(String messageSelector, BrowserCallback action) throws JmsException { Queue defaultQueue = getDefaultQueue(); if (defaultQueue != null) { return browseSelected(defaultQueue, messageSelector, action); @@ -854,12 +854,12 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations } } - public Object browseSelected(final Queue queue, final String messageSelector, final BrowserCallback action) + public T browseSelected(final Queue queue, final String messageSelector, final BrowserCallback action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); - return execute(new SessionCallback() { - public Object doInJms(Session session) throws JMSException { + return execute(new SessionCallback() { + public T doInJms(Session session) throws JMSException { QueueBrowser browser = createBrowser(session, queue, messageSelector); try { return action.doInJms(session, browser); @@ -871,12 +871,12 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations }, true); } - public Object browseSelected(final String queueName, final String messageSelector, final BrowserCallback action) + public T browseSelected(final String queueName, final String messageSelector, final BrowserCallback action) throws JmsException { Assert.notNull(action, "Callback object must not be null"); - return execute(new SessionCallback() { - public Object doInJms(Session session) throws JMSException { + return execute(new SessionCallback() { + public T doInJms(Session session) throws JMSException { Queue queue = (Queue) getDestinationResolver().resolveDestinationName(session, queueName, false); QueueBrowser browser = createBrowser(session, queue, messageSelector); try { diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/core/ProducerCallback.java b/org.springframework.jms/src/main/java/org/springframework/jms/core/ProducerCallback.java index 0c9cd483d6b..037b8df4867 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/core/ProducerCallback.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/core/ProducerCallback.java @@ -38,7 +38,7 @@ import javax.jms.Session; * @see JmsTemplate#execute(javax.jms.Destination, ProducerCallback) * @see JmsTemplate#execute(String, ProducerCallback) */ -public interface ProducerCallback { +public interface ProducerCallback { /** * Perform operations on the given {@link Session} and {@link MessageProducer}. @@ -49,6 +49,6 @@ public interface ProducerCallback { * @return a result object from working with the Session, if any (can be null) * @throws javax.jms.JMSException if thrown by JMS API methods */ - Object doInJms(Session session, MessageProducer producer) throws JMSException; + T doInJms(Session session, MessageProducer producer) throws JMSException; } diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/core/SessionCallback.java b/org.springframework.jms/src/main/java/org/springframework/jms/core/SessionCallback.java index 296fad63008..cf6fe1545c2 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/core/SessionCallback.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/core/SessionCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import javax.jms.Session; * @since 1.1 * @see JmsTemplate#execute(SessionCallback) */ -public interface SessionCallback { +public interface SessionCallback { /** * Execute any number of operations against the supplied JMS @@ -39,6 +39,6 @@ public interface SessionCallback { * @return a result object from working with the Session, if any (so can be null) * @throws javax.jms.JMSException if thrown by JMS API methods */ - Object doInJms(Session session) throws JMSException; + T doInJms(Session session) throws JMSException; } diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java index 3b55d446597..4da11960631 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java @@ -738,7 +738,7 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe logger.debug("Setup of JMS message listener invoker failed - already recovered by other invoker", ex); } else { - StringBuffer msg = new StringBuffer(); + StringBuilder msg = new StringBuilder(); msg.append("Setup of JMS message listener invoker failed for destination '"); msg.append(getDestinationDescription()).append("' - trying to recover. Cause: "); msg.append(ex instanceof JMSException ? JmsUtils.buildExceptionMessage((JMSException) ex) : ex.getMessage()); @@ -791,7 +791,7 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe break; } catch (Exception ex) { - StringBuffer msg = new StringBuffer(); + StringBuilder msg = new StringBuilder(); msg.append("Could not refresh JMS Connection for destination '"); msg.append(getDestinationDescription()).append("' - retrying in "); msg.append(this.recoveryInterval).append(" ms. Cause: "); diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java index c63c3ac4d93..bb774c7ee92 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/FilterDefinitionFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,11 @@ package org.springframework.orm.hibernate3; -import java.util.Enumeration; import java.util.HashMap; import java.util.Map; -import java.util.Properties; import org.hibernate.engine.FilterDefinition; +import org.hibernate.type.Type; import org.hibernate.type.TypeFactory; import org.springframework.beans.factory.BeanNameAware; @@ -44,10 +43,10 @@ import org.springframework.beans.factory.InitializingBean; * <bean class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean"> * <property name="filterName" value="myFilter"/> * <property name="parameterTypes"> - * <props> - * <prop key="myParam">string</prop> - * <prop key="myOtherParam">long</prop> - * </props> + * <map> + * <entry key="myParam" value="string"/> + * <entry key="myOtherParam" value="long"/> + * </map> * </property> * </bean> * </list> @@ -63,11 +62,11 @@ import org.springframework.beans.factory.InitializingBean; * @see org.hibernate.engine.FilterDefinition * @see LocalSessionFactoryBean#setFilterDefinitions */ -public class FilterDefinitionFactoryBean implements FactoryBean, BeanNameAware, InitializingBean { +public class FilterDefinitionFactoryBean implements FactoryBean, BeanNameAware, InitializingBean { private String filterName; - private Map parameterTypeMap = new HashMap(); + private Map parameterTypeMap = new HashMap(); private String defaultFilterCondition; @@ -86,17 +85,15 @@ public class FilterDefinitionFactoryBean implements FactoryBean, BeanNameAware, * with parameter names as keys and type names as values. * @see org.hibernate.type.TypeFactory#heuristicType(String) */ - public void setParameterTypes(Properties parameterTypes) { + public void setParameterTypes(Map parameterTypes) { if (parameterTypes != null) { - this.parameterTypeMap = new HashMap(parameterTypes.size()); - for (Enumeration names = parameterTypes.propertyNames(); names.hasMoreElements();) { - String paramName = (String) names.nextElement(); - String typeName = parameterTypes.getProperty(paramName); - this.parameterTypeMap.put(paramName, TypeFactory.heuristicType(typeName)); + this.parameterTypeMap = new HashMap(parameterTypes.size()); + for (Map.Entry entry : parameterTypes.entrySet()) { + this.parameterTypeMap.put(entry.getKey(), TypeFactory.heuristicType(entry.getValue())); } } else { - this.parameterTypeMap = new HashMap(); + this.parameterTypeMap = new HashMap(); } } @@ -124,11 +121,11 @@ public class FilterDefinitionFactoryBean implements FactoryBean, BeanNameAware, } - public Object getObject() { + public FilterDefinition getObject() { return this.filterDefinition; } - public Class getObjectType() { + public Class getObjectType() { return FilterDefinition.class; } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateOperations.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateOperations.java index 72ead6095f3..a18cc416780 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateOperations.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateOperations.java @@ -116,7 +116,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.Session#get(Class, java.io.Serializable) */ - Object get(Class entityClass, Serializable id) throws DataAccessException; + T get(Class entityClass, Serializable id) throws DataAccessException; /** * Return the persistent instance of the given entity class @@ -133,7 +133,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.Session#get(Class, java.io.Serializable, org.hibernate.LockMode) */ - Object get(Class entityClass, Serializable id, LockMode lockMode) + T get(Class entityClass, Serializable id, LockMode lockMode) throws DataAccessException; /** @@ -183,7 +183,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.Session#load(Class, java.io.Serializable) */ - Object load(Class entityClass, Serializable id) throws DataAccessException; + T load(Class entityClass, Serializable id) throws DataAccessException; /** * Return the persistent instance of the given entity class @@ -201,7 +201,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.Session#load(Class, java.io.Serializable) */ - Object load(Class entityClass, Serializable id, LockMode lockMode) + T load(Class entityClass, Serializable id, LockMode lockMode) throws DataAccessException; /** @@ -247,7 +247,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException if there is a Hibernate error * @see org.hibernate.Session#createCriteria */ - List loadAll(Class entityClass) throws DataAccessException; + List loadAll(Class entityClass) throws DataAccessException; /** * Load the persistent instance with the given identifier @@ -510,7 +510,7 @@ public interface HibernateOperations { * @see #saveOrUpdate * @see org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener */ - Object merge(Object entity) throws DataAccessException; + T merge(T entity) throws DataAccessException; /** * Copy the state of the given object onto the persistent object @@ -637,7 +637,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.Session#createQuery */ - List find(String queryString, Object[] values) throws DataAccessException; + List find(String queryString, Object... values) throws DataAccessException; /** * Execute an HQL query, binding one value to a ":" named parameter @@ -714,7 +714,7 @@ public interface HibernateOperations { * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.Session#getNamedQuery(String) */ - List findByNamedQuery(String queryName, Object[] values) throws DataAccessException; + List findByNamedQuery(String queryName, Object... values) throws DataAccessException; /** * Execute a named query, binding one value to a ":" named parameter @@ -889,7 +889,7 @@ public interface HibernateOperations { * @see org.hibernate.Session#createQuery * @see org.hibernate.Query#iterate */ - Iterator iterate(String queryString, Object[] values) throws DataAccessException; + Iterator iterate(String queryString, Object... values) throws DataAccessException; /** * Immediately close an {@link Iterator} created by any of the various @@ -933,6 +933,6 @@ public interface HibernateOperations { * @see org.hibernate.Session#createQuery * @see org.hibernate.Query#executeUpdate */ - int bulkUpdate(String queryString, Object[] values) throws DataAccessException; + int bulkUpdate(String queryString, Object... values) throws DataAccessException; } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTemplate.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTemplate.java index 8eb4ac493e6..1b81c17d73a 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTemplate.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTemplate.java @@ -516,14 +516,15 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe // Convenience methods for loading individual objects //------------------------------------------------------------------------- - public Object get(Class entityClass, Serializable id) throws DataAccessException { + public T get(Class entityClass, Serializable id) throws DataAccessException { return get(entityClass, id, null); } - public Object get(final Class entityClass, final Serializable id, final LockMode lockMode) + @SuppressWarnings("unchecked") + public T get(final Class entityClass, final Serializable id, final LockMode lockMode) throws DataAccessException { - return executeWithNativeSession(new HibernateCallback() { + return (T) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { if (lockMode != null) { return session.get(entityClass, id, lockMode); @@ -554,14 +555,15 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe }); } - public Object load(Class entityClass, Serializable id) throws DataAccessException { + public T load(Class entityClass, Serializable id) throws DataAccessException { return load(entityClass, id, null); } - public Object load(final Class entityClass, final Serializable id, final LockMode lockMode) + @SuppressWarnings("unchecked") + public T load(final Class entityClass, final Serializable id, final LockMode lockMode) throws DataAccessException { - return executeWithNativeSession(new HibernateCallback() { + return (T) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { if (lockMode != null) { return session.load(entityClass, id, lockMode); @@ -592,8 +594,9 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe }); } - public List loadAll(final Class entityClass) throws DataAccessException { - return (List) executeWithNativeSession(new HibernateCallback() { + @SuppressWarnings("unchecked") + public List loadAll(final Class entityClass) throws DataAccessException { + return (List) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = session.createCriteria(entityClass); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); @@ -631,12 +634,11 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe } public boolean contains(final Object entity) throws DataAccessException { - Boolean result = (Boolean) executeWithNativeSession(new HibernateCallback() { + return (Boolean) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) { - return (session.contains(entity) ? Boolean.TRUE : Boolean.FALSE); + return session.contains(entity); } }); - return result.booleanValue(); } public void evict(final Object entity) throws DataAccessException { @@ -769,8 +771,8 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); - for (Iterator it = entities.iterator(); it.hasNext();) { - session.saveOrUpdate(it.next()); + for (Object entity : entities) { + session.saveOrUpdate(entity); } return null; } @@ -879,8 +881,8 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); - for (Iterator it = entities.iterator(); it.hasNext();) { - session.delete(it.next()); + for (Object entity : entities) { + session.delete(entity); } return null; } @@ -918,7 +920,7 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe return find(queryString, new Object[] {value}); } - public List find(final String queryString, final Object[] values) throws DataAccessException { + public List find(final String queryString, final Object... values) throws DataAccessException { return (List) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); @@ -985,7 +987,7 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe return findByNamedQuery(queryName, new Object[] {value}); } - public List findByNamedQuery(final String queryName, final Object[] values) throws DataAccessException { + public List findByNamedQuery(final String queryName, final Object... values) throws DataAccessException { return (List) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.getNamedQuery(queryName); @@ -1115,7 +1117,7 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe return iterate(queryString, new Object[] {value}); } - public Iterator iterate(final String queryString, final Object[] values) throws DataAccessException { + public Iterator iterate(final String queryString, final Object... values) throws DataAccessException { return (Iterator) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); @@ -1147,8 +1149,8 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe return bulkUpdate(queryString, new Object[] {value}); } - public int bulkUpdate(final String queryString, final Object[] values) throws DataAccessException { - Integer updateCount = (Integer) executeWithNativeSession(new HibernateCallback() { + public int bulkUpdate(final String queryString, final Object... values) throws DataAccessException { + return (Integer) executeWithNativeSession(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); prepareQuery(queryObject); @@ -1157,10 +1159,9 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe queryObject.setParameter(i, values[i]); } } - return new Integer(queryObject.executeUpdate()); + return queryObject.executeUpdate(); } }); - return updateCount.intValue(); } @@ -1282,7 +1283,7 @@ public class HibernateTemplate extends HibernateAccessor implements HibernateOpe } else if (method.getName().equals("hashCode")) { // Use hashCode of Session proxy. - return new Integer(System.identityHashCode(proxy)); + return System.identityHashCode(proxy); } else if (method.getName().equals("close")) { // Handle close method: suppress, not valid. diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionHolder.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionHolder.java index 23beab4cf01..ebcde69b3b6 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionHolder.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public class SessionHolder extends ResourceHolderSupport { * This Map needs to be synchronized because there might be multi-threaded * access in the case of JTA with remote transaction propagation. */ - private final Map sessionMap = Collections.synchronizedMap(new HashMap(1)); + private final Map sessionMap = Collections.synchronizedMap(new HashMap(1)); private Transaction transaction; @@ -68,7 +68,7 @@ public class SessionHolder extends ResourceHolderSupport { } public Session getSession(Object key) { - return (Session) this.sessionMap.get(key); + return this.sessionMap.get(key); } public Session getValidatedSession() { @@ -76,7 +76,7 @@ public class SessionHolder extends ResourceHolderSupport { } public Session getValidatedSession(Object key) { - Session session = (Session) this.sessionMap.get(key); + Session session = this.sessionMap.get(key); // Check for dangling Session that's around but already closed. // Effectively an assertion: that should never happen in practice. // We'll seamlessly remove the Session here, to not let it cause @@ -91,7 +91,7 @@ public class SessionHolder extends ResourceHolderSupport { public Session getAnySession() { synchronized (this.sessionMap) { if (!this.sessionMap.isEmpty()) { - return (Session) this.sessionMap.values().iterator().next(); + return this.sessionMap.values().iterator().next(); } return null; } @@ -108,7 +108,7 @@ public class SessionHolder extends ResourceHolderSupport { } public Session removeSession(Object key) { - return (Session) this.sessionMap.remove(key); + return this.sessionMap.remove(key); } public boolean containsSession(Session session) { diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryBean.java b/org.springframework.orm/src/main/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryBean.java index 172b3c83808..9730af99774 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryBean.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,7 @@ public class LocalPersistenceManagerFactoryBean private Resource configLocation; - private final Map jdoPropertyMap = new HashMap(); + private final Map jdoPropertyMap = new HashMap(); private ClassLoader beanClassLoader; @@ -165,7 +165,7 @@ public class LocalPersistenceManagerFactoryBean *

Can be populated with a "map" or "props" element in XML bean definitions. * @see javax.jdo.JDOHelper#getPersistenceManagerFactory(java.util.Map) */ - public void setJdoPropertyMap(Map jdoProperties) { + public void setJdoPropertyMap(Map jdoProperties) { if (jdoProperties != null) { this.jdoPropertyMap.putAll(jdoProperties); } @@ -177,7 +177,7 @@ public class LocalPersistenceManagerFactoryBean *

Useful for specifying entries directly, for example via * "jdoPropertyMap[myKey]". */ - public Map getJdoPropertyMap() { + public Map getJdoPropertyMap() { return this.jdoPropertyMap; } /** @@ -218,18 +218,15 @@ public class LocalPersistenceManagerFactoryBean } else { - Map mergedProps = new HashMap(); - + Map mergedProps = new HashMap(); if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading JDO config from [" + this.configLocation + "]"); } - mergedProps.putAll(PropertiesLoaderUtils.loadProperties(this.configLocation)); + CollectionUtils.mergePropertiesIntoMap( + PropertiesLoaderUtils.loadProperties(this.configLocation), mergedProps); } - mergedProps.putAll(this.jdoPropertyMap); - - // Build PersistenceManagerFactory instance. logger.info("Building new JDO PersistenceManagerFactory"); this.persistenceManagerFactory = newPersistenceManagerFactory(mergedProps); } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java index 33060d4ff19..cc3f3f8b2c0 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java @@ -83,7 +83,7 @@ public abstract class AbstractEntityManagerFactoryBean implements private String persistenceUnitName; - private final Map jpaPropertyMap = new HashMap(); + private final Map jpaPropertyMap = new HashMap(); private Class entityManagerFactoryInterface; @@ -166,7 +166,7 @@ public abstract class AbstractEntityManagerFactoryBean implements * @see javax.persistence.Persistence#createEntityManagerFactory(String, java.util.Map) * @see javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map) */ - public void setJpaPropertyMap(Map jpaProperties) { + public void setJpaPropertyMap(Map jpaProperties) { if (jpaProperties != null) { this.jpaPropertyMap.putAll(jpaProperties); } @@ -178,7 +178,7 @@ public abstract class AbstractEntityManagerFactoryBean implements *

Useful for specifying entries directly, for example via * "jpaPropertyMap[myKey]". */ - public Map getJpaPropertyMap() { + public Map getJpaPropertyMap() { return this.jpaPropertyMap; } @@ -260,9 +260,9 @@ public abstract class AbstractEntityManagerFactoryBean implements if (this.persistenceProvider == null) { this.persistenceProvider = this.jpaVendorAdapter.getPersistenceProvider(); } - Map vendorPropertyMap = this.jpaVendorAdapter.getJpaPropertyMap(); + Map vendorPropertyMap = this.jpaVendorAdapter.getJpaPropertyMap(); if (vendorPropertyMap != null) { - for (Map.Entry entry : vendorPropertyMap.entrySet()) { + for (Map.Entry entry : vendorPropertyMap.entrySet()) { if (!this.jpaPropertyMap.containsKey(entry.getKey())) { this.jpaPropertyMap.put(entry.getKey(), entry.getValue()); } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryAccessor.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryAccessor.java index a21cfaf514e..c99bc788682 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryAccessor.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryAccessor.java @@ -47,7 +47,7 @@ public abstract class EntityManagerFactoryAccessor { private EntityManagerFactory entityManagerFactory; - private final Map jpaPropertyMap = new HashMap(); + private final Map jpaPropertyMap = new HashMap(); /** @@ -85,7 +85,7 @@ public abstract class EntityManagerFactoryAccessor { *

Can be populated with a "map" or "props" element in XML bean definitions. * @see javax.persistence.EntityManagerFactory#createEntityManager(java.util.Map) */ - public void setJpaPropertyMap(Map jpaProperties) { + public void setJpaPropertyMap(Map jpaProperties) { if (jpaProperties != null) { this.jpaPropertyMap.putAll(jpaProperties); } @@ -96,7 +96,7 @@ public abstract class EntityManagerFactoryAccessor { * provider, with the option to add or override specific entries. *

Useful for specifying entries directly, for example via "jpaPropertyMap[myKey]". */ - public Map getJpaPropertyMap() { + public Map getJpaPropertyMap() { return this.jpaPropertyMap; } @@ -112,7 +112,7 @@ public abstract class EntityManagerFactoryAccessor { protected EntityManager createEntityManager() throws IllegalStateException { EntityManagerFactory emf = getEntityManagerFactory(); Assert.state(emf != null, "No EntityManagerFactory specified"); - Map properties = getJpaPropertyMap(); + Map properties = getJpaPropertyMap(); return (!CollectionUtils.isEmpty(properties) ? emf.createEntityManager(properties) : emf.createEntityManager()); } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaOperations.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaOperations.java index 3e7b8ae138f..5ce389922a9 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaOperations.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,12 +73,12 @@ public interface JpaOperations { List find(String queryString, Object... values) throws DataAccessException; - List findByNamedParams(String queryString, Map params) throws DataAccessException; + List findByNamedParams(String queryString, Map params) throws DataAccessException; List findByNamedQuery(String queryName) throws DataAccessException; List findByNamedQuery(String queryName, Object... values) throws DataAccessException; - List findByNamedQueryAndNamedParams(String queryName, Map params) throws DataAccessException; + List findByNamedQueryAndNamedParams(String queryName, Map params) throws DataAccessException; } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaTransactionManager.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaTransactionManager.java index 919a2609fc7..b4bc36e791f 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaTransactionManager.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaTransactionManager.java @@ -109,7 +109,7 @@ public class JpaTransactionManager extends AbstractPlatformTransactionManager private EntityManagerFactory entityManagerFactory; - private final Map jpaPropertyMap = new HashMap(); + private final Map jpaPropertyMap = new HashMap(); private DataSource dataSource; @@ -167,7 +167,7 @@ public class JpaTransactionManager extends AbstractPlatformTransactionManager *

Can be populated with a "map" or "props" element in XML bean definitions. * @see javax.persistence.EntityManagerFactory#createEntityManager(java.util.Map) */ - public void setJpaPropertyMap(Map jpaProperties) { + public void setJpaPropertyMap(Map jpaProperties) { if (jpaProperties != null) { this.jpaPropertyMap.putAll(jpaProperties); } @@ -178,7 +178,7 @@ public class JpaTransactionManager extends AbstractPlatformTransactionManager * provider, with the option to add or override specific entries. *

Useful for specifying entries directly, for example via "jpaPropertyMap[myKey]". */ - public Map getJpaPropertyMap() { + public Map getJpaPropertyMap() { return this.jpaPropertyMap; } @@ -315,8 +315,6 @@ public class JpaTransactionManager extends AbstractPlatformTransactionManager "on a single DataSource, no matter whether JPA or JDBC access."); } - EntityManager em = null; - try { if (txObject.getEntityManagerHolder() == null || txObject.getEntityManagerHolder().isSynchronizedWithTransaction()) { @@ -327,7 +325,7 @@ public class JpaTransactionManager extends AbstractPlatformTransactionManager txObject.setEntityManagerHolder(new EntityManagerHolder(newEm), true); } - em = txObject.getEntityManagerHolder().getEntityManager(); + EntityManager em = txObject.getEntityManagerHolder().getEntityManager(); // Delegate to JpaDialect for actual transaction begin. Object transactionData = getJpaDialect().beginTransaction(em, definition); @@ -391,7 +389,7 @@ public class JpaTransactionManager extends AbstractPlatformTransactionManager if (emf instanceof EntityManagerFactoryInfo) { emf = ((EntityManagerFactoryInfo) emf).getNativeEntityManagerFactory(); } - Map properties = getJpaPropertyMap(); + Map properties = getJpaPropertyMap(); return (!CollectionUtils.isEmpty(properties) ? emf.createEntityManager(properties) : emf.createEntityManager()); } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaVendorAdapter.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaVendorAdapter.java index 52598a1141d..4f180d2ceb4 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaVendorAdapter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/JpaVendorAdapter.java @@ -59,7 +59,7 @@ public interface JpaVendorAdapter { * @see javax.persistence.Persistence#createEntityManagerFactory(String, java.util.Map) * @see javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map) */ - Map getJpaPropertyMap(); + Map getJpaPropertyMap(); /** * Return the vendor-specific JpaDialect implementation for this diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/AbstractJpaVendorAdapter.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/AbstractJpaVendorAdapter.java index 63e4c36b11f..400d9d5ffcb 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/AbstractJpaVendorAdapter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/AbstractJpaVendorAdapter.java @@ -17,7 +17,6 @@ package org.springframework.orm.jpa.vendor; import java.util.Map; - import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -115,7 +114,7 @@ public abstract class AbstractJpaVendorAdapter implements JpaVendorAdapter { return null; } - public Map getJpaPropertyMap() { + public Map getJpaPropertyMap() { return null; } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java index 8807c162f9c..43a6684449f 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java @@ -16,10 +16,9 @@ package org.springframework.orm.jpa.vendor; +import java.util.HashMap; import java.util.Map; -import java.util.Properties; import java.util.logging.Level; - import javax.persistence.EntityManager; import javax.persistence.spi.PersistenceProvider; @@ -62,27 +61,27 @@ public class EclipseLinkJpaVendorAdapter extends AbstractJpaVendorAdapter { } @Override - public Map getJpaPropertyMap() { - Properties jpaProperties = new Properties(); + public Map getJpaPropertyMap() { + Map jpaProperties = new HashMap(); if (getDatabasePlatform() != null) { - jpaProperties.setProperty(PersistenceUnitProperties.TARGET_DATABASE, getDatabasePlatform()); + jpaProperties.put(PersistenceUnitProperties.TARGET_DATABASE, getDatabasePlatform()); } else if (getDatabase() != null) { String targetDatabase = determineTargetDatabaseName(getDatabase()); if (targetDatabase != null) { - jpaProperties.setProperty(PersistenceUnitProperties.TARGET_DATABASE, targetDatabase); + jpaProperties.put(PersistenceUnitProperties.TARGET_DATABASE, targetDatabase); } } if (isGenerateDdl()) { - jpaProperties.setProperty(PersistenceUnitProperties.DDL_GENERATION, + jpaProperties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY); - jpaProperties.setProperty(PersistenceUnitProperties.DDL_GENERATION_MODE, + jpaProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, PersistenceUnitProperties.DDL_DATABASE_GENERATION); } if (isShowSql()) { - jpaProperties.setProperty(PersistenceUnitProperties.LOGGING_LEVEL, Level.FINE.toString()); + jpaProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, Level.FINE.toString()); } return jpaProperties; diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java index 8d7353ca0f6..4ab6dfe6995 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java @@ -18,6 +18,7 @@ package org.springframework.orm.jpa.vendor; import java.util.Map; import java.util.Properties; +import java.util.HashMap; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; @@ -69,24 +70,24 @@ public class HibernateJpaVendorAdapter extends AbstractJpaVendorAdapter { } @Override - public Map getJpaPropertyMap() { - Properties jpaProperties = new Properties(); + public Map getJpaPropertyMap() { + Map jpaProperties = new HashMap(); if (getDatabasePlatform() != null) { - jpaProperties.setProperty(Environment.DIALECT, getDatabasePlatform()); + jpaProperties.put(Environment.DIALECT, getDatabasePlatform()); } else if (getDatabase() != null) { Class databaseDialectClass = determineDatabaseDialectClass(getDatabase()); if (databaseDialectClass != null) { - jpaProperties.setProperty(Environment.DIALECT, databaseDialectClass.getName()); + jpaProperties.put(Environment.DIALECT, databaseDialectClass.getName()); } } if (isGenerateDdl()) { - jpaProperties.setProperty(Environment.HBM2DDL_AUTO, "update"); + jpaProperties.put(Environment.HBM2DDL_AUTO, "update"); } if (isShowSql()) { - jpaProperties.setProperty(Environment.SHOW_SQL, "true"); + jpaProperties.put(Environment.SHOW_SQL, "true"); } return jpaProperties; diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/OpenJpaVendorAdapter.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/OpenJpaVendorAdapter.java index a00f418f5da..7253b75b51b 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/OpenJpaVendorAdapter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/OpenJpaVendorAdapter.java @@ -16,9 +16,8 @@ package org.springframework.orm.jpa.vendor; +import java.util.HashMap; import java.util.Map; -import java.util.Properties; - import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; @@ -59,26 +58,25 @@ public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter { } @Override - public Map getJpaPropertyMap() { - Properties jpaProperties = new Properties(); + public Map getJpaPropertyMap() { + Map jpaProperties = new HashMap(); if (getDatabasePlatform() != null) { - jpaProperties.setProperty("openjpa.jdbc.DBDictionary", getDatabasePlatform()); + jpaProperties.put("openjpa.jdbc.DBDictionary", getDatabasePlatform()); } else if (getDatabase() != null) { String databaseDictonary = determineDatabaseDictionary(getDatabase()); if (databaseDictonary != null) { - jpaProperties.setProperty("openjpa.jdbc.DBDictionary", databaseDictonary); + jpaProperties.put("openjpa.jdbc.DBDictionary", databaseDictonary); } } if (isGenerateDdl()) { - jpaProperties.setProperty("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); + jpaProperties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); } - if (isShowSql()) { // Taken from the OpenJPA 0.9.6 docs ("Standard OpenJPA Log Configuration + All SQL Statements") - jpaProperties.setProperty("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"); + jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"); } return jpaProperties; diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/TopLinkJpaVendorAdapter.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/TopLinkJpaVendorAdapter.java index 13e6fde12b8..d865f89d3ab 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/TopLinkJpaVendorAdapter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/TopLinkJpaVendorAdapter.java @@ -18,6 +18,7 @@ package org.springframework.orm.jpa.vendor; import java.util.Map; import java.util.Properties; +import java.util.HashMap; import java.util.logging.Level; import javax.persistence.EntityManager; @@ -59,27 +60,27 @@ public class TopLinkJpaVendorAdapter extends AbstractJpaVendorAdapter { } @Override - public Map getJpaPropertyMap() { - Properties jpaProperties = new Properties(); + public Map getJpaPropertyMap() { + Map jpaProperties = new HashMap(); if (getDatabasePlatform() != null) { - jpaProperties.setProperty(TopLinkProperties.TARGET_DATABASE, getDatabasePlatform()); + jpaProperties.put(TopLinkProperties.TARGET_DATABASE, getDatabasePlatform()); } else if (getDatabase() != null) { String targetDatabase = determineTargetDatabaseName(getDatabase()); if (targetDatabase != null) { - jpaProperties.setProperty(TopLinkProperties.TARGET_DATABASE, targetDatabase); + jpaProperties.put(TopLinkProperties.TARGET_DATABASE, targetDatabase); } } if (isGenerateDdl()) { - jpaProperties.setProperty(EntityManagerFactoryProvider.DDL_GENERATION, + jpaProperties.put(EntityManagerFactoryProvider.DDL_GENERATION, EntityManagerFactoryProvider.CREATE_ONLY); - jpaProperties.setProperty(EntityManagerFactoryProvider.DDL_GENERATION_MODE, + jpaProperties.put(EntityManagerFactoryProvider.DDL_GENERATION_MODE, EntityManagerFactoryProvider.DDL_DATABASE_GENERATION); } if (isShowSql()) { - jpaProperties.setProperty(TopLinkProperties.LOGGING_LEVEL, Level.FINE.toString()); + jpaProperties.put(TopLinkProperties.LOGGING_LEVEL, Level.FINE.toString()); } return jpaProperties; diff --git a/org.springframework.test/src/main/java/org/springframework/mock/jndi/SimpleNamingContext.java b/org.springframework.test/src/main/java/org/springframework/mock/jndi/SimpleNamingContext.java index 75347b38f0b..b6489e42029 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/jndi/SimpleNamingContext.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/jndi/SimpleNamingContext.java @@ -20,7 +20,6 @@ import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; - import javax.naming.Binding; import javax.naming.Context; import javax.naming.Name; @@ -57,9 +56,9 @@ public class SimpleNamingContext implements Context { private final String root; - private final Hashtable boundObjects; + private final Hashtable boundObjects; - private final Hashtable environment = new Hashtable(); + private final Hashtable environment = new Hashtable(); /** @@ -74,32 +73,32 @@ public class SimpleNamingContext implements Context { */ public SimpleNamingContext(String root) { this.root = root; - this.boundObjects = new Hashtable(); + this.boundObjects = new Hashtable(); } /** * Create a new naming context with the given naming root, * the given name/object map, and the JNDI environment entries. */ - public SimpleNamingContext(String root, Hashtable boundObjects, Hashtable environment) { + public SimpleNamingContext(String root, Hashtable boundObjects, Hashtable env) { this.root = root; this.boundObjects = boundObjects; - if (environment != null) { - this.environment.putAll(environment); + if (env != null) { + this.environment.putAll(env); } } // Actual implementations of Context methods follow - public NamingEnumeration list(String root) throws NamingException { + public NamingEnumeration list(String root) throws NamingException { if (logger.isDebugEnabled()) { logger.debug("Listing name/class pairs under [" + root + "]"); } return new NameClassPairEnumeration(this, root); } - public NamingEnumeration listBindings(String root) throws NamingException { + public NamingEnumeration listBindings(String root) throws NamingException { if (logger.isDebugEnabled()) { logger.debug("Listing bindings under [" + root + "]"); } @@ -125,8 +124,7 @@ public class SimpleNamingContext implements Context { if (!name.endsWith("/")) { name = name + "/"; } - for (Iterator it = this.boundObjects.keySet().iterator(); it.hasNext();) { - String boundName = (String) it.next(); + for (String boundName : this.boundObjects.keySet()) { if (boundName.startsWith(name)) { return new SimpleNamingContext(name, this.boundObjects, this.environment); } @@ -191,7 +189,7 @@ public class SimpleNamingContext implements Context { return prefix + name; } - public Hashtable getEnvironment() { + public Hashtable getEnvironment() { return this.environment; } @@ -209,11 +207,11 @@ public class SimpleNamingContext implements Context { // Unsupported methods follow: no support for javax.naming.Name - public NamingEnumeration list(Name name) throws NamingException { + public NamingEnumeration list(Name name) throws NamingException { throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); } - public NamingEnumeration listBindings(Name name) throws NamingException { + public NamingEnumeration listBindings(Name name) throws NamingException { throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); } @@ -266,19 +264,17 @@ public class SimpleNamingContext implements Context { } - private static abstract class AbstractNamingEnumeration implements NamingEnumeration { + private static abstract class AbstractNamingEnumeration implements NamingEnumeration { - private Iterator iterator; + private Iterator iterator; private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException { if (!"".equals(proot) && !proot.endsWith("/")) { proot = proot + "/"; } String root = context.root + proot; - Map contents = new HashMap(); - Iterator it = context.boundObjects.keySet().iterator(); - while (it.hasNext()) { - String boundName = (String) it.next(); + Map contents = new HashMap(); + for (String boundName : context.boundObjects.keySet()) { if (boundName.startsWith(root)) { int startIndex = root.length(); int endIndex = boundName.indexOf('/', startIndex); @@ -300,13 +296,13 @@ public class SimpleNamingContext implements Context { this.iterator = contents.values().iterator(); } - protected abstract Object createObject(String strippedName, Object obj); + protected abstract T createObject(String strippedName, Object obj); public boolean hasMore() { return this.iterator.hasNext(); } - public Object next() { + public T next() { return this.iterator.next(); } @@ -314,7 +310,7 @@ public class SimpleNamingContext implements Context { return this.iterator.hasNext(); } - public Object nextElement() { + public T nextElement() { return this.iterator.next(); } @@ -323,25 +319,25 @@ public class SimpleNamingContext implements Context { } - private static class NameClassPairEnumeration extends AbstractNamingEnumeration { + private static class NameClassPairEnumeration extends AbstractNamingEnumeration { private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException { super(context, root); } - protected Object createObject(String strippedName, Object obj) { + protected NameClassPair createObject(String strippedName, Object obj) { return new NameClassPair(strippedName, obj.getClass().getName()); } } - private static class BindingEnumeration extends AbstractNamingEnumeration { + private static class BindingEnumeration extends AbstractNamingEnumeration { private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException { super(context, root); } - protected Object createObject(String strippedName, Object obj) { + protected Binding createObject(String strippedName, Object obj) { return new Binding(strippedName, obj); } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/HeaderValueHolder.java b/org.springframework.test/src/main/java/org/springframework/mock/web/HeaderValueHolder.java index 89dba8837a9..2ce5d10ece1 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/HeaderValueHolder.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/HeaderValueHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.mock.web; import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -35,7 +34,7 @@ import org.springframework.util.CollectionUtils; */ class HeaderValueHolder { - private final List values = new LinkedList(); + private final List values = new LinkedList(); public void setValue(Object value) { @@ -47,7 +46,7 @@ class HeaderValueHolder { this.values.add(value); } - public void addValues(Collection values) { + public void addValues(Collection values) { this.values.addAll(values); } @@ -55,7 +54,7 @@ class HeaderValueHolder { CollectionUtils.mergeArrayIntoCollection(values, this.values); } - public List getValues() { + public List getValues() { return Collections.unmodifiableList(this.values); } @@ -71,12 +70,11 @@ class HeaderValueHolder { * @return the corresponding HeaderValueHolder, * or null if none found */ - public static HeaderValueHolder getByName(Map headers, String name) { + public static HeaderValueHolder getByName(Map headers, String name) { Assert.notNull(name, "Header name must not be null"); - for (Iterator it = headers.keySet().iterator(); it.hasNext();) { - String headerName = (String) it.next(); + for (String headerName : headers.keySet()) { if (headerName.equalsIgnoreCase(name)) { - return (HeaderValueHolder) headers.get(headerName); + return headers.get(headerName); } } return null; diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockFilterConfig.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockFilterConfig.java index dd77753dd39..69d50dacadf 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockFilterConfig.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockFilterConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,9 @@ package org.springframework.mock.web; import java.util.Enumeration; import java.util.Properties; +import java.util.Collections; +import java.util.Map; +import java.util.LinkedHashMap; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; @@ -41,7 +44,7 @@ public class MockFilterConfig implements FilterConfig { private final String filterName; - private final Properties initParameters = new Properties(); + private final Map initParameters = new LinkedHashMap(); /** @@ -88,16 +91,16 @@ public class MockFilterConfig implements FilterConfig { public void addInitParameter(String name, String value) { Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.setProperty(name, value); + this.initParameters.put(name, value); } public String getInitParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.getProperty(name); + return this.initParameters.get(name); } - public Enumeration getInitParameterNames() { - return this.initParameters.keys(); + public Enumeration getInitParameterNames() { + return Collections.enumeration(this.initParameters.keySet()); } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java index 527f05c150a..4964e5fbd0c 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java @@ -29,13 +29,12 @@ import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; -import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.Vector; - import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; @@ -121,7 +120,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private String remoteHost = DEFAULT_REMOTE_HOST; /** List of locales in descending order */ - private final Vector locales = new Vector(); + private final List locales = new LinkedList(); private boolean secure = false; @@ -147,7 +146,7 @@ public class MockHttpServletRequest implements HttpServletRequest { /** * The key is the lowercase header name; the value is a {@link HeaderValueHolder} object. */ - private final Hashtable headers = new Hashtable(); + private final Map headers = new Hashtable(); private String method; @@ -159,7 +158,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private String remoteUser; - private final Set userRoles = new HashSet(); + private final Set userRoles = new HashSet(); private Principal userPrincipal; @@ -284,7 +283,7 @@ public class MockHttpServletRequest implements HttpServletRequest { return this.attributes.get(name); } - public Enumeration getAttributeNames() { + public Enumeration getAttributeNames() { checkActive(); return this.attributes.keys(); } @@ -439,7 +438,7 @@ public class MockHttpServletRequest implements HttpServletRequest { return (arr != null && arr.length > 0 ? arr[0] : null); } - public Enumeration getParameterNames() { + public Enumeration getParameterNames() { return Collections.enumeration(this.parameters.keySet()); } @@ -545,11 +544,11 @@ public class MockHttpServletRequest implements HttpServletRequest { } public Locale getLocale() { - return (Locale) this.locales.get(0); + return this.locales.get(0); } - public Enumeration getLocales() { - return this.locales.elements(); + public Enumeration getLocales() { + return Collections.enumeration(this.locales); } public void setSecure(boolean secure) { @@ -679,13 +678,13 @@ public class MockHttpServletRequest implements HttpServletRequest { return (header != null ? header.getValue().toString() : null); } - public Enumeration getHeaders(String name) { + public Enumeration getHeaders(String name) { HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return Collections.enumeration(header != null ? header.getValues() : Collections.EMPTY_LIST); + return Collections.enumeration(header != null ? header.getValues() : Collections.emptyList()); } - public Enumeration getHeaderNames() { - return this.headers.keys(); + public Enumeration getHeaderNames() { + return Collections.enumeration(this.headers.keySet()); } public int getIntHeader(String name) { diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index 986864076d6..ca98ae991f8 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -88,12 +88,12 @@ public class MockHttpServletResponse implements HttpServletResponse { // HttpServletResponse properties //--------------------------------------------------------------------- - private final List cookies = new ArrayList(); + private final List cookies = new ArrayList(); /** * The key is the lowercase header name; the value is a {@link HeaderValueHolder} object. */ - private final Map headers = new HashMap(); + private final Map headers = new HashMap(); private int status = HttpServletResponse.SC_OK; @@ -266,13 +266,12 @@ public class MockHttpServletResponse implements HttpServletResponse { } public Cookie[] getCookies() { - return (Cookie[]) this.cookies.toArray(new Cookie[this.cookies.size()]); + return this.cookies.toArray(new Cookie[this.cookies.size()]); } public Cookie getCookie(String name) { Assert.notNull(name, "Cookie name must not be null"); - for (Iterator it = this.cookies.iterator(); it.hasNext();) { - Cookie cookie = (Cookie) it.next(); + for (Cookie cookie : this.cookies) { if (name.equals(cookie.getName())) { return cookie; } @@ -288,7 +287,7 @@ public class MockHttpServletResponse implements HttpServletResponse { * Return the names of all specified headers as a Set of Strings. * @return the Set of header name Strings, or an empty Set if none */ - public Set getHeaderNames() { + public Set getHeaderNames() { return this.headers.keySet(); } @@ -310,7 +309,7 @@ public class MockHttpServletResponse implements HttpServletResponse { */ public List getHeaders(String name) { HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return (header != null ? header.getValues() : Collections.EMPTY_LIST); + return (header != null ? header.getValues() : Collections.emptyList()); } /** @@ -372,11 +371,11 @@ public class MockHttpServletResponse implements HttpServletResponse { } public void setDateHeader(String name, long value) { - setHeaderValue(name, new Long(value)); + setHeaderValue(name, value); } public void addDateHeader(String name, long value) { - addHeaderValue(name, new Long(value)); + addHeaderValue(name, value); } public void setHeader(String name, String value) { @@ -388,11 +387,11 @@ public class MockHttpServletResponse implements HttpServletResponse { } public void setIntHeader(String name, int value) { - setHeaderValue(name, new Integer(value)); + setHeaderValue(name, value); } public void addIntHeader(String name, int value) { - addHeaderValue(name, new Integer(value)); + addHeaderValue(name, value); } private void setHeaderValue(String name, Object value) { diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpSession.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpSession.java index 0698a7b156b..8bfbf96a96e 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpSession.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ package org.springframework.mock.web; import java.io.Serializable; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; -import java.util.Hashtable; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.Map; - import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; @@ -60,7 +60,7 @@ public class MockHttpSession implements HttpSession { private final ServletContext servletContext; - private final Hashtable attributes = new Hashtable(); + private final Map attributes = new LinkedHashMap(); private boolean invalid = false; @@ -136,12 +136,12 @@ public class MockHttpSession implements HttpSession { return getAttribute(name); } - public Enumeration getAttributeNames() { - return this.attributes.keys(); + public Enumeration getAttributeNames() { + return Collections.enumeration(this.attributes.keySet()); } public String[] getValueNames() { - return (String[]) this.attributes.keySet().toArray(new String[this.attributes.size()]); + return this.attributes.keySet().toArray(new String[this.attributes.size()]); } public void setAttribute(String name, Object value) { @@ -177,9 +177,9 @@ public class MockHttpSession implements HttpSession { * Clear all of this session's attributes. */ public void clearAttributes() { - for (Iterator it = this.attributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String name = (String) entry.getKey(); + for (Iterator> it = this.attributes.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + String name = entry.getKey(); Object value = entry.getValue(); it.remove(); if (value instanceof HttpSessionBindingListener) { @@ -212,14 +212,14 @@ public class MockHttpSession implements HttpSession { * @return a representation of this session's serialized state */ public Serializable serializeState() { - HashMap state = new HashMap(); - for (Iterator it = this.attributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String name = (String) entry.getKey(); + HashMap state = new HashMap(); + for (Iterator> it = this.attributes.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + String name = entry.getKey(); Object value = entry.getValue(); it.remove(); if (value instanceof Serializable) { - state.put(name, value); + state.put(name, (Serializable) value); } else { // Not serializable... Servlet containers usually automatically @@ -237,9 +237,10 @@ public class MockHttpSession implements HttpSession { * created by {@link #serializeState()}. * @param state a representation of this session's serialized state */ + @SuppressWarnings("unchecked") public void deserializeState(Serializable state) { Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]"); - this.attributes.putAll((Map) state); + this.attributes.putAll((Map) state); } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockMultipartHttpServletRequest.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockMultipartHttpServletRequest.java index 04f3e278b4c..d0eb95c74a5 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockMultipartHttpServletRequest.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockMultipartHttpServletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ import org.springframework.web.multipart.MultipartHttpServletRequest; */ public class MockMultipartHttpServletRequest extends MockHttpServletRequest implements MultipartHttpServletRequest { - private final Map multipartFiles = new LinkedHashMap(4); + private final Map multipartFiles = new LinkedHashMap(); /** @@ -53,15 +53,15 @@ public class MockMultipartHttpServletRequest extends MockHttpServletRequest impl this.multipartFiles.put(file.getName(), file); } - public Iterator getFileNames() { + public Iterator getFileNames() { return getFileMap().keySet().iterator(); } public MultipartFile getFile(String name) { - return (MultipartFile) this.multipartFiles.get(name); + return this.multipartFiles.get(name); } - public Map getFileMap() { + public Map getFileMap() { return Collections.unmodifiableMap(this.multipartFiles); } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockPageContext.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockPageContext.java index 1b70bcf586b..6a75613fe29 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockPageContext.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockPageContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,9 +17,10 @@ package org.springframework.mock.web; import java.io.IOException; +import java.util.Collections; import java.util.Enumeration; -import java.util.Hashtable; - +import java.util.HashMap; +import java.util.Map; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @@ -59,7 +60,7 @@ public class MockPageContext extends PageContext { private final ServletConfig servletConfig; - private final Hashtable attributes = new Hashtable(); + private final Map attributes = new HashMap(); private JspWriter out; @@ -244,11 +245,12 @@ public class MockPageContext extends PageContext { } } - public Enumeration getAttributeNames() { - return this.attributes.keys(); + public Enumeration getAttributeNames() { + return Collections.enumeration(this.attributes.keySet()); } - public Enumeration getAttributeNamesInScope(int scope) { + @SuppressWarnings("unchecked") + public Enumeration getAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return getAttributeNames(); diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletConfig.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletConfig.java index 1647ebff5d4..ca15d76a870 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletConfig.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,10 @@ package org.springframework.mock.web; +import java.util.Collections; import java.util.Enumeration; -import java.util.Properties; - +import java.util.LinkedHashMap; +import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @@ -40,7 +41,7 @@ public class MockServletConfig implements ServletConfig { private final String servletName; - private final Properties initParameters = new Properties(); + private final Map initParameters = new LinkedHashMap(); /** @@ -78,25 +79,25 @@ public class MockServletConfig implements ServletConfig { public String getServletName() { - return servletName; + return this.servletName; } public ServletContext getServletContext() { - return servletContext; + return this.servletContext; } public void addInitParameter(String name, String value) { Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.setProperty(name, value); + this.initParameters.put(name, value); } public String getInitParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.getProperty(name); + return this.initParameters.get(name); } - public Enumeration getInitParameterNames() { - return this.initParameters.keys(); + public Enumeration getInitParameterNames() { + return Collections.enumeration(this.initParameters.keySet()); } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletContext.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletContext.java index 4eebe54bef3..071d89e5f8a 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletContext.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockServletContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,11 @@ import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; -import java.util.Hashtable; +import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; -import java.util.Properties; import java.util.Set; - import javax.activation.FileTypeMap; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; @@ -90,11 +89,11 @@ public class MockServletContext implements ServletContext { private String contextPath = ""; - private final Map contexts = new HashMap(); + private final Map contexts = new HashMap(); - private final Properties initParameters = new Properties(); + private final Map initParameters = new LinkedHashMap(); - private final Hashtable attributes = new Hashtable(); + private final Map attributes = new LinkedHashMap(); private String servletContextName = "MockServletContext"; @@ -174,7 +173,7 @@ public class MockServletContext implements ServletContext { if (this.contextPath.equals(contextPath)) { return this; } - return (ServletContext) this.contexts.get(contextPath); + return this.contexts.get(contextPath); } public int getMajorVersion() { @@ -198,10 +197,10 @@ public class MockServletContext implements ServletContext { if (ObjectUtils.isEmpty(fileList)) { return null; } - Set resourcePaths = new LinkedHashSet(fileList.length); - for (int i = 0; i < fileList.length; i++) { - String resultPath = actualPath + fileList[i]; - if (resource.createRelative(fileList[i]).getFile().isDirectory()) { + Set resourcePaths = new LinkedHashSet(fileList.length); + for (String fileEntry : fileList) { + String resultPath = actualPath + fileEntry; + if (resource.createRelative(fileEntry).getFile().isDirectory()) { resultPath += "/"; } resourcePaths.add(resultPath); @@ -260,12 +259,12 @@ public class MockServletContext implements ServletContext { return null; } - public Enumeration getServlets() { - return Collections.enumeration(Collections.EMPTY_SET); + public Enumeration getServlets() { + return Collections.enumeration(new HashSet()); } - public Enumeration getServletNames() { - return Collections.enumeration(Collections.EMPTY_SET); + public Enumeration getServletNames() { + return Collections.enumeration(new HashSet()); } public void log(String message) { @@ -297,16 +296,16 @@ public class MockServletContext implements ServletContext { public String getInitParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.getProperty(name); + return this.initParameters.get(name); } public void addInitParameter(String name, String value) { Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.setProperty(name, value); + this.initParameters.put(name, value); } - public Enumeration getInitParameterNames() { - return this.initParameters.keys(); + public Enumeration getInitParameterNames() { + return Collections.enumeration(this.initParameters.keySet()); } public Object getAttribute(String name) { @@ -314,8 +313,8 @@ public class MockServletContext implements ServletContext { return this.attributes.get(name); } - public Enumeration getAttributeNames() { - return this.attributes.keys(); + public Enumeration getAttributeNames() { + return Collections.enumeration(this.attributes.keySet()); } public void setAttribute(String name, Object value) { diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java index 58c65df5219..e608e81c49f 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,8 @@ package org.springframework.mock.web.portlet; import java.io.IOException; import java.util.Collections; import java.util.Iterator; -import java.util.Map; import java.util.LinkedHashMap; - +import java.util.Map; import javax.portlet.ActionResponse; import javax.portlet.PortalContext; import javax.portlet.PortletMode; @@ -29,7 +28,6 @@ import javax.portlet.PortletModeException; import javax.portlet.WindowState; import javax.portlet.WindowStateException; -import org.springframework.core.CollectionFactory; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; @@ -48,7 +46,7 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes private String redirectedUrl; - private final Map renderParameters = new LinkedHashMap(16); + private final Map renderParameters = new LinkedHashMap(); /** @@ -120,7 +118,7 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes Map.Entry entry = (Map.Entry) it.next(); Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String"); Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]"); - this.renderParameters.put(entry.getKey(), entry.getValue()); + this.renderParameters.put((String) entry.getKey(), (String[]) entry.getValue()); } } @@ -133,8 +131,9 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes this.renderParameters.put(key, new String[] {value}); } - public String getRenderParameter(String name) { - String[] arr = (String[]) this.renderParameters.get(name); + public String getRenderParameter(String key) { + Assert.notNull(key, "Parameter key must not be null"); + String[] arr = this.renderParameters.get(key); return (arr != null && arr.length > 0 ? arr[0] : null); } @@ -149,7 +148,7 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes public String[] getRenderParameterValues(String key) { Assert.notNull(key, "Parameter key must not be null"); - return (String[]) this.renderParameters.get(key); + return this.renderParameters.get(key); } public Iterator getRenderParameterNames() { diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java index 7505eafa227..cc2b2277cff 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import org.springframework.web.portlet.multipart.MultipartActionRequest; */ public class MockMultipartActionRequest extends MockActionRequest implements MultipartActionRequest { - private final Map multipartFiles = new LinkedHashMap(4); + private final Map multipartFiles = new LinkedHashMap(); /** @@ -52,15 +52,15 @@ public class MockMultipartActionRequest extends MockActionRequest implements Mul this.multipartFiles.put(file.getName(), file); } - public Iterator getFileNames() { + public Iterator getFileNames() { return getFileMap().keySet().iterator(); } public MultipartFile getFile(String name) { - return (MultipartFile) this.multipartFiles.get(name); + return this.multipartFiles.get(name); } - public Map getFileMap() { + public Map getFileMap() { return Collections.unmodifiableMap(this.multipartFiles); } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java index ccf411a78e7..1a81847f978 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,12 @@ package org.springframework.mock.web.portlet; +import java.util.ArrayList; +import java.util.Collections; import java.util.Enumeration; +import java.util.HashMap; import java.util.List; -import java.util.Properties; -import java.util.Vector; - +import java.util.Map; import javax.portlet.PortalContext; import javax.portlet.PortletMode; import javax.portlet.WindowState; @@ -34,11 +35,11 @@ import javax.portlet.WindowState; */ public class MockPortalContext implements PortalContext { - private final Properties properties = new Properties(); + private final Map properties = new HashMap(); - private final Vector portletModes; + private final List portletModes; - private final Vector windowStates; + private final List windowStates; /** @@ -49,12 +50,12 @@ public class MockPortalContext implements PortalContext { * @see javax.portlet.WindowState */ public MockPortalContext() { - this.portletModes = new Vector(3); + this.portletModes = new ArrayList(3); this.portletModes.add(PortletMode.VIEW); this.portletModes.add(PortletMode.EDIT); this.portletModes.add(PortletMode.HELP); - this.windowStates = new Vector(3); + this.windowStates = new ArrayList(3); this.windowStates.add(WindowState.NORMAL); this.windowStates.add(WindowState.MAXIMIZED); this.windowStates.add(WindowState.MINIMIZED); @@ -67,9 +68,9 @@ public class MockPortalContext implements PortalContext { * @see javax.portlet.PortletMode * @see javax.portlet.WindowState */ - public MockPortalContext(List supportedPortletModes, List supportedWindowStates) { - this.portletModes = new Vector(supportedPortletModes); - this.windowStates = new Vector(supportedWindowStates); + public MockPortalContext(List supportedPortletModes, List supportedWindowStates) { + this.portletModes = new ArrayList(supportedPortletModes); + this.windowStates = new ArrayList(supportedWindowStates); } @@ -77,20 +78,24 @@ public class MockPortalContext implements PortalContext { return "MockPortal/1.0"; } + public void setProperty(String name, String value) { + this.properties.put(name, value); + } + public String getProperty(String name) { - return this.properties.getProperty(name); + return this.properties.get(name); } - public Enumeration getPropertyNames() { - return this.properties.propertyNames(); + public Enumeration getPropertyNames() { + return Collections.enumeration(this.properties.keySet()); } - public Enumeration getSupportedPortletModes() { - return this.portletModes.elements(); + public Enumeration getSupportedPortletModes() { + return Collections.enumeration(this.portletModes); } - public Enumeration getSupportedWindowStates() { - return this.windowStates.elements(); + public Enumeration getSupportedWindowStates() { + return Collections.enumeration(this.windowStates); } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java index a5c0e0452f7..249429e1a13 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,11 @@ package org.springframework.mock.web.portlet; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; +import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; - +import java.util.LinkedHashMap; +import java.util.Collections; import javax.portlet.PortletConfig; import javax.portlet.PortletContext; @@ -40,9 +42,9 @@ public class MockPortletConfig implements PortletConfig { private final String portletName; - private final HashMap resourceBundles = new HashMap(); + private final Map resourceBundles = new HashMap(); - private final Properties initParameters = new Properties(); + private final Map initParameters = new LinkedHashMap(); /** @@ -94,21 +96,21 @@ public class MockPortletConfig implements PortletConfig { public ResourceBundle getResourceBundle(Locale locale) { Assert.notNull(locale, "Locale must not be null"); - return (ResourceBundle) this.resourceBundles.get(locale); + return this.resourceBundles.get(locale); } public void addInitParameter(String name, String value) { Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.setProperty(name, value); + this.initParameters.put(name, value); } public String getInitParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.getProperty(name); + return this.initParameters.get(name); } - public Enumeration getInitParameterNames() { - return this.initParameters.keys(); + public Enumeration getInitParameterNames() { + return Collections.enumeration(this.initParameters.keySet()); } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java index b823ad1d0e3..336b21e95b4 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,12 @@ import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; +import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; -import java.util.Hashtable; -import java.util.Properties; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Set; - import javax.portlet.PortletContext; import javax.portlet.PortletRequestDispatcher; @@ -57,9 +57,9 @@ public class MockPortletContext implements PortletContext { private final ResourceLoader resourceLoader; - private final Hashtable attributes = new Hashtable(); + private final Map attributes = new LinkedHashMap(); - private final Properties initParameters = new Properties(); + private final Map initParameters = new LinkedHashMap(); private String portletContextName = "MockPortletContext"; @@ -171,15 +171,15 @@ public class MockPortletContext implements PortletContext { } } - public Set getResourcePaths(String path) { + public Set getResourcePaths(String path) { Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); try { File file = resource.getFile(); String[] fileList = file.list(); String prefix = (path.endsWith("/") ? path : path + "/"); - Set resourcePaths = new HashSet(fileList.length); - for (int i = 0; i < fileList.length; i++) { - resourcePaths.add(prefix + fileList[i]); + Set resourcePaths = new HashSet(fileList.length); + for (String fileEntry : fileList) { + resourcePaths.add(prefix + fileEntry); } return resourcePaths; } @@ -204,8 +204,8 @@ public class MockPortletContext implements PortletContext { return this.attributes.get(name); } - public Enumeration getAttributeNames() { - return this.attributes.keys(); + public Enumeration getAttributeNames() { + return Collections.enumeration(this.attributes.keySet()); } public void setAttribute(String name, Object value) { @@ -223,16 +223,16 @@ public class MockPortletContext implements PortletContext { public void addInitParameter(String name, String value) { Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.setProperty(name, value); + this.initParameters.put(name, value); } public String getInitParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.getProperty(name); + return this.initParameters.get(name); } - public Enumeration getInitParameterNames() { - return this.initParameters.keys(); + public Enumeration getInitParameterNames() { + return Collections.enumeration(this.initParameters.keySet()); } public void log(String message) { diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java index 4d3c7a2d927..122ead007e6 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,9 @@ public class MockPortletPreferences implements PortletPreferences { private PreferencesValidator preferencesValidator; - private final Map preferences = new LinkedHashMap(16); + private final Map preferences = new LinkedHashMap(); - private final Set readOnly = new HashSet(); + private final Set readOnly = new HashSet(); public void setReadOnly(String key, boolean readOnly) { @@ -64,13 +64,13 @@ public class MockPortletPreferences implements PortletPreferences { public String getValue(String key, String def) { Assert.notNull(key, "Key must not be null"); - String[] values = (String[]) this.preferences.get(key); + String[] values = this.preferences.get(key); return (values != null && values.length > 0 ? values[0] : def); } public String[] getValues(String key, String[] def) { Assert.notNull(key, "Key must not be null"); - String[] values = (String[]) this.preferences.get(key); + String[] values = this.preferences.get(key); return (values != null && values.length > 0 ? values : def); } @@ -86,11 +86,11 @@ public class MockPortletPreferences implements PortletPreferences { this.preferences.put(key, values); } - public Enumeration getNames() { + public Enumeration getNames() { return Collections.enumeration(this.preferences.keySet()); } - public Map getMap() { + public Map getMap() { return Collections.unmodifiableMap(this.preferences); } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java index 8c62d7b0afa..84c8af733f3 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,16 +20,12 @@ import java.security.Principal; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.Vector; - import javax.portlet.PortalContext; import javax.portlet.PortletContext; import javax.portlet.PortletMode; @@ -64,11 +60,11 @@ public class MockPortletRequest implements PortletRequest { private PortletPreferences portletPreferences = new MockPortletPreferences(); - private final Map properties = new LinkedHashMap(16); + private final Map> properties = new LinkedHashMap>(); - private final Hashtable attributes = new Hashtable(); + private final Map attributes = new LinkedHashMap(); - private final Map parameters = new LinkedHashMap(16); + private final Map parameters = new LinkedHashMap(); private String authType = null; @@ -78,15 +74,15 @@ public class MockPortletRequest implements PortletRequest { private Principal userPrincipal = null; - private final Set userRoles = new HashSet(); + private final Set userRoles = new HashSet(); private boolean secure = false; private boolean requestedSessionIdValid = true; - private final Vector responseContentTypes = new Vector(); + private final List responseContentTypes = new LinkedList(); - private final Vector locales = new Vector(); + private final List locales = new LinkedList(); private String scheme = "http"; @@ -227,7 +223,7 @@ public class MockPortletRequest implements PortletRequest { */ public void setProperty(String key, String value) { Assert.notNull(key, "Property key must not be null"); - List list = new LinkedList(); + List list = new LinkedList(); list.add(value); this.properties.put(key, list); } @@ -239,12 +235,12 @@ public class MockPortletRequest implements PortletRequest { */ public void addProperty(String key, String value) { Assert.notNull(key, "Property key must not be null"); - List oldList = (List) this.properties.get(key); + List oldList = this.properties.get(key); if (oldList != null) { oldList.add(value); } else { - List list = new LinkedList(); + List list = new LinkedList(); list.add(value); this.properties.put(key, list); } @@ -252,16 +248,16 @@ public class MockPortletRequest implements PortletRequest { public String getProperty(String key) { Assert.notNull(key, "Property key must not be null"); - List list = (List) this.properties.get(key); + List list = this.properties.get(key); return (list != null && list.size() > 0 ? (String) list.get(0) : null); } - public Enumeration getProperties(String key) { + public Enumeration getProperties(String key) { Assert.notNull(key, "property key must not be null"); - return Collections.enumeration((List) this.properties.get(key)); + return Collections.enumeration(this.properties.get(key)); } - public Enumeration getPropertyNames() { + public Enumeration getPropertyNames() { return Collections.enumeration(this.properties.keySet()); } @@ -314,20 +310,15 @@ public class MockPortletRequest implements PortletRequest { return this.attributes.get(name); } - public Enumeration getAttributeNames() { + public Enumeration getAttributeNames() { checkActive(); - return this.attributes.keys(); + return Collections.enumeration(this.attributes.keySet()); } - public void setParameters(Map parameters) { + public void setParameters(Map parameters) { Assert.notNull(parameters, "Parameters Map must not be null"); this.parameters.clear(); - for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String"); - Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]"); - this.parameters.put(entry.getKey(), entry.getValue()); - } + this.parameters.putAll(parameters); } public void setParameter(String key, String value) { @@ -347,7 +338,7 @@ public class MockPortletRequest implements PortletRequest { } public void addParameter(String name, String[] values) { - String[] oldArr = (String[]) this.parameters.get(name); + String[] oldArr = this.parameters.get(name); if (oldArr != null) { String[] newArr = new String[oldArr.length + values.length]; System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); @@ -360,16 +351,16 @@ public class MockPortletRequest implements PortletRequest { } public String getParameter(String name) { - String[] arr = (String[]) this.parameters.get(name); + String[] arr = this.parameters.get(name); return (arr != null && arr.length > 0 ? arr[0] : null); } - public Enumeration getParameterNames() { + public Enumeration getParameterNames() { return Collections.enumeration(this.parameters.keySet()); } public String[] getParameterValues(String name) { - return (String[]) this.parameters.get(name); + return this.parameters.get(name); } public Map getParameterMap() { @@ -421,11 +412,11 @@ public class MockPortletRequest implements PortletRequest { } public String getResponseContentType() { - return (String) this.responseContentTypes.get(0); + return this.responseContentTypes.get(0); } - public Enumeration getResponseContentTypes() { - return this.responseContentTypes.elements(); + public Enumeration getResponseContentTypes() { + return Collections.enumeration(this.responseContentTypes); } public void addLocale(Locale locale) { @@ -437,11 +428,11 @@ public class MockPortletRequest implements PortletRequest { } public Locale getLocale() { - return (Locale) this.locales.get(0); + return this.locales.get(0); } - public Enumeration getLocales() { - return this.locales.elements(); + public Enumeration getLocales() { + return Collections.enumeration(this.locales); } public void setScheme(String scheme) { @@ -449,7 +440,7 @@ public class MockPortletRequest implements PortletRequest { } public String getScheme() { - return scheme; + return this.scheme; } public void setServerName(String serverName) { @@ -457,7 +448,7 @@ public class MockPortletRequest implements PortletRequest { } public String getServerName() { - return serverName; + return this.serverName; } public void setServerPort(int serverPort) { @@ -465,7 +456,7 @@ public class MockPortletRequest implements PortletRequest { } public int getServerPort() { - return serverPort; + return this.serverPort; } } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java index d047c05af21..2c94ddda4a5 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ public class MockPortletResponse implements PortletResponse { private final PortalContext portalContext; - private final Map properties = new LinkedHashMap(16); + private final Map properties = new LinkedHashMap(); /** @@ -61,7 +61,7 @@ public class MockPortletResponse implements PortletResponse { * defining the supported PortletModes and WindowStates. */ public PortalContext getPortalContext() { - return portalContext; + return this.portalContext; } @@ -71,7 +71,7 @@ public class MockPortletResponse implements PortletResponse { public void addProperty(String key, String value) { Assert.notNull(key, "Property key must not be null"); - String[] oldArr = (String[]) this.properties.get(key); + String[] oldArr = this.properties.get(key); if (oldArr != null) { String[] newArr = new String[oldArr.length + 1]; System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); @@ -94,13 +94,13 @@ public class MockPortletResponse implements PortletResponse { public String getProperty(String key) { Assert.notNull(key, "Property key must not be null"); - String[] arr = (String[]) this.properties.get(key); + String[] arr = this.properties.get(key); return (arr != null && arr.length > 0 ? arr[0] : null); } public String[] getProperties(String key) { Assert.notNull(key, "Property key must not be null"); - return (String[]) this.properties.get(key); + return this.properties.get(key); } public String encodeURL(String path) { diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java index 6888af250f5..ab27defe000 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,10 @@ package org.springframework.mock.web.portlet; +import java.util.Collections; import java.util.Enumeration; -import java.util.Hashtable; - +import java.util.HashMap; +import java.util.Map; import javax.portlet.PortletContext; import javax.portlet.PortletSession; @@ -44,9 +45,9 @@ public class MockPortletSession implements PortletSession { private final PortletContext portletContext; - private final Hashtable portletAttributes = new Hashtable(); + private final Map portletAttributes = new HashMap(); - private final Hashtable applicationAttributes = new Hashtable(); + private final Map applicationAttributes = new HashMap(); private boolean invalid = false; @@ -84,16 +85,16 @@ public class MockPortletSession implements PortletSession { return null; } - public Enumeration getAttributeNames() { - return this.portletAttributes.keys(); + public Enumeration getAttributeNames() { + return Collections.enumeration(this.portletAttributes.keySet()); } - public Enumeration getAttributeNames(int scope) { + public Enumeration getAttributeNames(int scope) { if (scope == PortletSession.PORTLET_SCOPE) { - return this.portletAttributes.keys(); + return Collections.enumeration(this.portletAttributes.keySet()); } else if (scope == PortletSession.APPLICATION_SCOPE) { - return this.applicationAttributes.keys(); + return Collections.enumeration(this.applicationAttributes.keySet()); } return null; } diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java index 2e60b5fbea8..5230fd5aa4c 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ public class MockPortletURL implements PortletURL { private PortletMode portletMode; - private final Map parameters = new LinkedHashMap(16); + private final Map parameters = new LinkedHashMap(); private boolean secure = false; @@ -116,24 +116,24 @@ public class MockPortletURL implements PortletURL { Map.Entry entry = (Map.Entry) it.next(); Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String"); Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]"); - this.parameters.put(entry.getKey(), entry.getValue()); + this.parameters.put((String) entry.getKey(), (String[]) entry.getValue()); } } - public Set getParameterNames() { + public Set getParameterNames() { return this.parameters.keySet(); } public String getParameter(String name) { - String[] arr = (String[]) this.parameters.get(name); + String[] arr = this.parameters.get(name); return (arr != null && arr.length > 0 ? arr[0] : null); } public String[] getParameterValues(String name) { - return (String[]) this.parameters.get(name); + return this.parameters.get(name); } - public Map getParameterMap() { + public Map getParameterMap() { return Collections.unmodifiableMap(this.parameters); } @@ -142,33 +142,13 @@ public class MockPortletURL implements PortletURL { } public boolean isSecure() { - return secure; - } - - public String toString() { - StringBuffer query = new StringBuffer(); - query.append(encodeParameter("urlType", this.urlType)); - if (this.windowState != null) { - query.append(";" + encodeParameter("windowState", this.windowState.toString())); - } - if (this.portletMode != null) { - query.append(";" + encodeParameter("portletMode", this.portletMode.toString())); - } - for (Iterator it = this.parameters.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String name = (String) entry.getKey(); - String[] values = (String[]) entry.getValue(); - query.append(";" + encodeParameter("param_" + name, values)); - } - return (this.secure ? "https:" : "http:") + - "//localhost/mockportlet?" + query.toString(); + return this.secure; } private String encodeParameter(String name, String value) { try { - return URLEncoder.encode(name, ENCODING) + "=" + - URLEncoder.encode(value, ENCODING); + return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING); } catch (UnsupportedEncodingException ex) { return null; @@ -177,17 +157,34 @@ public class MockPortletURL implements PortletURL { private String encodeParameter(String name, String[] values) { try { - StringBuffer buf = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0, n = values.length; i < n; i++) { - buf.append((i > 0 ? ";" : "") + + sb.append((i > 0 ? ";" : "") + URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(values[i], ENCODING)); } - return buf.toString(); + return sb.toString(); } catch (UnsupportedEncodingException ex) { return null; } } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(encodeParameter("urlType", this.urlType)); + if (this.windowState != null) { + sb.append(";").append(encodeParameter("windowState", this.windowState.toString())); + } + if (this.portletMode != null) { + sb.append(";").append(encodeParameter("portletMode", this.portletMode.toString())); + } + for (Map.Entry entry : this.parameters.entrySet()) { + sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue())); + } + return (this.secure ? "https:" : "http:") + + "//localhost/mockportlet?" + sb.toString(); + } + } diff --git a/org.springframework.test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java b/org.springframework.test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java index e4dd510458e..90d70e1cb6a 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java +++ b/org.springframework.test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java @@ -59,7 +59,10 @@ import org.springframework.util.Assert; * @see #contextKey * @see #getContext * @see #getConfigLocations + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class AbstractDependencyInjectionSpringContextTests extends AbstractSingleSpringContextTests { /** diff --git a/org.springframework.test/src/main/java/org/springframework/test/AbstractSingleSpringContextTests.java b/org.springframework.test/src/main/java/org/springframework/test/AbstractSingleSpringContextTests.java index 7ed2ff71b06..b05f927d4aa 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/AbstractSingleSpringContextTests.java +++ b/org.springframework.test/src/main/java/org/springframework/test/AbstractSingleSpringContextTests.java @@ -65,7 +65,10 @@ import org.springframework.util.StringUtils; * @see #contextKey() * @see #loadContext(Object) * @see #getApplicationContext() + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class AbstractSingleSpringContextTests extends AbstractSpringContextTests { /** Application context this test will run against */ diff --git a/org.springframework.test/src/main/java/org/springframework/test/AbstractSpringContextTests.java b/org.springframework.test/src/main/java/org/springframework/test/AbstractSpringContextTests.java index 37982f95a2e..0b4ae975ee1 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/AbstractSpringContextTests.java +++ b/org.springframework.test/src/main/java/org/springframework/test/AbstractSpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,10 @@ import org.springframework.util.StringUtils; * @see AbstractDependencyInjectionSpringContextTests * @see AbstractTransactionalSpringContextTests * @see AbstractTransactionalDataSourceSpringContextTests + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class AbstractSpringContextTests extends ConditionalTestCase { /** @@ -64,7 +67,8 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { * contexts. This needs to be static, as JUnit tests are destroyed and * recreated between running individual test methods. */ - private static Map contextKeyToContextMap = new HashMap(); + private static Map contextKeyToContextMap = + new HashMap(); /** @@ -80,12 +84,11 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { super(name); } + /** * Explicitly add an ApplicationContext instance under a given key. - *

- * This is not meant to be used by subclasses. It is rather exposed for + *

This is not meant to be used by subclasses. It is rather exposed for * special test suite environments. - * * @param key the context key * @param context the ApplicationContext instance */ @@ -96,7 +99,6 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { /** * Return whether there is a cached context for the given key. - * * @param key the context key */ protected final boolean hasCachedContext(Object key) { @@ -104,38 +106,29 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { } /** - *

- * Determines if the supplied context key is empty. - *

- *

- * By default, null values, empty strings, and zero-length + * Determine if the supplied context key is empty. + *

By default, null values, empty strings, and zero-length * arrays are considered empty. - *

- * * @param key the context key to check - * @return true if the supplied context key is empty. + * @return true if the supplied context key is empty */ protected boolean isContextKeyEmpty(Object key) { - return (key == null) || ((key instanceof String) && !StringUtils.hasText((String) key)) - || ((key instanceof Object[]) && ObjectUtils.isEmpty((Object[]) key)); + return (key == null) || ((key instanceof String) && !StringUtils.hasText((String) key)) || + ((key instanceof Object[]) && ObjectUtils.isEmpty((Object[]) key)); } /** * Obtain an ApplicationContext for the given key, potentially cached. - * * @param key the context key; may be null. - * @return the corresponding ApplicationContext instance (potentially - * cached), or null if the provided key - * is empty. + * @return the corresponding ApplicationContext instance (potentially cached), + * or null if the provided key is empty */ protected final ConfigurableApplicationContext getContext(Object key) throws Exception { - if (isContextKeyEmpty(key)) { return null; } - String keyString = contextKeyString(key); - ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) contextKeyToContextMap.get(keyString); + ConfigurableApplicationContext ctx = contextKeyToContextMap.get(keyString); if (ctx == null) { ctx = loadContext(key); ctx.registerShutdownHook(); @@ -147,13 +140,12 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { /** * Mark the context with the given key as dirty. This will cause the cached * context to be reloaded before the next test case is executed. - *

- * Call this method only if you change the state of a singleton bean, + *

Call this method only if you change the state of a singleton bean, * potentially affecting future tests. */ protected final void setDirty(Object contextKey) { String keyString = contextKeyString(contextKey); - ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) contextKeyToContextMap.remove(keyString); + ConfigurableApplicationContext ctx = contextKeyToContextMap.remove(keyString); if (ctx != null) { ctx.close(); } @@ -162,7 +154,6 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { /** * Subclasses can override this to return a String representation of their * context key for use in caching and logging. - * * @param contextKey the context key */ protected String contextKeyString(Object contextKey) { @@ -171,9 +162,7 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { /** * Load a new ApplicationContext for the given key. - *

- * To be implemented by subclasses. - * + *

To be implemented by subclasses. * @param key the context key * @return the corresponding ApplicationContext instance (new) */ diff --git a/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java b/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java index f74753df41c..c40137b1035 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java +++ b/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java @@ -45,7 +45,10 @@ import org.springframework.util.StringUtils; * @since 1.1.1 * @see #setDataSource(javax.sql.DataSource) * @see #getJdbcTemplate() + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class AbstractTransactionalDataSourceSpringContextTests extends AbstractTransactionalSpringContextTests { diff --git a/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalSpringContextTests.java b/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalSpringContextTests.java index db302973e28..7e32eabd33e 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalSpringContextTests.java +++ b/org.springframework.test/src/main/java/org/springframework/test/AbstractTransactionalSpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,46 +26,46 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; * Convenient base class for JUnit 3.8 based tests that should occur in a * transaction, but normally will roll the transaction back on the completion of * each test. - *

- * This is useful in a range of circumstances, allowing the following benefits: + * + *

This is useful in a range of circumstances, allowing the following benefits: *

    *
  • Ability to delete or insert any data in the database, without affecting * other tests *
  • Providing a transactional context for any code requiring a transaction *
  • Ability to write anything to the database without any need to clean up. *
- *

- * This class is typically very fast, compared to traditional setup/teardown + * + *

This class is typically very fast, compared to traditional setup/teardown * scripts. - *

- * If data should be left in the database, call the {@link #setComplete()} + * + *

If data should be left in the database, call the {@link #setComplete()} * method in each test. The {@link #setDefaultRollback "defaultRollback"} * property, which defaults to "true", determines whether transactions will * complete by default. - *

- * It is even possible to end the transaction early; for example, to verify lazy + * + *

It is even possible to end the transaction early; for example, to verify lazy * loading behavior of an O/R mapping tool. (This is a valuable away to avoid * unexpected errors when testing a web UI, for example.) Simply call the * {@link #endTransaction()} method. Execution will then occur without a * transactional context. - *

- * The {@link #startNewTransaction()} method may be called after a call to + * + *

The {@link #startNewTransaction()} method may be called after a call to * {@link #endTransaction()} if you wish to create a new transaction, quite * independent of the old transaction. The new transaction's default fate will * be to roll back, unless {@link #setComplete()} is called again during the * scope of the new transaction. Any number of transactions may be created and * ended in this way. The final transaction will automatically be rolled back * when the test case is torn down. - *

- * Transactional behavior requires a single bean in the context implementing the + * + *

Transactional behavior requires a single bean in the context implementing the * {@link PlatformTransactionManager} interface. This will be set by the * superclass's Dependency Injection mechanism. If using the superclass's Field * Injection mechanism, the implementation should be named "transactionManager". * This mechanism allows the use of the * {@link AbstractDependencyInjectionSpringContextTests} superclass even when * there is more than one transaction manager in the context. - *

- * This base class can also be used without transaction management, if no + * + *

This base class can also be used without transaction management, if no * PlatformTransactionManager bean is found in the context provided. Be * careful about using this mode, as it allows the potential to permanently * modify data. This mode is available only if dependency checking is turned off @@ -77,49 +77,51 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; * @author Juergen Hoeller * @author Sam Brannen * @since 1.1.1 + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class AbstractTransactionalSpringContextTests extends AbstractDependencyInjectionSpringContextTests { /** The transaction manager to use */ - protected PlatformTransactionManager transactionManager; + protected PlatformTransactionManager transactionManager; /** Should we roll back by default? */ - private boolean defaultRollback = true; + private boolean defaultRollback = true; /** Should we commit the current transaction? */ - private boolean complete = false; + private boolean complete = false; /** Number of transactions started */ - private int transactionsStarted = 0; + private int transactionsStarted = 0; /** * Transaction definition used by this test class: by default, a plain * DefaultTransactionDefinition. Subclasses can change this to cause * different behavior. */ - protected TransactionDefinition transactionDefinition = new DefaultTransactionDefinition(); + protected TransactionDefinition transactionDefinition= new DefaultTransactionDefinition(); /** * TransactionStatus for this test. Typical subclasses won't need to use it. */ - protected TransactionStatus transactionStatus; + protected TransactionStatus transactionStatus; + /** * Default constructor for AbstractTransactionalSpringContextTests. */ public AbstractTransactionalSpringContextTests() { - } /** - * Constructor for AbstractTransactionalSpringContextTests with a JUnit - * name. + * Constructor for AbstractTransactionalSpringContextTests with a JUnit name. */ - public AbstractTransactionalSpringContextTests(final String name) { - + public AbstractTransactionalSpringContextTests(String name) { super(name); } + /** * Specify the transaction manager to use. No transaction management will be * available if this is not set. Populated through dependency injection by @@ -128,44 +130,32 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe * This mode works only if dependency checking is turned off in the * {@link AbstractDependencyInjectionSpringContextTests} superclass. */ - public void setTransactionManager(final PlatformTransactionManager transactionManager) { - + public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } - /** - * Get the default rollback flag for this test. - * - * @see #setDefaultRollback(boolean) - * @return The default rollback flag. - */ - protected boolean isDefaultRollback() { - - return this.defaultRollback; - } - /** * Subclasses can set this value in their constructor to change the default, * which is always to roll the transaction back. */ public void setDefaultRollback(final boolean defaultRollback) { - this.defaultRollback = defaultRollback; } + /** + * Get the default rollback flag for this test. + * @see #setDefaultRollback(boolean) + * @return The default rollback flag. + */ + protected boolean isDefaultRollback() { + return this.defaultRollback; + } /** - *

* Determines whether or not to rollback transactions for the current test. - *

- *

- * The default implementation delegates to {@link #isDefaultRollback()}. + *

The default implementation delegates to {@link #isDefaultRollback()}. * Subclasses can override as necessary. - *

- * - * @return The rollback flag for the current test. */ protected boolean isRollback() { - return isDefaultRollback(); } @@ -174,7 +164,6 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe * transactional execution. */ protected void preventTransaction() { - this.transactionDefinition = null; } @@ -182,28 +171,23 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe * Call this method in an overridden {@link #runBare()} method to override * the transaction attributes that will be used, so that {@link #setUp()} * and {@link #tearDown()} behavior is modified. - * * @param customDefinition the custom transaction definition */ - protected void setTransactionDefinition(final TransactionDefinition customDefinition) { - + protected void setTransactionDefinition(TransactionDefinition customDefinition) { this.transactionDefinition = customDefinition; } /** * This implementation creates a transaction before test execution. - *

- * Override {@link #onSetUpBeforeTransaction()} and/or + *

Override {@link #onSetUpBeforeTransaction()} and/or * {@link #onSetUpInTransaction()} to add custom set-up behavior for * transactional execution. Alternatively, override this method for general * set-up behavior, calling super.onSetUp() as part of your * method implementation. - * * @throws Exception simply let any exception propagate * @see #onTearDown() */ protected void onSetUp() throws Exception { - this.complete = !this.isRollback(); if (this.transactionManager == null) { @@ -231,52 +215,42 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe * this class. Only invoked if there is a transaction: that is, if * {@link #preventTransaction()} has not been invoked in an overridden * {@link #runTest()} method. - * * @throws Exception simply let any exception propagate */ protected void onSetUpBeforeTransaction() throws Exception { - } /** * Subclasses can override this method to perform any setup operations, such * as populating a database table, within the transaction created by * this class. - *

- * NB: Not called if there is no transaction management, due to no + *

NB: Not called if there is no transaction management, due to no * transaction manager being provided in the context. - *

- * If any {@link Throwable} is thrown, the transaction that has been started + *

If any {@link Throwable} is thrown, the transaction that has been started * prior to the execution of this method will be * {@link #endTransaction() ended} (or rather an attempt will be made to * {@link #endTransaction() end it gracefully}); The offending * {@link Throwable} will then be rethrown. - * * @throws Exception simply let any exception propagate */ protected void onSetUpInTransaction() throws Exception { - } /** * This implementation ends the transaction after test execution. - *

- * Override {@link #onTearDownInTransaction()} and/or + *

Override {@link #onTearDownInTransaction()} and/or * {@link #onTearDownAfterTransaction()} to add custom tear-down behavior * for transactional execution. Alternatively, override this method for * general tear-down behavior, calling super.onTearDown() as * part of your method implementation. - *

- * Note that {@link #onTearDownInTransaction()} will only be called if a + *

Note that {@link #onTearDownInTransaction()} will only be called if a * transaction is still active at the time of the test shutdown. In * particular, it will not be called if the transaction has been * completed with an explicit {@link #endTransaction()} call before. - * * @throws Exception simply let any exception propagate * @see #onSetUp() */ protected void onTearDown() throws Exception { - // Call onTearDownInTransaction and end transaction if the transaction // is still active. if (this.transactionStatus != null && !this.transactionStatus.isCompleted()) { @@ -287,6 +261,7 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe endTransaction(); } } + // Call onTearDownAfterTransaction if there was at least one // transaction, even if it has been completed early through an // endTransaction() call. @@ -300,35 +275,28 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe * transaction is still active at this point, so any changes made in * the transaction will still be visible. However, there is no need to clean * up the database, as a rollback will follow automatically. - *

- * NB: Not called if there is no actual transaction, for example due + *

NB: Not called if there is no actual transaction, for example due * to no transaction manager being provided in the application context. - * * @throws Exception simply let any exception propagate */ protected void onTearDownInTransaction() throws Exception { - } /** * Subclasses can override this method to perform cleanup after a * transaction here. At this point, the transaction is not active anymore. - * * @throws Exception simply let any exception propagate */ protected void onTearDownAfterTransaction() throws Exception { - } /** * Cause the transaction to commit for this test method, even if the test * method is configured to {@link #isRollback() rollback}. - * * @throws IllegalStateException if the operation cannot be set to complete - * as no transaction manager was provided + * as no transaction manager was provided */ protected void setComplete() { - if (this.transactionManager == null) { throw new IllegalStateException("No transaction manager set"); } @@ -338,17 +306,13 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe /** * Immediately force a commit or rollback of the transaction, according to * the complete and {@link #isRollback() rollback} flags. - *

- * Can be used to explicitly let the transaction end early, for example to + *

Can be used to explicitly let the transaction end early, for example to * check whether lazy associations of persistent objects work outside of a * transaction (that is, have been initialized properly). - * * @see #setComplete() */ protected void endTransaction() { - final boolean commit = this.complete || !isRollback(); - if (this.transactionStatus != null) { try { if (commit) { @@ -371,11 +335,9 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe * {@link #endTransaction()} has been called. {@link #setComplete()} can be * used again in the new transaction. The fate of the new transaction, by * default, will be the usual rollback. - * * @throws TransactionException if starting the transaction failed */ protected void startNewTransaction() throws TransactionException { - if (this.transactionStatus != null) { throw new IllegalStateException("Cannot start new transaction without ending existing transaction: " + "Invoke endTransaction() before startNewTransaction()"); diff --git a/org.springframework.test/src/main/java/org/springframework/test/AssertThrows.java b/org.springframework.test/src/main/java/org/springframework/test/AssertThrows.java index 45b9185bdbc..4be59459f39 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/AssertThrows.java +++ b/org.springframework.test/src/main/java/org/springframework/test/AssertThrows.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.test; -import junit.framework.Assert; -import junit.framework.AssertionFailedError; - /** * Simple method object encapsulation of the 'test-for-Exception' scenario (for JUnit). * @@ -77,11 +74,10 @@ import junit.framework.AssertionFailedError; * } * } * + * Intended for use with JUnit 4 and TestNG (as of Spring 3.0). * You might want to compare this class with the * {@link junit.extensions.ExceptionTestCase} class. * - *

Note: This class requires JDK 1.4 or higher. - * * @author Rick Evans * @author Juergen Hoeller * @since 2.0 @@ -193,7 +189,7 @@ public abstract class AssertThrows { * @see #getFailureMessage() */ protected void doFail() { - Assert.fail(createMessageForNoExceptionThrown()); + throw new AssertionError(createMessageForNoExceptionThrown()); } /** @@ -203,7 +199,7 @@ public abstract class AssertThrows { * @see #getFailureMessage() */ protected String createMessageForNoExceptionThrown() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("Should have thrown a [").append(this.getExpectedException()).append("]"); if (getFailureMessage() != null) { sb.append(": ").append(getFailureMessage()); @@ -223,8 +219,8 @@ public abstract class AssertThrows { */ protected void checkExceptionExpectations(Exception actualException) { if (!getExpectedException().isAssignableFrom(actualException.getClass())) { - AssertionFailedError error = - new AssertionFailedError(createMessageForWrongThrownExceptionType(actualException)); + AssertionError error = + new AssertionError(createMessageForWrongThrownExceptionType(actualException)); error.initCause(actualException); throw error; } @@ -237,7 +233,7 @@ public abstract class AssertThrows { * @return the message for the given exception */ protected String createMessageForWrongThrownExceptionType(Exception actualException) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("Was expecting a [").append(getExpectedException().getName()); sb.append("] to be thrown, but instead a [").append(actualException.getClass().getName()); sb.append("] was thrown."); diff --git a/org.springframework.test/src/main/java/org/springframework/test/ConditionalTestCase.java b/org.springframework.test/src/main/java/org/springframework/test/ConditionalTestCase.java index 6ea36a8626a..e44c9ac7963 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/ConditionalTestCase.java +++ b/org.springframework.test/src/main/java/org/springframework/test/ConditionalTestCase.java @@ -32,7 +32,10 @@ import org.apache.commons.logging.LogFactory; * @author Rod Johnson * @since 2.0 * @see #isDisabledInThisEnvironment + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class ConditionalTestCase extends TestCase { private static int disabledTestCount; @@ -78,7 +81,6 @@ public abstract class ConditionalTestCase extends TestCase { /** * Should this test run? - * * @param testMethodName name of the test method * @return whether the test should execute in the current environment */ @@ -88,7 +90,6 @@ public abstract class ConditionalTestCase extends TestCase { /** * Record a disabled test. - * * @return the current disabled test count */ protected int recordDisabled() { diff --git a/org.springframework.test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java b/org.springframework.test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java index 457ea21b58d..a3b9784c231 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java +++ b/org.springframework.test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,14 +33,13 @@ public class JdbcTestUtils { /** * Read a script from the LineNumberReaded and build a String containing the lines. - * * @param lineNumberReader the LineNumberReader containing the script to be processed * @return String containing the script lines * @throws IOException */ public static String readScript(LineNumberReader lineNumberReader) throws IOException { String currentStatement = lineNumberReader.readLine(); - StringBuffer scriptBuilder = new StringBuffer(); + StringBuilder scriptBuilder = new StringBuilder(); while (currentStatement != null) { if (StringUtils.hasText(currentStatement)) { if (scriptBuilder.length() > 0) { @@ -55,17 +54,15 @@ public class JdbcTestUtils { /** * Does the provided SQL script contain the specified delimiter? - * * @param script the SQL script * @param delim charecter delimiting each statement - typically a ';' character */ public static boolean containsSqlScriptDelimiters(String script, char delim) { boolean inLiteral = false; char[] content = script.toCharArray(); - for (int i = 0; i < script.length(); i++) { if (content[i] == '\'') { - inLiteral = inLiteral ? false : true; + inLiteral = !inLiteral; } if (content[i] == delim && !inLiteral) { return true; @@ -81,19 +78,18 @@ public class JdbcTestUtils { * @param delim charecter delimiting each statement - typically a ';' character * @param statements the List that will contain the individual statements */ - public static void splitSqlScript(String script, char delim, List statements) { - StringBuffer sb = new StringBuffer(); + public static void splitSqlScript(String script, char delim, List statements) { + StringBuilder sb = new StringBuilder(); boolean inLiteral = false; char[] content = script.toCharArray(); - for (int i = 0; i < script.length(); i++) { if (content[i] == '\'') { - inLiteral = inLiteral ? false : true; + inLiteral = !inLiteral; } if (content[i] == delim && !inLiteral) { if (sb.length() > 0) { statements.add(sb.toString()); - sb = new StringBuffer(); + sb = new StringBuilder(); } } else { diff --git a/org.springframework.test/src/main/java/org/springframework/test/jdbc/SimpleJdbcTestUtils.java b/org.springframework.test/src/main/java/org/springframework/test/jdbc/SimpleJdbcTestUtils.java index 3a3466eb0c3..72b8d822d46 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/jdbc/SimpleJdbcTestUtils.java +++ b/org.springframework.test/src/main/java/org/springframework/test/jdbc/SimpleJdbcTestUtils.java @@ -18,7 +18,6 @@ package org.springframework.test.jdbc; import java.io.IOException; import java.io.LineNumberReader; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -31,7 +30,6 @@ import org.springframework.core.io.support.EncodedResource; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; -import org.springframework.util.StringUtils; /** * A Java-5-based collection of JDBC related utility functions intended to @@ -65,11 +63,11 @@ public abstract class SimpleJdbcTestUtils { */ public static int deleteFromTables(SimpleJdbcTemplate simpleJdbcTemplate, String... tableNames) { int totalRowCount = 0; - for (int i = 0; i < tableNames.length; i++) { - int rowCount = simpleJdbcTemplate.update("DELETE FROM " + tableNames[i]); + for (String tableName : tableNames) { + int rowCount = simpleJdbcTemplate.update("DELETE FROM " + tableName); totalRowCount += rowCount; if (logger.isInfoEnabled()) { - logger.info("Deleted " + rowCount + " rows from table " + tableNames[i]); + logger.info("Deleted " + rowCount + " rows from table " + tableName); } } return totalRowCount; @@ -145,8 +143,7 @@ public abstract class SimpleJdbcTestUtils { delimiter = '\n'; } JdbcTestUtils.splitSqlScript(script, delimiter, statements); - for (Iterator itr = statements.iterator(); itr.hasNext();) { - String statement = itr.next(); + for (String statement : statements) { try { int rowsAffected = simpleJdbcTemplate.update(statement); if (logger.isDebugEnabled()) { diff --git a/org.springframework.test/src/main/java/org/springframework/test/web/AbstractModelAndViewTests.java b/org.springframework.test/src/main/java/org/springframework/test/web/AbstractModelAndViewTests.java index 25805627137..c7d0b753aa9 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/web/AbstractModelAndViewTests.java +++ b/org.springframework.test/src/main/java/org/springframework/test/web/AbstractModelAndViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,16 +26,12 @@ import junit.framework.TestCase; import org.springframework.web.servlet.ModelAndView; /** - *

* Convenient JUnit 3.8 base class for tests dealing with Spring Web MVC * {@link org.springframework.web.servlet.ModelAndView ModelAndView} objects. - *

- *

- * All assert*() methods throw {@link AssertionFailedError}s. - *

- *

- * Consider the use of {@link ModelAndViewAssert} with JUnit 4 and TestNG. - *

+ * + *

All assert*() methods throw {@link AssertionFailedError}s. + * + *

Consider the use of {@link ModelAndViewAssert} with JUnit 4 and TestNG. * * @author Alef Arendsen * @author Bram Smeets @@ -43,14 +39,16 @@ import org.springframework.web.servlet.ModelAndView; * @since 2.0 * @see org.springframework.web.servlet.ModelAndView * @see ModelAndViewAssert + * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework + * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ +@Deprecated public abstract class AbstractModelAndViewTests extends TestCase { /** * Checks whether the model value under the given modelName * exists and checks it type, based on the expectedType. If * the model entry exists and the type matches, the model value is returned. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) @@ -58,7 +56,6 @@ public abstract class AbstractModelAndViewTests extends TestCase { * @return the model value */ protected Object assertAndReturnModelAttributeOfType(ModelAndView mav, Object modelName, Class expectedType) { - try { return ModelAndViewAssert.assertAndReturnModelAttributeOfType(mav, modelName, expectedType); } @@ -69,14 +66,12 @@ public abstract class AbstractModelAndViewTests extends TestCase { /** * Compare each individual entry in a list, without first sorting the lists. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) * @param expectedList the expected list */ protected void assertCompareListModelAttribute(ModelAndView mav, Object modelName, List expectedList) { - try { ModelAndViewAssert.assertCompareListModelAttribute(mav, modelName, expectedList); } @@ -87,13 +82,11 @@ public abstract class AbstractModelAndViewTests extends TestCase { /** * Assert whether or not a model attribute is available. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) */ protected void assertModelAttributeAvailable(ModelAndView mav, Object modelName) { - try { ModelAndViewAssert.assertModelAttributeAvailable(mav, modelName); } @@ -105,14 +98,12 @@ public abstract class AbstractModelAndViewTests extends TestCase { /** * Compare a given expectedValue to the value from the model * bound under the given modelName. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) * @param expectedValue the model value */ protected void assertModelAttributeValue(ModelAndView mav, Object modelName, Object expectedValue) { - try { ModelAndViewAssert.assertModelAttributeValue(mav, modelName, expectedValue); } @@ -124,12 +115,10 @@ public abstract class AbstractModelAndViewTests extends TestCase { /** * Inspect the expectedModel to see if all elements in the * model appear and are equal. - * * @param mav ModelAndView to test against (never null) * @param expectedModel the expected model */ protected void assertModelAttributeValues(ModelAndView mav, Map expectedModel) { - try { ModelAndViewAssert.assertModelAttributeValues(mav, expectedModel); } @@ -141,7 +130,6 @@ public abstract class AbstractModelAndViewTests extends TestCase { /** * Compare each individual entry in a list after having sorted both lists * (optionally using a comparator). - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) @@ -152,7 +140,6 @@ public abstract class AbstractModelAndViewTests extends TestCase { */ protected void assertSortAndCompareListModelAttribute( ModelAndView mav, Object modelName, List expectedList, Comparator comparator) { - try { ModelAndViewAssert.assertSortAndCompareListModelAttribute(mav, modelName, expectedList, comparator); } @@ -164,12 +151,10 @@ public abstract class AbstractModelAndViewTests extends TestCase { /** * Check to see if the view name in the ModelAndView matches the given * expectedName. - * * @param mav ModelAndView to test against (never null) * @param expectedName the name of the model value */ protected void assertViewName(ModelAndView mav, String expectedName) { - try { ModelAndViewAssert.assertViewName(mav, expectedName); } diff --git a/org.springframework.test/src/main/java/org/springframework/test/web/ModelAndViewAssert.java b/org.springframework.test/src/main/java/org/springframework/test/web/ModelAndViewAssert.java index 3a9b547eb6b..b4937604f1e 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/web/ModelAndViewAssert.java +++ b/org.springframework.test/src/main/java/org/springframework/test/web/ModelAndViewAssert.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.test.web; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -27,15 +26,12 @@ import java.util.Set; import org.springframework.web.servlet.ModelAndView; /** - *

* A collection of assertions intended to simplify testing scenarios * dealing with Spring Web MVC * {@link org.springframework.web.servlet.ModelAndView ModelAndView} objects. - * Intended for use with JUnit 4 and TestNG. - *

- *

+ * + *

Intended for use with JUnit 4 and TestNG. * All assert*() methods throw {@link AssertionError}s. - *

* * @author Sam Brannen * @author Alef Arendsen @@ -49,29 +45,28 @@ public abstract class ModelAndViewAssert { * Checks whether the model value under the given modelName * exists and checks it type, based on the expectedType. If * the model entry exists and the type matches, the model value is returned. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) * @param expectedType expected type of the model value * @return the model value */ - public static Object assertAndReturnModelAttributeOfType(ModelAndView mav, Object modelName, Class expectedType) + @SuppressWarnings("unchecked") + public static T assertAndReturnModelAttributeOfType(ModelAndView mav, Object modelName, Class expectedType) throws AssertionError { assertCondition(mav != null, "ModelAndView is null"); assertCondition(mav.getModel() != null, "Model is null"); - final Object obj = mav.getModel().get(modelName); + Object obj = mav.getModel().get(modelName); assertCondition(obj != null, "Model attribute with name '" + modelName + "' is null"); - assertCondition(expectedType.isAssignableFrom(obj.getClass()), "Model attribute is not of expected type '" - + expectedType.getName() + "' but rather of type '" + obj.getClass().getName() + "'"); - return obj; + assertCondition(expectedType.isAssignableFrom(obj.getClass()), "Model attribute is not of expected type '" + + expectedType.getName() + "' but rather of type '" + obj.getClass().getName() + "'"); + return (T) obj; } /** * Compare each individual entry in a list, without first sorting the lists. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) @@ -82,101 +77,92 @@ public abstract class ModelAndViewAssert { assertCondition(mav != null, "ModelAndView is null"); List modelList = (List) assertAndReturnModelAttributeOfType(mav, modelName, List.class); - assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() - + "' while size of expected list is '" + expectedList.size() + "'"); - assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName - + "' is not equal to the expected list."); + assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() + + "' while size of expected list is '" + expectedList.size() + "'"); + assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName + + "' is not equal to the expected list."); } /** * Assert whether or not a model attribute is available. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) */ public static void assertModelAttributeAvailable(ModelAndView mav, Object modelName) throws AssertionError { - assertCondition(mav != null, "ModelAndView is null"); assertCondition(mav.getModel() != null, "Model is null"); - assertCondition(mav.getModel().containsKey(modelName), "Model attribute with name '" + modelName - + "' is not available"); + assertCondition(mav.getModel().containsKey(modelName), "Model attribute with name '" + modelName + + "' is not available"); } /** * Compare a given expectedValue to the value from the model * bound under the given modelName. - * * @param mav ModelAndView to test against (never null) * @param modelName name of the object to add to the model (never * null) * @param expectedValue the model value */ - public static void assertModelAttributeValue(ModelAndView mav, Object modelName, Object expectedValue) - throws AssertionError { - + public static void assertModelAttributeValue(ModelAndView mav, Object modelName, Object expectedValue) { assertCondition(mav != null, "ModelAndView is null"); Object modelValue = assertAndReturnModelAttributeOfType(mav, modelName, Object.class); - assertCondition(modelValue.equals(expectedValue), "Model value with name '" + modelName - + "' is not the same as the expected value which was '" + expectedValue + "'"); + assertCondition(modelValue.equals(expectedValue), "Model value with name '" + modelName + + "' is not the same as the expected value which was '" + expectedValue + "'"); } /** * Inspect the expectedModel to see if all elements in the * model appear and are equal. - * * @param mav ModelAndView to test against (never null) * @param expectedModel the expected model */ - public static void assertModelAttributeValues(ModelAndView mav, Map expectedModel) throws AssertionError { - + public static void assertModelAttributeValues(ModelAndView mav, Map expectedModel) { assertCondition(mav != null, "ModelAndView is null"); assertCondition(mav.getModel() != null, "Model is null"); if (!mav.getModel().keySet().equals(expectedModel.keySet())) { - StringBuffer buf = new StringBuffer("Keyset of expected model does not match.\n"); - appendNonMatchingSetsErrorMessage(expectedModel.keySet(), mav.getModel().keySet(), buf); - fail(buf.toString()); + StringBuilder sb = new StringBuilder("Keyset of expected model does not match.\n"); + appendNonMatchingSetsErrorMessage(expectedModel.keySet(), mav.getModel().keySet(), sb); + fail(sb.toString()); } - StringBuffer buf = new StringBuffer(); - Iterator it = mav.getModel().keySet().iterator(); - while (it.hasNext()) { - Object modelName = it.next(); + StringBuilder sb = new StringBuilder(); + for (String modelName : mav.getModel().keySet()) { Object assertionValue = expectedModel.get(modelName); Object mavValue = mav.getModel().get(modelName); if (!assertionValue.equals(mavValue)) { - buf.append("Value under name '" + modelName + "' differs, should have been '" + assertionValue - + "' but was '" + mavValue + "'\n"); + sb.append("Value under name '").append(modelName).append("' differs, should have been '") + .append(assertionValue).append("' but was '").append(mavValue).append("'\n"); } } - if (buf.length() != 0) { - buf.insert(0, "Values of expected model do not match.\n"); - fail(buf.toString()); + if (sb.length() != 0) { + sb.insert(0, "Values of expected model do not match.\n"); + fail(sb.toString()); } } /** * Compare each individual entry in a list after having sorted both lists * (optionally using a comparator). - * * @param mav ModelAndView to test against (never null) - * @param modelName name of the object to add to the model (never - * null) + * @param modelName name of the object to add to the model + * (never null) * @param expectedList the expected list - * @param comparator the comparator to use (may be null). If - * not specifying the comparator, both lists will be sorted not using + * @param comparator the comparator to use (may be null). + * If not specifying the comparator, both lists will be sorted not using * any comparator. */ + @SuppressWarnings("unchecked") public static void assertSortAndCompareListModelAttribute( - ModelAndView mav, Object modelName, List expectedList, Comparator comparator) throws AssertionError { + ModelAndView mav, Object modelName, List expectedList, Comparator comparator) { assertCondition(mav != null, "ModelAndView is null"); - List modelList = (List) assertAndReturnModelAttributeOfType(mav, modelName, List.class); + List modelList = assertAndReturnModelAttributeOfType(mav, modelName, List.class); - assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() - + "' while size of expected list is '" + expectedList.size() + "'"); + assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() + + "' while size of expected list is '" + expectedList.size() + "'"); if (comparator != null) { Collections.sort(modelList, comparator); @@ -187,34 +173,30 @@ public abstract class ModelAndViewAssert { Collections.sort(expectedList); } - assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName - + "' is not equal to the expected list."); + assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName + + "' is not equal to the expected list."); } /** * Check to see if the view name in the ModelAndView matches the given * expectedName. - * * @param mav ModelAndView to test against (never null) * @param expectedName the name of the model value */ - public static void assertViewName(ModelAndView mav, String expectedName) throws AssertionError { - + public static void assertViewName(ModelAndView mav, String expectedName) { assertCondition(mav != null, "ModelAndView is null"); - assertCondition(expectedName.equals(mav.getViewName()), "View name is not equal to '" + expectedName - + "' but was '" + mav.getViewName() + "'"); + assertCondition(expectedName.equals(mav.getViewName()), "View name is not equal to '" + expectedName + + "' but was '" + mav.getViewName() + "'"); } /** * Fails by throwing an AssertionError with the supplied * message. - * * @param message the exception message to use * @see #assertCondition(boolean,String) */ - private static void fail(String message) throws AssertionError { - + private static void fail(String message) { throw new AssertionError(message); } @@ -222,47 +204,39 @@ public abstract class ModelAndViewAssert { * Assert the provided boolean condition, throwing * AssertionError with the supplied message if * the test result is false. - * * @param condition a boolean expression * @param message the exception message to use if the assertion fails - * @throws AssertionError if condition is false * @see #fail(String) */ - private static void assertCondition(boolean condition, String message) throws AssertionError { - + private static void assertCondition(boolean condition, String message) { if (!condition) { fail(message); } } - private static void appendNonMatchingSetsErrorMessage(Set assertionSet, Set incorrectSet, StringBuffer buf) { - - Set tempSet = new HashSet(); + private static void appendNonMatchingSetsErrorMessage(Set assertionSet, Set incorrectSet, StringBuilder buf) { + Set tempSet = new HashSet(); tempSet.addAll(incorrectSet); tempSet.removeAll(assertionSet); if (tempSet.size() > 0) { buf.append("Set has too many elements:\n"); - Iterator it = tempSet.iterator(); - while (it.hasNext()) { - Object o = it.next(); + for (Object element : tempSet) { buf.append('-'); - buf.append(o.toString()); + buf.append(element); buf.append('\n'); } } - tempSet = new HashSet(); + tempSet = new HashSet(); tempSet.addAll(assertionSet); tempSet.removeAll(incorrectSet); if (tempSet.size() > 0) { buf.append("Set is missing elements:\n"); - Iterator it = tempSet.iterator(); - while (it.hasNext()) { - Object o = it.next(); + for (Object element : tempSet) { buf.append('-'); - buf.append(o.toString()); + buf.append(element); buf.append('\n'); } } diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessorTests.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessorTests.java deleted file mode 100644 index 7a0f7a37fee..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/GenericBeanFactoryAccessorTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.generic; - -import junit.framework.TestCase; -import org.springframework.beans.factory.xml.XmlBeanFactory; -import org.springframework.beans.TestBean; -import org.springframework.core.io.ClassPathResource; -import org.springframework.test.AssertThrows; - -import java.util.Map; - -/** - * @author Rob Harrop - * @see 2.0 - */ -public class GenericBeanFactoryAccessorTests extends TestCase { - - private GenericBeanFactoryAccessor beanFactoryAccessor; - - protected void setUp() throws Exception { - XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("genericBeanFactoryAccessorTests.xml", getClass())); - this.beanFactoryAccessor = new GenericBeanFactoryAccessor(beanFactory); - } - - public void testGetBean() throws Exception { - TestBean testBean = this.beanFactoryAccessor.getBean("testBean"); - assertNotNull("TestBean should not be null", testBean); - } - - public void testGetBeanWithType() throws Exception { - TestBean testBean = this.beanFactoryAccessor.getBean("testBean", TestBean.class); - assertNotNull("TestBean should not be null", testBean); - } - - public void testGetBeanFails() throws Exception { - new AssertThrows(ClassCastException.class) { - public void test() throws Exception { - Integer bean = beanFactoryAccessor.getBean("testBean"); - } - }.runTest(); - } - - public void testGetBeansOfType() throws Exception { - Map beansOfType = this.beanFactoryAccessor.getBeansOfType(TestBean.class); - assertEquals(3, beansOfType.size()); - assertNotNull(beansOfType.get("testBean")); - assertNotNull(beansOfType.get("otherTestBean")); - assertNotNull(beansOfType.get("prototypeTestBean")); - } - - public void testGetBeansOfTypeExtended() throws Exception { - Map beansOfType = this.beanFactoryAccessor.getBeansOfType(TestBean.class, false, false); - assertEquals(2, beansOfType.size()); - assertNotNull(beansOfType.get("testBean")); - assertNotNull(beansOfType.get("otherTestBean")); - } - - public void testGetBeansWithAnnotation() throws Exception { - Map beansWithAnnotation = this.beanFactoryAccessor.getBeansWithAnnotation(MyAnnotation.class); - assertEquals(1, beansWithAnnotation.size()); - assertNotNull(beansWithAnnotation.get("annotatedBean")); - } -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/MyAnnotation.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/MyAnnotation.java deleted file mode 100644 index fb4813f361c..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/MyAnnotation.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.generic; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.annotation.ElementType; - -/** - * @author Rob Harrop - * @since 2.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface MyAnnotation { - -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/SomeAnnotatedBean.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/SomeAnnotatedBean.java deleted file mode 100644 index 2b81ad4faf0..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/SomeAnnotatedBean.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.generic; - -/** - * @author Rob Harrop - * @since 2.0 - */ -@MyAnnotation -public class SomeAnnotatedBean { - -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/genericBeanFactoryAccessorTests.xml b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/genericBeanFactoryAccessorTests.xml deleted file mode 100644 index 9e6934904e4..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/generic/genericBeanFactoryAccessorTests.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/org.springframework.testsuite/src/test/java/org/springframework/context/support/ResourceMapFactoryBeanTests.java b/org.springframework.testsuite/src/test/java/org/springframework/context/support/ResourceMapFactoryBeanTests.java deleted file mode 100644 index d45c2f7084d..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/context/support/ResourceMapFactoryBeanTests.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.springframework.context.support; - -import java.util.Map; -import java.util.Properties; - -import junit.framework.TestCase; - -import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -/** - * @author Juergen Hoeller - * @since 25.04.2004 - */ -public class ResourceMapFactoryBeanTests extends TestCase { - - public void testResourceMapFactoryBeanWithoutContext() { - DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - Properties props = new Properties(); - props.setProperty("test1", "classpath:org/springframework/context/support/contextA.xml"); - props.setProperty("test2", "classpath:org/springframework/context/support/contextB.xml"); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue("properties", props); - RootBeanDefinition bd = new RootBeanDefinition(ResourceMapFactoryBean.class, pvs); - beanFactory.registerBeanDefinition("resourceMap", bd); - Map result = (Map) beanFactory.getBean("resourceMap"); - assertEquals(2, result.size()); - assertTrue(result.get("test1") instanceof ClassPathResource); - assertTrue(((Resource) result.get("test1")).getDescription().indexOf("contextA.xml") != -1); - assertTrue(((Resource) result.get("test2")).getDescription().indexOf("contextB.xml") != -1); - } - - public void testResourceMapFactoryBeanWithContext() { - StaticApplicationContext context = new StaticApplicationContext() { - public Resource getResource(String location) { - return super.getResource("classpath:org/springframework/context/support/context" + location); - } - }; - DefaultListableBeanFactory beanFactory = context.getDefaultListableBeanFactory(); - Properties props = new Properties(); - props.setProperty("test1", "A.xml"); - props.setProperty("test2", "B.xml"); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue("properties", props); - RootBeanDefinition bd = new RootBeanDefinition(ResourceMapFactoryBean.class, pvs); - beanFactory.registerBeanDefinition("resourceMap", bd); - context.refresh(); - Map result = (Map) beanFactory.getBean("resourceMap"); - assertEquals(2, result.size()); - assertTrue(result.get("test1") instanceof ClassPathResource); - assertTrue(((Resource) result.get("test1")).getDescription().indexOf("contextA.xml") != -1); - assertTrue(((Resource) result.get("test2")).getDescription().indexOf("contextB.xml") != -1); - } - - public void testResourceMapFactoryBeanWithResourceBasePath() { - DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - Properties props = new Properties(); - props.setProperty("test1", "A.xml"); - props.setProperty("test2", "B.xml"); - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue("properties", props); - pvs.addPropertyValue("resourceBasePath", "classpath:org/springframework/context/support/context"); - RootBeanDefinition bd = new RootBeanDefinition(ResourceMapFactoryBean.class, pvs); - beanFactory.registerBeanDefinition("resourceMap", bd); - Map result = (Map) beanFactory.getBean("resourceMap"); - assertEquals(2, result.size()); - assertTrue(result.get("test1") instanceof ClassPathResource); - assertTrue(((Resource) result.get("test1")).getDescription().indexOf("contextA.xml") != -1); - assertTrue(((Resource) result.get("test2")).getDescription().indexOf("contextB.xml") != -1); - } - -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/core/BridgeMethodResolverTests.java b/org.springframework.testsuite/src/test/java/org/springframework/core/BridgeMethodResolverTests.java index b3e9152a239..8f1f8b94fad 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/core/BridgeMethodResolverTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/core/BridgeMethodResolverTests.java @@ -20,6 +20,7 @@ import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; +import java.lang.reflect.Type; import java.util.Collection; import java.util.Date; import java.util.HashMap; @@ -106,7 +107,7 @@ public class BridgeMethodResolverTests extends TestCase { } public void testCreateTypeVariableMap() throws Exception { - Map typeVariableMap = GenericTypeResolver.getTypeVariableMap(MyBar.class); + Map typeVariableMap = GenericTypeResolver.getTypeVariableMap(MyBar.class); TypeVariable barT = findTypeVariable(InterBar.class, "T"); assertEquals(String.class, typeVariableMap.get(barT)); diff --git a/org.springframework.testsuite/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java b/org.springframework.testsuite/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java index fb813b49e47..86921c7c57e 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java @@ -19,14 +19,12 @@ package org.springframework.transaction.annotation; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.Map; - import javax.management.MBeanServer; import javax.management.ObjectName; import junit.framework.TestCase; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.factory.generic.GenericBeanFactoryAccessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jmx.export.annotation.ManagedOperation; @@ -54,7 +52,7 @@ public class AnnotationTransactionNamespaceHandlerTests extends TestCase { public void testIsProxy() throws Exception { TransactionalTestBean bean = getTestBean(); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); - Map services = new GenericBeanFactoryAccessor(this.context).getBeansWithAnnotation(Service.class); + Map services = this.context.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); } diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsTests.java index 0cb1857d485..0bd25791d07 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; /** * @author Rob Harrop - * @since 18.11.2004 + * @author Juergen Hoeller */ public abstract class AbstractJasperReportsTests extends TestCase { @@ -71,7 +71,7 @@ public abstract class AbstractJasperReportsTests extends TestCase { } - protected Map getModel() { + protected Map getModel() { Map model = new HashMap(); model.put("ReportTitle", "Dear Lord!"); model.put("dataSource", new JRBeanCollectionDataSource(getData())); @@ -82,7 +82,7 @@ public abstract class AbstractJasperReportsTests extends TestCase { /** * Subclasses can extend the model if they need to. */ - protected void extendModel(Map model) { + protected void extendModel(Map model) { } protected List getData() { diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewTests.java index 66617496e33..2d375002e41 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,19 +19,17 @@ package org.springframework.web.servlet.view.jasperreports; import java.util.HashMap; import java.util.Map; import java.util.Properties; -import java.util.Iterator; - import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JasperPrint; -import net.sf.jasperreports.engine.JRExporterParameter; /** * @author Rob Harrop + * @author Juergen Hoeller */ public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsViewTests { - protected void extendModel(Map model) { + protected void extendModel(Map model) { model.put(getDiscriminatorKey(), "csv"); } @@ -42,7 +40,7 @@ public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsView AbstractJasperReportsView view = getView(UNCOMPILED_REPORT); - Map model = getBaseModel(); + Map model = getBaseModel(); model.put(getDiscriminatorKey(), "html"); view.render(model, request, response); @@ -57,7 +55,7 @@ public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsView AbstractJasperReportsView view = getView(UNCOMPILED_REPORT); - Map model = getBaseModel(); + Map model = getBaseModel(); model.put(getDiscriminatorKey(), "csv"); String headerValue = "inline; filename=foo.txt"; @@ -80,10 +78,10 @@ public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsView JasperReportsMultiFormatView view = (JasperReportsMultiFormatView) getView(UNCOMPILED_REPORT); - Properties mappings = new Properties(); - mappings.put("test", ExporterParameterTestView.class.getName()); + Map mappings = new HashMap(); + mappings.put("test", ExporterParameterTestView.class); - Map exporterParameters = new HashMap(); + Map exporterParameters = new HashMap(); // test view class performs the assertions - robh exporterParameters.put(ExporterParameterTestView.TEST_PARAM, "foo"); @@ -92,7 +90,7 @@ public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsView view.setFormatMappings(mappings); view.initApplicationContext(); - Map model = getBaseModel(); + Map model = getBaseModel(); model.put(getDiscriminatorKey(), "test"); view.render(model, request, response); @@ -110,8 +108,8 @@ public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsView return "text/csv"; } - private Map getBaseModel() { - Map model = new HashMap(); + private Map getBaseModel() { + Map model = new HashMap(); model.put("ReportTitle", "Foo"); model.put("dataSource", getData()); return model; diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewWithCustomMappingsTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewWithCustomMappingsTests.java index e109ceb99ca..1a448e00325 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewWithCustomMappingsTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatViewWithCustomMappingsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,23 @@ package org.springframework.web.servlet.view.jasperreports; +import java.util.HashMap; import java.util.Map; -import java.util.Properties; /** * @author Rob Harrop + * @author Juergen Hoeller */ public class JasperReportsMultiFormatViewWithCustomMappingsTests extends JasperReportsMultiFormatViewTests { protected AbstractJasperReportsView getViewImplementation() { JasperReportsMultiFormatView view = new JasperReportsMultiFormatView(); view.setFormatKey("fmt"); - - Properties props = new Properties(); - props.setProperty("csv", JasperReportsCsvView.class.getName()); - props.setProperty("comma-separated", JasperReportsCsvView.class.getName()); - props.setProperty("html", JasperReportsHtmlView.class.getName()); - - view.setFormatMappings(props); + Map mappings = new HashMap(); + mappings.put("csv", JasperReportsCsvView.class); + mappings.put("comma-separated", JasperReportsCsvView.class); + mappings.put("html", JasperReportsHtmlView.class); + view.setFormatMappings(mappings); return view; } @@ -41,7 +40,7 @@ public class JasperReportsMultiFormatViewWithCustomMappingsTests extends JasperR return "fmt"; } - protected void extendModel(Map model) { + protected void extendModel(Map model) { model.put(getDiscriminatorKey(), "comma-separated"); } diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java index 6d833de3965..809fe1151f5 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java @@ -20,15 +20,12 @@ import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; -import java.util.Properties; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.apache.velocity.Template; import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.app.tools.VelocityFormatter; import org.apache.velocity.context.Context; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; @@ -310,7 +307,6 @@ public class VelocityViewTests extends TestCase { assertTrue(response == expectedResponse); assertEquals("myValue", context.get("myHelper")); - assertTrue(context.get("velocityFormatter") instanceof VelocityFormatter); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("dateTool") instanceof DateTool); @@ -329,10 +325,9 @@ public class VelocityViewTests extends TestCase { vv.setUrl(templateName); vv.setApplicationContext(wac); - Properties toolAttributes = new Properties(); - toolAttributes.setProperty("math", MathTool.class.getName()); + Map toolAttributes = new HashMap(); + toolAttributes.put("math", MathTool.class); vv.setToolAttributes(toolAttributes); - vv.setVelocityFormatterAttribute("velocityFormatter"); vv.setDateToolAttribute("dateTool"); vv.setNumberToolAttribute("numberTool"); vv.setExposeSpringMacroHelpers(false); @@ -383,9 +378,9 @@ public class VelocityViewTests extends TestCase { vv.setUrl(templateName); vv.setApplicationContext(wac); - Properties toolAttributes = new Properties(); - toolAttributes.setProperty("math", MathTool.class.getName()); - toolAttributes.setProperty("link2", LinkTool.class.getName()); + Map toolAttributes = new HashMap(); + toolAttributes.put("math", MathTool.class); + toolAttributes.put("link2", LinkTool.class); vv.setToolAttributes(toolAttributes); vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml"); vv.setExposeSpringMacroHelpers(false); diff --git a/org.springframework.transaction/src/main/java/org/springframework/dao/support/DataAccessUtils.java b/org.springframework.transaction/src/main/java/org/springframework/dao/support/DataAccessUtils.java index a15fd26af28..7f5331819ae 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/dao/support/DataAccessUtils.java +++ b/org.springframework.transaction/src/main/java/org/springframework/dao/support/DataAccessUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public abstract class DataAccessUtils { * @throws IncorrectResultSizeDataAccessException if more than one * element has been found in the given Collection */ - public static Object singleResult(Collection results) throws IncorrectResultSizeDataAccessException { + public static T singleResult(Collection results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { return null; @@ -65,7 +65,7 @@ public abstract class DataAccessUtils { * @throws EmptyResultDataAccessException if no element at all * has been found in the given Collection */ - public static Object requiredSingleResult(Collection results) throws IncorrectResultSizeDataAccessException { + public static T requiredSingleResult(Collection results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { throw new EmptyResultDataAccessException(1); @@ -86,7 +86,7 @@ public abstract class DataAccessUtils { * result object has been found in the given Collection * @see org.springframework.util.CollectionUtils#hasUniqueObject */ - public static Object uniqueResult(Collection results) throws IncorrectResultSizeDataAccessException { + public static T uniqueResult(Collection results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { return null; @@ -108,7 +108,7 @@ public abstract class DataAccessUtils { * has been found in the given Collection * @see org.springframework.util.CollectionUtils#hasUniqueObject */ - public static Object requiredUniqueResult(Collection results) throws IncorrectResultSizeDataAccessException { + public static T requiredUniqueResult(Collection results) throws IncorrectResultSizeDataAccessException { int size = (results != null ? results.size() : 0); if (size == 0) { throw new EmptyResultDataAccessException(1); @@ -133,7 +133,8 @@ public abstract class DataAccessUtils { * @throws TypeMismatchDataAccessException if the unique object does * not match the specified required type */ - public static Object objectResult(Collection results, Class requiredType) + @SuppressWarnings("unchecked") + public static T objectResult(Collection results, Class requiredType) throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException { Object result = requiredUniqueResult(results); @@ -155,7 +156,7 @@ public abstract class DataAccessUtils { "] and could not be converted to required type [" + requiredType.getName() + "]"); } } - return result; + return (T) result; } /** @@ -174,7 +175,7 @@ public abstract class DataAccessUtils { public static int intResult(Collection results) throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException { - return ((Number) objectResult(results, Number.class)).intValue(); + return objectResult(results, Number.class).intValue(); } /** @@ -193,7 +194,7 @@ public abstract class DataAccessUtils { public static long longResult(Collection results) throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException { - return ((Number) objectResult(results, Number.class)).longValue(); + return objectResult(results, Number.class).longValue(); } diff --git a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciOperations.java b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciOperations.java index 55e638d1a0f..5982c036d1b 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciOperations.java +++ b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public interface CciOperations { * @return the result object returned by the action, if any * @throws DataAccessException if there is any problem */ - Object execute(ConnectionCallback action) throws DataAccessException; + T execute(ConnectionCallback action) throws DataAccessException; /** * Execute a request on an EIS with CCI, implemented as callback action @@ -62,7 +62,7 @@ public interface CciOperations { * @return the result object returned by the action, if any * @throws DataAccessException if there is any problem */ - Object execute(InteractionCallback action) throws DataAccessException; + T execute(InteractionCallback action) throws DataAccessException; /** * Execute the specified interaction on an EIS with CCI. @@ -103,7 +103,7 @@ public interface CciOperations { * @return the output data extracted with the RecordExtractor object * @throws DataAccessException if there is any problem */ - Object execute(InteractionSpec spec, Record inputRecord, RecordExtractor outputExtractor) + T execute(InteractionSpec spec, Record inputRecord, RecordExtractor outputExtractor) throws DataAccessException; /** @@ -115,7 +115,7 @@ public interface CciOperations { * @return the output data extracted with the RecordExtractor object * @throws DataAccessException if there is any problem */ - Object execute(InteractionSpec spec, RecordCreator inputCreator, RecordExtractor outputExtractor) + T execute(InteractionSpec spec, RecordCreator inputCreator, RecordExtractor outputExtractor) throws DataAccessException; } diff --git a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciTemplate.java b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciTemplate.java index d04bedb7682..c072dcb9ad0 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciTemplate.java +++ b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/CciTemplate.java @@ -17,7 +17,6 @@ package org.springframework.jca.cci.core; import java.sql.SQLException; - import javax.resource.NotSupportedException; import javax.resource.ResourceException; import javax.resource.cci.Connection; @@ -188,9 +187,8 @@ public class CciTemplate implements CciOperations { } - public Object execute(ConnectionCallback action) throws DataAccessException { + public T execute(ConnectionCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); - Connection con = ConnectionFactoryUtils.getConnection(getConnectionFactory(), getConnectionSpec()); try { return action.doInConnection(con, getConnectionFactory()); @@ -209,13 +207,11 @@ public class CciTemplate implements CciOperations { } } - public Object execute(final InteractionCallback action) throws DataAccessException { + public T execute(final InteractionCallback action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); - - return execute(new ConnectionCallback() { - public Object doInConnection(Connection connection, ConnectionFactory connectionFactory) + return execute(new ConnectionCallback() { + public T doInConnection(Connection connection, ConnectionFactory connectionFactory) throws ResourceException, SQLException, DataAccessException { - Interaction interaction = connection.createInteraction(); try { return action.doInInteraction(interaction, connectionFactory); @@ -228,7 +224,7 @@ public class CciTemplate implements CciOperations { } public Record execute(InteractionSpec spec, Record inputRecord) throws DataAccessException { - return (Record) doExecute(spec, inputRecord, null, null); + return doExecute(spec, inputRecord, null, new SimpleRecordExtractor()); } public void execute(InteractionSpec spec, Record inputRecord, Record outputRecord) throws DataAccessException { @@ -236,16 +232,16 @@ public class CciTemplate implements CciOperations { } public Record execute(InteractionSpec spec, RecordCreator inputCreator) throws DataAccessException { - return (Record) doExecute(spec, createRecord(inputCreator), null, null); + return doExecute(spec, createRecord(inputCreator), null, new SimpleRecordExtractor()); } - public Object execute(InteractionSpec spec, Record inputRecord, RecordExtractor outputExtractor) + public T execute(InteractionSpec spec, Record inputRecord, RecordExtractor outputExtractor) throws DataAccessException { return doExecute(spec, inputRecord, null, outputExtractor); } - public Object execute(InteractionSpec spec, RecordCreator inputCreator, RecordExtractor outputExtractor) + public T execute(InteractionSpec spec, RecordCreator inputCreator, RecordExtractor outputExtractor) throws DataAccessException { return doExecute(spec, createRecord(inputCreator), null, outputExtractor); @@ -262,14 +258,13 @@ public class CciTemplate implements CciOperations { * @return the output data extracted with the RecordExtractor object * @throws DataAccessException if there is any problem */ - protected Object doExecute( + protected T doExecute( final InteractionSpec spec, final Record inputRecord, final Record outputRecord, - final RecordExtractor outputExtractor) throws DataAccessException { + final RecordExtractor outputExtractor) throws DataAccessException { - return execute(new InteractionCallback() { - public Object doInInteraction(Interaction interaction, ConnectionFactory connectionFactory) + return execute(new InteractionCallback() { + public T doInInteraction(Interaction interaction, ConnectionFactory connectionFactory) throws ResourceException, SQLException, DataAccessException { - Record outputRecordToUse = outputRecord; try { if (outputRecord != null || getOutputRecordCreator() != null) { @@ -283,12 +278,7 @@ public class CciTemplate implements CciOperations { else { outputRecordToUse = interaction.execute(spec, inputRecord); } - if (outputExtractor != null) { - return outputExtractor.extractData(outputRecordToUse); - } - else { - return outputRecordToUse; - } + return (outputExtractor != null ? outputExtractor.extractData(outputRecordToUse) : null); } finally { if (outputRecordToUse instanceof ResultSet) { @@ -378,7 +368,7 @@ public class CciTemplate implements CciOperations { */ protected RecordFactory getRecordFactory(ConnectionFactory connectionFactory) throws ResourceException { try { - return getConnectionFactory().getRecordFactory(); + return connectionFactory.getRecordFactory(); } catch (NotSupportedException ex) { return new NotSupportedRecordFactory(); @@ -428,4 +418,12 @@ public class CciTemplate implements CciOperations { } } + + private static class SimpleRecordExtractor implements RecordExtractor { + + public Record extractData(Record record) { + return record; + } + } + } diff --git a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/ConnectionCallback.java b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/ConnectionCallback.java index ad69d7e57a5..f7dd0edae58 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/ConnectionCallback.java +++ b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/ConnectionCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,7 +41,7 @@ import org.springframework.dao.DataAccessException; * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, javax.resource.cci.Record) * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) */ -public interface ConnectionCallback { +public interface ConnectionCallback { /** * Gets called by CciTemplate.execute with an active CCI Connection. @@ -73,7 +73,7 @@ public interface ConnectionCallback { * @see javax.resource.cci.ConnectionFactory#getMetaData() * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) */ - Object doInConnection(Connection connection, ConnectionFactory connectionFactory) + T doInConnection(Connection connection, ConnectionFactory connectionFactory) throws ResourceException, SQLException, DataAccessException; } diff --git a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/InteractionCallback.java b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/InteractionCallback.java index 24cf3558bf8..9de2bfce86e 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/InteractionCallback.java +++ b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/InteractionCallback.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,7 +42,7 @@ import org.springframework.dao.DataAccessException; * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, javax.resource.cci.Record) * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) */ -public interface InteractionCallback { +public interface InteractionCallback { /** * Gets called by CciTemplate.execute with an active CCI Interaction. @@ -74,7 +74,7 @@ public interface InteractionCallback { * @see javax.resource.cci.ConnectionFactory#getMetaData() * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) */ - Object doInInteraction(Interaction interaction, ConnectionFactory connectionFactory) + T doInInteraction(Interaction interaction, ConnectionFactory connectionFactory) throws ResourceException, SQLException, DataAccessException; } diff --git a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/RecordExtractor.java b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/RecordExtractor.java index 325f7c9f9c1..6cdb8753262 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/RecordExtractor.java +++ b/org.springframework.transaction/src/main/java/org/springframework/jca/cci/core/RecordExtractor.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,7 +43,7 @@ import org.springframework.dao.DataAccessException; * @see CciTemplate#execute(javax.resource.cci.InteractionSpec, RecordCreator, RecordExtractor) * @see javax.resource.cci.ResultSet */ -public interface RecordExtractor { +public interface RecordExtractor { /** * Process the data in the given Record, creating a corresponding result object. @@ -58,6 +58,6 @@ public interface RecordExtractor { * @throws DataAccessException in case of custom exceptions * @see javax.resource.cci.ResultSet */ - Object extractData(Record record) throws ResourceException, SQLException, DataAccessException; + T extractData(Record record) throws ResourceException, SQLException, DataAccessException; } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java index d853ec8e366..144fdfef6aa 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java @@ -972,8 +972,8 @@ public class DispatcherPortlet extends FrameworkPortlet { throws Exception { ModelAndView exMv = null; - for (Iterator it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) { - HandlerExceptionResolver resolver = (HandlerExceptionResolver) it.next(); + for (Iterator it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) { + HandlerExceptionResolver resolver = it.next(); exMv = resolver.resolveException(request, response, handler, ex); } if (exMv != null) { diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java index f4bcf3fc59a..26986de6b08 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java @@ -91,7 +91,7 @@ public class ModelAndView { * (Objects). Model entries may not be null, but the * model Map may be null if there is no model data. */ - public ModelAndView(String viewName, Map model) { + public ModelAndView(String viewName, Map model) { this.view = viewName; if (model != null) { getModelMap().addAllAttributes(model); @@ -105,7 +105,7 @@ public class ModelAndView { * (Objects). Model entries may not be null, but the * model Map may be null if there is no model data. */ - public ModelAndView(Object view, Map model) { + public ModelAndView(Object view, Map model) { this.view = view; if (model != null) { getModelMap().addAllAttributes(model); @@ -193,7 +193,7 @@ public class ModelAndView { * Return the model map. May return null. * Called by DispatcherPortlet for evaluation of the model. */ - protected Map getModelInternal() { + protected Map getModelInternal() { return this.model; } @@ -211,7 +211,7 @@ public class ModelAndView { * Return the model map. Never returns null. * To be called by application code for modifying the model. */ - public Map getModel() { + public Map getModel() { return getModelMap(); } @@ -245,7 +245,7 @@ public class ModelAndView { * @see ModelMap#addAllAttributes(Map) * @see #getModelMap() */ - public ModelAndView addAllObjects(Map modelMap) { + public ModelAndView addAllObjects(Map modelMap) { getModelMap().addAllAttributes(modelMap); return this; } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java index 463161a467b..a62ddb12927 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,12 +73,12 @@ public class PortletContextResourcePatternResolver extends PathMatchingResourceP * @see javax.portlet.PortletContext#getResourcePaths */ @Override - protected Set doFindPathMatchingFileResources(Resource rootDirResource, String subPattern) throws IOException { + protected Set doFindPathMatchingFileResources(Resource rootDirResource, String subPattern) throws IOException { if (rootDirResource instanceof PortletContextResource) { PortletContextResource pcResource = (PortletContextResource) rootDirResource; PortletContext pc = pcResource.getPortletContext(); String fullPattern = pcResource.getPath() + subPattern; - Set result = new HashSet(); + Set result = new HashSet(); doRetrieveMatchingPortletContextResources(pc, fullPattern, pcResource.getPath(), result); return result; } @@ -98,11 +98,11 @@ public class PortletContextResourcePatternResolver extends PathMatchingResourceP * @see javax.portlet.PortletContext#getResourcePaths */ protected void doRetrieveMatchingPortletContextResources( - PortletContext portletContext, String fullPattern, String dir, Set result) throws IOException { + PortletContext portletContext, String fullPattern, String dir, Set result) throws IOException { Set candidates = portletContext.getResourcePaths(dir); if (candidates != null) { - boolean dirDepthNotFixed = (fullPattern.indexOf("**") != -1); + boolean dirDepthNotFixed = fullPattern.contains("**"); for (Iterator it = candidates.iterator(); it.hasNext();) { String currPath = (String) it.next(); if (currPath.endsWith("/") && diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java index 3a2dd132aa3..e9479b5ecc9 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java @@ -18,12 +18,10 @@ package org.springframework.web.portlet.handler; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; - import javax.portlet.PortletRequest; import org.springframework.beans.BeansException; @@ -40,11 +38,11 @@ import org.springframework.util.Assert; * @see #getLookupKey(javax.portlet.PortletRequest) * @see #registerHandler(Object, Object) */ -public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapping { +public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapping { private boolean lazyInitHandlers = false; - private final Map handlerMap = new HashMap(); + private final Map handlerMap = new HashMap(); /** @@ -67,18 +65,20 @@ public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapp * @see #getLookupKey */ @Override + @SuppressWarnings("unchecked") protected Object getHandlerInternal(PortletRequest request) throws Exception { - Object lookupKey = getLookupKey(request); + K lookupKey = getLookupKey(request); Object handler = this.handlerMap.get(lookupKey); if (handler != null && logger.isDebugEnabled()) { logger.debug("Key [" + lookupKey + "] -> handler [" + handler + "]"); } if (handler instanceof Map) { - Map predicateMap = (Map) handler; - List predicates = new LinkedList(predicateMap.keySet()); + Map predicateMap = + (Map) handler; + List predicates = + new LinkedList(predicateMap.keySet()); Collections.sort(predicates); - for (Iterator it = predicates.iterator(); it.hasNext();) { - PortletRequestMappingPredicate predicate = (PortletRequestMappingPredicate) it.next(); + for (PortletRequestMappingPredicate predicate : predicates) { if (predicate.match(request)) { return predicateMap.get(predicate); } @@ -94,7 +94,7 @@ public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapp * @return the lookup key (never null) * @throws Exception if key computation failed */ - protected abstract Object getLookupKey(PortletRequest request) throws Exception; + protected abstract K getLookupKey(PortletRequest request) throws Exception; /** @@ -102,10 +102,9 @@ public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapp * @param handlerMap Map with lookup keys as keys and handler beans or bean names as values * @throws BeansException if the handler couldn't be registered */ - protected void registerHandlers(Map handlerMap) throws BeansException { + protected void registerHandlers(Map handlerMap) throws BeansException { Assert.notNull(handlerMap, "Handler Map must not be null"); - for (Iterator it = handlerMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry entry : handlerMap.entrySet()) { registerHandler(entry.getKey(), entry.getValue()); } } @@ -118,7 +117,7 @@ public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapp * @throws BeansException if the handler couldn't be registered * @throws IllegalStateException if there is a conflicting handler registered */ - protected void registerHandler(Object lookupKey, Object handler) throws BeansException, IllegalStateException { + protected void registerHandler(K lookupKey, Object handler) throws BeansException, IllegalStateException { registerHandler(lookupKey, handler, null); } @@ -132,7 +131,8 @@ public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapp * @throws BeansException if the handler couldn't be registered * @throws IllegalStateException if there is a conflicting handler registered */ - protected void registerHandler(Object lookupKey, Object handler, PortletRequestMappingPredicate predicate) + @SuppressWarnings("unchecked") + protected void registerHandler(K lookupKey, Object handler, PortletRequestMappingPredicate predicate) throws BeansException, IllegalStateException { Assert.notNull(lookupKey, "Lookup key must not be null"); @@ -158,9 +158,10 @@ public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapp else { if (predicate != null) { // Add the handler to the predicate map. - Map predicateMap = (Map) mappedHandler; + Map predicateMap = + (Map) mappedHandler; if (predicateMap == null) { - predicateMap = new LinkedHashMap(); + predicateMap = new LinkedHashMap(); this.handlerMap.put(lookupKey, predicateMap); } predicateMap.put(predicate, resolvedHandler); diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java index 06894ce87bf..c8f712050fd 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,10 @@ package org.springframework.web.portlet.handler; import java.util.Map; - import javax.portlet.PortletRequest; import org.springframework.beans.BeansException; import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; /** * Implementation of the {@link org.springframework.web.portlet.HandlerMapping} @@ -51,7 +49,7 @@ import org.springframework.util.CollectionUtils; * @since 2.0 * @see ParameterMappingInterceptor */ -public class ParameterHandlerMapping extends AbstractMapBasedHandlerMapping { +public class ParameterHandlerMapping extends AbstractMapBasedHandlerMapping { /** * Default request parameter name to use for mapping to handlers: "action". @@ -61,7 +59,7 @@ public class ParameterHandlerMapping extends AbstractMapBasedHandlerMapping { private String parameterName = DEFAULT_PARAMETER_NAME; - private Map parameterMap; + private Map parameterMap; /** @@ -78,7 +76,7 @@ public class ParameterHandlerMapping extends AbstractMapBasedHandlerMapping { * Convenient for population with bean references. * @param parameterMap map with parameters as keys and beans as values */ - public void setParameterMap(Map parameterMap) { + public void setParameterMap(Map parameterMap) { this.parameterMap = parameterMap; } @@ -94,28 +92,12 @@ public class ParameterHandlerMapping extends AbstractMapBasedHandlerMapping { registerHandlers(this.parameterMap); } - /** - * Register all handlers specified in the Portlet mode map for the corresponding modes. - * @param parameterMap Map with parameter names as keys and handler beans or bean names as values - * @throws BeansException if the handler couldn't be registered - */ - @Override - protected void registerHandlers(Map parameterMap) throws BeansException { - if (CollectionUtils.isEmpty(parameterMap)) { - logger.warn("'parameterMap' is empty on ParameterHandlerMapping"); - } - else { - super.registerHandlers(parameterMap); - } - } - - /** * Uses the value of the specified parameter as lookup key. * @see #setParameterName */ @Override - protected Object getLookupKey(PortletRequest request) throws Exception { + protected String getLookupKey(PortletRequest request) throws Exception { return request.getParameter(this.parameterName); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java index 19a294d072f..0bcdcc8b413 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,14 +17,13 @@ package org.springframework.web.portlet.handler; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.portlet.PortletMode; import javax.portlet.PortletRequest; import org.springframework.beans.BeansException; +import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** @@ -48,9 +47,9 @@ import org.springframework.util.CollectionUtils; * @author John A. Lewis * @since 2.0 */ -public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { +public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { - private final Map portletModeMap = new HashMap(); + private final Map portletModeMap = new HashMap(); /** @@ -58,7 +57,7 @@ public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { * @param mappings properties with PortletMode names as keys and bean names as values */ public void setMappings(Properties mappings) { - this.portletModeMap.putAll(mappings); + CollectionUtils.mergePropertiesIntoMap(mappings, this.portletModeMap); } /** @@ -66,7 +65,7 @@ public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { * Convenient for population with bean references. * @param portletModeMap map with PortletMode names as keys and beans or bean names as values */ - public void setPortletModeMap(Map portletModeMap) { + public void setPortletModeMap(Map portletModeMap) { this.portletModeMap.putAll(portletModeMap); } @@ -79,27 +78,17 @@ public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { @Override public void initApplicationContext() throws BeansException { super.initApplicationContext(); - registerHandlers(this.portletModeMap); + registerHandlersByMode(this.portletModeMap); } /** * Register all handlers specified in the Portlet mode map for the corresponding modes. * @param portletModeMap Map with mode names as keys and handler beans or bean names as values - * @throws BeansException if the handler couldn't be registered */ - @Override - protected void registerHandlers(Map portletModeMap) throws BeansException { - if (CollectionUtils.isEmpty(portletModeMap)) { - logger.warn("Neither 'portletModeMap' nor 'mappings' set on PortletModeHandlerMapping"); - } - else { - for (Iterator it = portletModeMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String modeKey = (String) entry.getKey(); - PortletMode mode = new PortletMode(modeKey); - Object handler = entry.getValue(); - registerHandler(mode, handler); - } + protected void registerHandlersByMode(Map portletModeMap) { + Assert.notNull(portletModeMap, "'portletModeMap' must not be null"); + for (Map.Entry entry : portletModeMap.entrySet()) { + registerHandler(new PortletMode(entry.getKey()), entry.getValue()); } } @@ -108,7 +97,7 @@ public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { * Uses the current PortletMode as lookup key. */ @Override - protected Object getLookupKey(PortletRequest request) throws Exception { + protected PortletMode getLookupKey(PortletRequest request) throws Exception { return request.getPortletMode(); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java index af7ed5ec9f2..cde1399fe88 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java @@ -17,17 +17,13 @@ package org.springframework.web.portlet.handler; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Set; - import javax.portlet.PortletMode; import javax.portlet.PortletRequest; import org.springframework.beans.BeansException; import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; -import org.springframework.util.ObjectUtils; /** * Implementation of the {@link org.springframework.web.portlet.HandlerMapping} @@ -82,7 +78,7 @@ import org.springframework.util.ObjectUtils; * @since 2.0 * @see ParameterMappingInterceptor */ -public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerMapping { +public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerMapping { /** * Default request parameter name to use for mapping to handlers: "action". @@ -92,11 +88,11 @@ public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerM private String parameterName = DEFAULT_PARAMETER_NAME; - private Map portletModeParameterMap; + private Map> portletModeParameterMap; private boolean allowDuplicateParameters = false; - private final Set parametersUsed = new HashSet(); + private final Set parametersUsed = new HashSet(); /** @@ -114,7 +110,7 @@ public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerM *

Convenient for population with bean references. * @param portletModeParameterMap two-level map of portlet modes and parameters to handler beans */ - public void setPortletModeParameterMap(Map portletModeParameterMap) { + public void setPortletModeParameterMap(Map> portletModeParameterMap) { this.portletModeParameterMap = portletModeParameterMap; } @@ -140,45 +136,28 @@ public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerM @Override public void initApplicationContext() throws BeansException { super.initApplicationContext(); - registerHandlers(this.portletModeParameterMap); + registerHandlersByModeAndParameter(this.portletModeParameterMap); } /** * Register all handlers specified in the Portlet mode map for the corresponding modes. * @param portletModeParameterMap Map with mode names as keys and parameter Maps as values - * @throws BeansException if the handler couldn't be registered */ - @Override - protected void registerHandlers(Map portletModeParameterMap) throws BeansException { - if (CollectionUtils.isEmpty(portletModeParameterMap)) { - logger.warn("'portletModeParameterMap' not set on PortletModeParameterHandlerMapping"); - } - else { - for (Iterator it = portletModeParameterMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String modeKey = (String) entry.getKey(); - PortletMode mode = new PortletMode(modeKey); - Object parameterMap = entry.getValue(); - if (!(parameterMap instanceof Map)) { - throw new IllegalArgumentException( - "The value for the portlet mode must be a Map of parameter Strings to handler Objects"); - } - registerHandler(mode, (Map) parameterMap); - } + protected void registerHandlersByModeAndParameter(Map> portletModeParameterMap) { + Assert.notNull(portletModeParameterMap, "'portletModeParameterMap' must not be null"); + for (Map.Entry> entry : portletModeParameterMap.entrySet()) { + PortletMode mode = new PortletMode(entry.getKey()); + registerHandler(mode, entry.getValue()); } } /** * Register all handlers specified in the given parameter map. * @param parameterMap Map with parameter names as keys and handler beans or bean names as values - * @throws BeansException if the handler couldn't be registered */ - protected void registerHandler(PortletMode mode, Map parameterMap) throws BeansException { - for (Iterator it = parameterMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String parameter = (String) entry.getKey(); - Object handler = entry.getValue(); - registerHandler(mode, parameter, handler); + protected void registerHandler(PortletMode mode, Map parameterMap) { + for (Map.Entry entry : parameterMap.entrySet()) { + registerHandler(mode, entry.getKey(), entry.getValue()); } } @@ -202,10 +181,9 @@ public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerM } this.parametersUsed.add(parameter); - registerHandler(new LookupKey(mode, parameter), handler); + registerHandler(new PortletModeParameterLookupKey(mode, parameter), handler); } - /** * Returns a lookup key that combines the current PortletMode and the current * value of the specified parameter. @@ -213,49 +191,10 @@ public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerM * @see #setParameterName */ @Override - protected Object getLookupKey(PortletRequest request) throws Exception { + protected PortletModeParameterLookupKey getLookupKey(PortletRequest request) throws Exception { PortletMode mode = request.getPortletMode(); String parameter = request.getParameter(this.parameterName); - return new LookupKey(mode, parameter); - } - - - /** - * Internal class used as lookup key, combining PortletMode and parameter value. - */ - private static class LookupKey { - - private final PortletMode mode; - - private final String parameter; - - public LookupKey(PortletMode portletMode, String parameter) { - this.mode = portletMode; - this.parameter = parameter; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof LookupKey)) { - return false; - } - LookupKey otherKey = (LookupKey) other; - return (this.mode.equals(otherKey.mode) && - ObjectUtils.nullSafeEquals(this.parameter, otherKey.parameter)); - } - - @Override - public int hashCode() { - return (this.mode.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.parameter)); - } - - @Override - public String toString() { - return "Portlet mode '" + this.mode + "', parameter '" + this.parameter + "'"; - } + return new PortletModeParameterLookupKey(mode, parameter); } } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java new file mode 100644 index 00000000000..c5273680770 --- /dev/null +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java @@ -0,0 +1,64 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.web.portlet.handler; + +import javax.portlet.PortletMode; + +import org.springframework.util.ObjectUtils; + +/** + * Internal class used as lookup key, combining PortletMode and parameter value. + * + * @author Juergen Hoeller + */ +class PortletModeParameterLookupKey { + + private final PortletMode mode; + + private final String parameter; + + + public PortletModeParameterLookupKey(PortletMode portletMode, String parameter) { + this.mode = portletMode; + this.parameter = parameter; + } + + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof PortletModeParameterLookupKey)) { + return false; + } + PortletModeParameterLookupKey otherKey = (PortletModeParameterLookupKey) other; + return (this.mode.equals(otherKey.mode) && + ObjectUtils.nullSafeEquals(this.parameter, otherKey.parameter)); + } + + @Override + public int hashCode() { + return (this.mode.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.parameter)); + } + + @Override + public String toString() { + return "Portlet mode '" + this.mode + "', parameter '" + this.parameter + "'"; + } + +} diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java index 5797e5fd718..c5247c91957 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java @@ -20,6 +20,7 @@ import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.PortletContext; +import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadBase; @@ -113,12 +114,7 @@ public class CommonsPortletMultipartResolver extends CommonsFileUploadSupport public boolean isMultipart(ActionRequest request) { - if (request == null) { - return false; - } - else { - return PortletFileUpload.isMultipartContent(request); - } + return (request != null && PortletFileUpload.isMultipartContent(request)); } public MultipartActionRequest resolveMultipart(final ActionRequest request) throws MultipartException { @@ -146,11 +142,12 @@ public class CommonsPortletMultipartResolver extends CommonsFileUploadSupport * @return the parsing result * @throws MultipartException if multipart resolution failed. */ + @SuppressWarnings("unchecked") protected MultipartParsingResult parseRequest(ActionRequest request) throws MultipartException { String encoding = determineEncoding(request); FileUpload fileUpload = prepareFileUpload(encoding); try { - List fileItems = ((PortletFileUpload) fileUpload).parseRequest(request); + List fileItems = ((PortletFileUpload) fileUpload).parseRequest(request); return parseFileItems(fileItems, encoding); } catch (FileUploadBase.SizeLimitExceededException ex) { diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java index 155fdf1ee15..01b46e47f2f 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; - import javax.portlet.ActionRequest; import org.springframework.web.multipart.MultipartFile; @@ -39,22 +38,24 @@ import org.springframework.web.portlet.util.ActionRequestWrapper; */ public class DefaultMultipartActionRequest extends ActionRequestWrapper implements MultipartActionRequest { - private Map multipartFiles; + private Map multipartFiles; - private Map multipartParameters; + private Map multipartParameters; /** * Wrap the given Portlet ActionRequest in a MultipartActionRequest. * @param request the request to wrap - * @param multipartFiles a map of the multipart files - * @param multipartParameters a map of the parameters to expose, + * @param mpFiles a map of the multipart files + * @param mpParams a map of the parameters to expose, * with Strings as keys and String arrays as values */ - public DefaultMultipartActionRequest(ActionRequest request, Map multipartFiles, Map multipartParameters) { + public DefaultMultipartActionRequest( + ActionRequest request, Map mpFiles, Map mpParams) { + super(request); - setMultipartFiles(multipartFiles); - setMultipartParameters(multipartParameters); + setMultipartFiles(mpFiles); + setMultipartParameters(mpParams); } /** @@ -66,25 +67,25 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen } - public Iterator getFileNames() { + public Iterator getFileNames() { return getMultipartFiles().keySet().iterator(); } public MultipartFile getFile(String name) { - return (MultipartFile) getMultipartFiles().get(name); + return getMultipartFiles().get(name); } - public Map getFileMap() { + public Map getFileMap() { return getMultipartFiles(); } @Override - public Enumeration getParameterNames() { - Set paramNames = new HashSet(); + public Enumeration getParameterNames() { + Set paramNames = new HashSet(); Enumeration paramEnum = super.getParameterNames(); while (paramEnum.hasMoreElements()) { - paramNames.add(paramEnum.nextElement()); + paramNames.add((String) paramEnum.nextElement()); } paramNames.addAll(getMultipartParameters().keySet()); return Collections.enumeration(paramNames); @@ -92,7 +93,7 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen @Override public String getParameter(String name) { - String[] values = (String[]) getMultipartParameters().get(name); + String[] values = getMultipartParameters().get(name); if (values != null) { return (values.length > 0 ? values[0] : null); } @@ -101,7 +102,7 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen @Override public String[] getParameterValues(String name) { - String[] values = (String[]) getMultipartParameters().get(name); + String[] values = getMultipartParameters().get(name); if (values != null) { return values; } @@ -109,8 +110,9 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen } @Override - public Map getParameterMap() { - Map paramMap = new HashMap(); + @SuppressWarnings("unchecked") + public Map getParameterMap() { + Map paramMap = new HashMap(); paramMap.putAll(super.getParameterMap()); paramMap.putAll(getMultipartParameters()); return paramMap; @@ -121,7 +123,7 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen * Set a Map with parameter names as keys and MultipartFile objects as values. * To be invoked by subclasses on initialization. */ - protected final void setMultipartFiles(Map multipartFiles) { + protected final void setMultipartFiles(Map multipartFiles) { this.multipartFiles = Collections.unmodifiableMap(multipartFiles); } @@ -130,7 +132,7 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen * lazily initializing it if necessary. * @see #initializeMultipart() */ - protected Map getMultipartFiles() { + protected Map getMultipartFiles() { if (this.multipartFiles == null) { initializeMultipart(); } @@ -141,7 +143,7 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen * Set a Map with parameter names as keys and String array objects as values. * To be invoked by subclasses on initialization. */ - protected final void setMultipartParameters(Map multipartParameters) { + protected final void setMultipartParameters(Map multipartParameters) { this.multipartParameters = multipartParameters; } @@ -150,7 +152,7 @@ public class DefaultMultipartActionRequest extends ActionRequestWrapper implemen * lazily initializing it if necessary. * @see #initializeMultipart() */ - protected Map getMultipartParameters() { + protected Map getMultipartParameters() { if (this.multipartParameters == null) { initializeMultipart(); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractCommandController.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractCommandController.java index f354e1dc1ec..acfe87e30e5 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractCommandController.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractCommandController.java @@ -49,7 +49,9 @@ import org.springframework.web.portlet.util.PortletUtils; * @see #setCommandClass * @see #setCommandName * @see #setValidator + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class AbstractCommandController extends BaseCommandController { /** diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractFormController.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractFormController.java index cb5b7110a1c..f21a40ccec5 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractFormController.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractFormController.java @@ -243,7 +243,9 @@ import org.springframework.web.portlet.handler.PortletSessionRequiredException; * @see #showForm(RenderRequest, RenderResponse, BindException) * @see SimpleFormController * @see AbstractWizardFormController + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class AbstractFormController extends BaseCommandController { /** diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractWizardFormController.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractWizardFormController.java index 3ff16a1bede..ef52eec3458 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractWizardFormController.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractWizardFormController.java @@ -17,9 +17,7 @@ package org.springframework.web.portlet.mvc; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; - import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; @@ -83,7 +81,9 @@ import org.springframework.web.portlet.util.PortletUtils; * @see #validatePage * @see #processFinish * @see #processCancel + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class AbstractWizardFormController extends AbstractFormController { /** @@ -480,10 +480,9 @@ public abstract class AbstractWizardFormController extends AbstractFormControlle */ protected void setTargetRenderParameter(ActionRequest request, ActionResponse response) { try { - Iterator it = PortletUtils.getParametersStartingWith(request, PARAM_TARGET).entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - String param = PARAM_TARGET + (String) entry.getKey(); + Map params = PortletUtils.getParametersStartingWith(request, PARAM_TARGET); + for (Map.Entry entry : params.entrySet()) { + String param = PARAM_TARGET + entry.getKey(); Object value = entry.getValue(); if (logger.isDebugEnabled()) { logger.debug("Setting target render parameter [" + param + "]"); diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/BaseCommandController.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/BaseCommandController.java index 4780708adaf..162843b29b9 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/BaseCommandController.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/BaseCommandController.java @@ -138,7 +138,9 @@ import org.springframework.web.portlet.handler.PortletSessionRequiredException; * @author Juergen Hoeller * @author John A. Lewis * @since 2.0 + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class BaseCommandController extends AbstractController { /** diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleFormController.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleFormController.java index b3d3fc95621..97e622bef4c 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleFormController.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleFormController.java @@ -132,7 +132,9 @@ import org.springframework.web.portlet.ModelAndView; * @author Juergen Hoeller * @author Rob Harrop * @since 2.0 + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public class SimpleFormController extends AbstractFormController { private String formView; diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java index 067b908e7ca..2ae1422bd98 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java @@ -19,15 +19,11 @@ package org.springframework.web.portlet.mvc.annotation; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; - import javax.portlet.PortletMode; import javax.portlet.PortletRequest; import org.springframework.beans.BeansException; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.generic.GenericBeanFactoryAccessor; import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Controller; import org.springframework.util.ReflectionUtils; @@ -77,7 +73,7 @@ import org.springframework.web.portlet.handler.AbstractMapBasedHandlerMapping; * @see RequestMapping * @see AnnotationMethodHandlerAdapter */ -public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapping { +public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapping { /** * Calls the registerHandlers method in addition @@ -99,10 +95,7 @@ public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapp String[] beanNames = context.getBeanNamesForType(Object.class); for (String beanName : beanNames) { Class handlerType = context.getType(beanName); - ListableBeanFactory bf = (context instanceof ConfigurableApplicationContext ? - ((ConfigurableApplicationContext) context).getBeanFactory() : context); - GenericBeanFactoryAccessor bfa = new GenericBeanFactoryAccessor(bf); - RequestMapping mapping = bfa.findAnnotationOnBean(beanName, RequestMapping.class); + RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class); if (mapping != null) { String[] modeKeys = mapping.value(); String[] params = mapping.params(); @@ -167,7 +160,7 @@ public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapp * Uses the current PortletMode as lookup key. */ @Override - protected Object getLookupKey(PortletRequest request) throws Exception { + protected PortletMode getLookupKey(PortletRequest request) throws Exception { return request.getPortletMode(); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java index c76f45ffce8..2e0dd8d8476 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java @@ -276,17 +276,11 @@ public abstract class PortletUtils { * @param request current portlet request * @param attributes the attributes Map */ - public static void exposeRequestAttributes(PortletRequest request, Map attributes) { + public static void exposeRequestAttributes(PortletRequest request, Map attributes) { Assert.notNull(request, "Request must not be null"); - Assert.notNull(attributes, "attributes Map must not be null"); - Iterator it = attributes.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - if (!(entry.getKey() instanceof String)) { - throw new IllegalArgumentException( - "Invalid key [" + entry.getKey() + "] in attributes Map - only Strings allowed as attribute keys"); - } - request.setAttribute((String) entry.getKey(), entry.getValue()); + Assert.notNull(attributes, "Attributes Map must not be null"); + for (Map.Entry entry : attributes.entrySet()) { + request.setAttribute(entry.getKey(), entry.getValue()); } } @@ -345,10 +339,10 @@ public abstract class PortletUtils { * @see javax.portlet.PortletRequest#getParameterValues * @see javax.portlet.PortletRequest#getParameterMap */ - public static Map getParametersStartingWith(PortletRequest request, String prefix) { + public static Map getParametersStartingWith(PortletRequest request, String prefix) { Assert.notNull(request, "Request must not be null"); Enumeration paramNames = request.getParameterNames(); - Map params = new TreeMap(); + Map params = new TreeMap(); if (prefix == null) { prefix = ""; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/WebDataBinder.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/WebDataBinder.java index 7c8575c52de..ba575a95ba7 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/WebDataBinder.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/WebDataBinder.java @@ -17,7 +17,6 @@ package org.springframework.web.bind; import java.lang.reflect.Array; -import java.util.Iterator; import java.util.Map; import org.springframework.beans.MutablePropertyValues; @@ -165,8 +164,7 @@ public class WebDataBinder extends DataBinder { if (getFieldMarkerPrefix() != null) { String fieldMarkerPrefix = getFieldMarkerPrefix(); PropertyValue[] pvArray = mpvs.getPropertyValues(); - for (int i = 0; i < pvArray.length; i++) { - PropertyValue pv = pvArray[i]; + for (PropertyValue pv : pvArray) { if (pv.getName().startsWith(fieldMarkerPrefix)) { String field = pv.getName().substring(fieldMarkerPrefix.length()); if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) { @@ -214,11 +212,10 @@ public class WebDataBinder extends DataBinder { * @see org.springframework.web.multipart.MultipartFile * @see #setBindEmptyMultipartFiles */ - protected void bindMultipartFiles(Map multipartFiles, MutablePropertyValues mpvs) { - for (Iterator it = multipartFiles.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String key = (String) entry.getKey(); - MultipartFile value = (MultipartFile) entry.getValue(); + protected void bindMultipartFiles(Map multipartFiles, MutablePropertyValues mpvs) { + for (Map.Entry entry : multipartFiles.entrySet()) { + String key = entry.getKey(); + MultipartFile value = entry.getValue(); if (isBindEmptyMultipartFiles() || !value.isEmpty()) { mpvs.addPropertyValue(key, value); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/MultipartRequest.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/MultipartRequest.java index a7591051bc7..d22ce7bde75 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/MultipartRequest.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/MultipartRequest.java @@ -37,7 +37,7 @@ public interface MultipartRequest { * original file names. * @return the names of the files */ - Iterator getFileNames(); + Iterator getFileNames(); /** * Return the contents plus description of an uploaded file in this request, @@ -53,6 +53,6 @@ public interface MultipartRequest { * {@link org.springframework.web.multipart.MultipartFile} objects as values * @see MultipartFile */ - Map getFileMap(); + Map getFileMap(); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java index 733047a5817..0ee6e641116 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -34,6 +33,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartException; +import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.WebUtils; /** @@ -212,13 +212,12 @@ public abstract class CommonsFileUploadSupport { * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) */ - protected MultipartParsingResult parseFileItems(List fileItems, String encoding) { - Map multipartFiles = new HashMap(); - Map multipartParameters = new HashMap(); + protected MultipartParsingResult parseFileItems(List fileItems, String encoding) { + Map multipartFiles = new HashMap(); + Map multipartParameters = new HashMap(); // Extract multipart files and multipart parameters. - for (Iterator it = fileItems.iterator(); it.hasNext();) { - FileItem fileItem = (FileItem) it.next(); + for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value = null; if (encoding != null) { @@ -236,10 +235,10 @@ public abstract class CommonsFileUploadSupport { else { value = fileItem.getString(); } - String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName()); + String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field - multipartParameters.put(fileItem.getFieldName(), new String[] { value }); + multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields @@ -251,8 +250,8 @@ public abstract class CommonsFileUploadSupport { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); if (multipartFiles.put(file.getName(), file) != null) { - throw new MultipartException( - "Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver"); + throw new MultipartException("Multiple files for field name [" + file.getName() + + "] found - not supported by MultipartResolver"); } if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + @@ -271,14 +270,16 @@ public abstract class CommonsFileUploadSupport { * @param multipartFiles Collection of MultipartFile instances * @see org.apache.commons.fileupload.FileItem#delete() */ - protected void cleanupFileItems(Collection multipartFiles) { - for (Iterator it = multipartFiles.iterator(); it.hasNext();) { - CommonsMultipartFile file = (CommonsMultipartFile) it.next(); - if (logger.isDebugEnabled()) { - logger.debug("Cleaning up multipart file [" + file.getName() + "] with original filename [" + - file.getOriginalFilename() + "], stored " + file.getStorageDescription()); + protected void cleanupFileItems(Collection multipartFiles) { + for (MultipartFile file : multipartFiles) { + if (file instanceof CommonsMultipartFile) { + CommonsMultipartFile cmf = (CommonsMultipartFile) file; + cmf.getFileItem().delete(); + if (logger.isDebugEnabled()) { + logger.debug("Cleaning up multipart file [" + cmf.getName() + "] with original filename [" + + cmf.getOriginalFilename() + "], stored " + cmf.getStorageDescription()); + } } - file.getFileItem().delete(); } } @@ -289,31 +290,31 @@ public abstract class CommonsFileUploadSupport { */ protected static class MultipartParsingResult { - private final Map multipartFiles; + private final Map multipartFiles; - private final Map multipartParameters; + private final Map multipartParameters; /** * Create a new MultipartParsingResult. - * @param multipartFiles Map of field name to MultipartFile instance + * @param mpFiles Map of field name to MultipartFile instance * @param multipartParameters Map of field name to form field String value */ - public MultipartParsingResult(Map multipartFiles, Map multipartParameters) { - this.multipartFiles = multipartFiles; - this.multipartParameters = multipartParameters; + public MultipartParsingResult(Map mpFiles, Map mpParams) { + this.multipartFiles = mpFiles; + this.multipartParameters = mpParams; } /** * Return the multipart files as Map of field name to MultipartFile instance. */ - public Map getMultipartFiles() { + public Map getMultipartFiles() { return this.multipartFiles; } /** * Return the multipart parameters as Map of field name to form field String value. */ - public Map getMultipartParameters() { + public Map getMultipartParameters() { return this.multipartParameters; } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java index cdb19d7a32f..42a72e6b1ab 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java @@ -24,6 +24,7 @@ import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.util.Assert; @@ -118,12 +119,7 @@ public class CommonsMultipartResolver extends CommonsFileUploadSupport public boolean isMultipart(HttpServletRequest request) { - if (request == null) { - return false; - } - else { - return ServletFileUpload.isMultipartContent(request); - } + return (request != null && ServletFileUpload.isMultipartContent(request)); } public MultipartHttpServletRequest resolveMultipart(final HttpServletRequest request) throws MultipartException { @@ -151,11 +147,12 @@ public class CommonsMultipartResolver extends CommonsFileUploadSupport * @return the parsing result * @throws MultipartException if multipart resolution failed. */ + @SuppressWarnings("unchecked") protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException { String encoding = determineEncoding(request); FileUpload fileUpload = prepareFileUpload(encoding); try { - List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); + List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); return parseFileItems(fileItems, encoding); } catch (FileUploadBase.SizeLimitExceededException ex) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/AbstractMultipartHttpServletRequest.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/AbstractMultipartHttpServletRequest.java index 53ef71c0770..c0b6626fb60 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/AbstractMultipartHttpServletRequest.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/AbstractMultipartHttpServletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import org.springframework.web.multipart.MultipartHttpServletRequest; public abstract class AbstractMultipartHttpServletRequest extends HttpServletRequestWrapper implements MultipartHttpServletRequest { - private Map multipartFiles; + private Map multipartFiles; /** @@ -48,15 +48,15 @@ public abstract class AbstractMultipartHttpServletRequest extends HttpServletReq } - public Iterator getFileNames() { + public Iterator getFileNames() { return getMultipartFiles().keySet().iterator(); } public MultipartFile getFile(String name) { - return (MultipartFile) getMultipartFiles().get(name); + return getMultipartFiles().get(name); } - public Map getFileMap() { + public Map getFileMap() { return getMultipartFiles(); } @@ -65,7 +65,7 @@ public abstract class AbstractMultipartHttpServletRequest extends HttpServletReq * Set a Map with parameter names as keys and MultipartFile objects as values. * To be invoked by subclasses on initialization. */ - protected final void setMultipartFiles(Map multipartFiles) { + protected final void setMultipartFiles(Map multipartFiles) { this.multipartFiles = Collections.unmodifiableMap(multipartFiles); } @@ -74,7 +74,7 @@ public abstract class AbstractMultipartHttpServletRequest extends HttpServletReq * lazily initializing it if necessary. * @see #initializeMultipart() */ - protected Map getMultipartFiles() { + protected Map getMultipartFiles() { if (this.multipartFiles == null) { initializeMultipart(); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequest.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequest.java index c242cff7f9d..656abf30d15 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequest.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,10 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - import javax.servlet.http.HttpServletRequest; +import org.springframework.web.multipart.MultipartFile; + /** * Default implementation of the * {@link org.springframework.web.multipart.MultipartHttpServletRequest} @@ -37,22 +38,22 @@ import javax.servlet.http.HttpServletRequest; */ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest { - private Map multipartParameters; + private Map multipartParameters; /** * Wrap the given HttpServletRequest in a MultipartHttpServletRequest. * @param request the servlet request to wrap - * @param multipartFiles a map of the multipart files - * @param multipartParameters a map of the parameters to expose, + * @param mpFiles a map of the multipart files + * @param mpParams a map of the parameters to expose, * with Strings as keys and String arrays as values */ public DefaultMultipartHttpServletRequest( - HttpServletRequest request, Map multipartFiles, Map multipartParameters) { + HttpServletRequest request, Map mpFiles, Map mpParams) { super(request); - setMultipartFiles(multipartFiles); - setMultipartParameters(multipartParameters); + setMultipartFiles(mpFiles); + setMultipartParameters(mpParams); } /** @@ -65,11 +66,11 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer @Override - public Enumeration getParameterNames() { - Set paramNames = new HashSet(); + public Enumeration getParameterNames() { + Set paramNames = new HashSet(); Enumeration paramEnum = super.getParameterNames(); while (paramEnum.hasMoreElements()) { - paramNames.add(paramEnum.nextElement()); + paramNames.add((String) paramEnum.nextElement()); } paramNames.addAll(getMultipartParameters().keySet()); return Collections.enumeration(paramNames); @@ -77,7 +78,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer @Override public String getParameter(String name) { - String[] values = (String[]) getMultipartParameters().get(name); + String[] values = getMultipartParameters().get(name); if (values != null) { return (values.length > 0 ? values[0] : null); } @@ -86,7 +87,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer @Override public String[] getParameterValues(String name) { - String[] values = (String[]) getMultipartParameters().get(name); + String[] values = getMultipartParameters().get(name); if (values != null) { return values; } @@ -94,8 +95,9 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer } @Override - public Map getParameterMap() { - Map paramMap = new HashMap(); + @SuppressWarnings("unchecked") + public Map getParameterMap() { + Map paramMap = new HashMap(); paramMap.putAll(super.getParameterMap()); paramMap.putAll(getMultipartParameters()); return paramMap; @@ -106,7 +108,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer * Set a Map with parameter names as keys and String array objects as values. * To be invoked by subclasses on initialization. */ - protected final void setMultipartParameters(Map multipartParameters) { + protected final void setMultipartParameters(Map multipartParameters) { this.multipartParameters = multipartParameters; } @@ -115,7 +117,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer * lazily initializing it if necessary. * @see #initializeMultipart() */ - protected Map getMultipartParameters() { + protected Map getMultipartParameters() { if (this.multipartParameters == null) { initializeMultipart(); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java index 54de4f55883..3753f1823ef 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java @@ -1101,9 +1101,8 @@ public class DispatcherServlet extends FrameworkServlet { // Check registerer HandlerExceptionResolvers... ModelAndView exMv = null; - for (Iterator it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) { - HandlerExceptionResolver resolver = (HandlerExceptionResolver) it.next(); - exMv = resolver.resolveException(request, response, handler, ex); + for (Iterator it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) { + exMv = it.next().resolveException(request, response, handler, ex); } if (exMv != null) { if (logger.isDebugEnabled()) { @@ -1191,7 +1190,8 @@ public class DispatcherServlet extends FrameworkServlet { * (typically in case of problems creating an actual View object) * @see ViewResolver#resolveViewName */ - protected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest request) + protected View resolveViewName( + String viewName, Map model, Locale locale, HttpServletRequest request) throws Exception { for (ViewResolver viewResolver : this.viewResolvers) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ModelAndView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ModelAndView.java index 9eadea7002f..5a6fd426d81 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ModelAndView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ModelAndView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,7 +92,7 @@ public class ModelAndView { * (Objects). Model entries may not be null, but the * model Map may be null if there is no model data. */ - public ModelAndView(String viewName, Map model) { + public ModelAndView(String viewName, Map model) { this.view = viewName; if (model != null) { getModelMap().addAllAttributes(model); @@ -109,7 +109,7 @@ public class ModelAndView { * (Objects). Model entries may not be null, but the * model Map may be null if there is no model data. */ - public ModelAndView(View view, Map model) { + public ModelAndView(View view, Map model) { this.view = view; if (model != null) { getModelMap().addAllAttributes(model); @@ -194,7 +194,7 @@ public class ModelAndView { * Return the model map. May return null. * Called by DispatcherServlet for evaluation of the model. */ - protected Map getModelInternal() { + protected Map getModelInternal() { return this.model; } @@ -212,7 +212,7 @@ public class ModelAndView { * Return the model map. Never returns null. * To be called by application code for modifying the model. */ - public Map getModel() { + public Map getModel() { return getModelMap(); } @@ -246,7 +246,7 @@ public class ModelAndView { * @see ModelMap#addAllAttributes(Map) * @see #getModelMap() */ - public ModelAndView addAllObjects(Map modelMap) { + public ModelAndView addAllObjects(Map modelMap) { getModelMap().addAllAttributes(modelMap); return this; } @@ -291,14 +291,14 @@ public class ModelAndView { */ @Override public String toString() { - StringBuffer buf = new StringBuffer("ModelAndView: "); + StringBuilder sb = new StringBuilder("ModelAndView: "); if (isReference()) { - buf.append("reference to view with name '").append(this.view).append("'"); + sb.append("reference to view with name '").append(this.view).append("'"); } else { - buf.append("materialized View is [").append(this.view).append(']'); + sb.append("materialized View is [").append(this.view).append(']'); } - buf.append("; model is ").append(this.model); - return buf.toString(); + sb.append("; model is ").append(this.model); + return sb.toString(); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/View.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/View.java index aa7550deeb8..24d98adaf4a 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/View.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/View.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -63,6 +63,6 @@ public interface View { * @param response HTTP response we are building * @throws Exception if rendering failed */ - void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; + void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java index 89fab03fdcb..3fe25a7c7aa 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,12 +104,13 @@ public class ViewRendererServlet extends HttpServlet { * @throws Exception in case of any kind of processing failure * @see org.springframework.web.servlet.View#render */ + @SuppressWarnings("unchecked") protected void renderView(HttpServletRequest request, HttpServletResponse response) throws Exception { View view = (View) request.getAttribute(VIEW_ATTRIBUTE); if (view == null) { throw new ServletException("Could not complete render request: View is null"); } - Map model = (Map) request.getAttribute(MODEL_ATTRIBUTE); + Map model = (Map) request.getAttribute(MODEL_ATTRIBUTE); view.render(model, request, response); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java index a6f02eef94e..97546525a22 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,11 @@ package org.springframework.web.servlet.handler; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.springframework.beans.BeansException; +import org.springframework.util.CollectionUtils; /** * Implementation of the {@link org.springframework.web.servlet.HandlerMapping} @@ -55,7 +55,7 @@ import org.springframework.beans.BeansException; */ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping { - private final Map urlMap = new HashMap(); + private final Map urlMap = new HashMap(); /** @@ -67,7 +67,7 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping { * @see #setUrlMap */ public void setMappings(Properties mappings) { - this.urlMap.putAll(mappings); + CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap); } /** @@ -78,7 +78,7 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping { * @param urlMap map with URLs as keys and beans as values * @see #setMappings */ - public void setUrlMap(Map urlMap) { + public void setUrlMap(Map urlMap) { this.urlMap.putAll(urlMap); } @@ -110,15 +110,14 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping { * @throws BeansException if a handler couldn't be registered * @throws IllegalStateException if there is a conflicting handler registered */ - protected void registerHandlers(Map urlMap) throws BeansException { + protected void registerHandlers(Map urlMap) throws BeansException { if (urlMap.isEmpty()) { logger.warn("Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping"); } else { - Iterator it = urlMap.keySet().iterator(); - while (it.hasNext()) { - String url = (String) it.next(); - Object handler = urlMap.get(url); + for (Map.Entry entry : urlMap.entrySet()) { + String url = entry.getKey(); + Object handler = entry.getValue(); // Prepend with slash if not already present. if (!url.startsWith("/")) { url = "/" + url; diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractCommandController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractCommandController.java index f3e50c11a54..81df88d3087 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractCommandController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractCommandController.java @@ -47,7 +47,9 @@ import org.springframework.web.servlet.ModelAndView; * @see #setCommandClass * @see #setCommandName * @see #setValidator + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class AbstractCommandController extends BaseCommandController { /** diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractFormController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractFormController.java index 832de175d8d..4b1518f1c9f 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractFormController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractFormController.java @@ -167,7 +167,9 @@ import org.springframework.web.servlet.ModelAndView; * @see #processFormSubmission * @see SimpleFormController * @see AbstractWizardFormController + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class AbstractFormController extends BaseCommandController { private boolean bindOnNewForm = false; diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractWizardFormController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractWizardFormController.java index 3cae3a06a6c..c9aafcab00b 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractWizardFormController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/AbstractWizardFormController.java @@ -73,7 +73,9 @@ import org.springframework.web.util.WebUtils; * @see #validatePage * @see #processFinish * @see #processCancel + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class AbstractWizardFormController extends AbstractFormController { /** diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/BaseCommandController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/BaseCommandController.java index f4963ae2fca..9082bbf993b 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/BaseCommandController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/BaseCommandController.java @@ -131,7 +131,9 @@ import org.springframework.web.context.request.ServletWebRequest; * * @author Rod Johnson * @author Juergen Hoeller + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public abstract class BaseCommandController extends AbstractController { /** Default command name used for binding command objects: "command" */ diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/CancellableFormController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/CancellableFormController.java index d5be516c864..888dce14e27 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/CancellableFormController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/CancellableFormController.java @@ -57,7 +57,9 @@ import org.springframework.web.util.WebUtils; * @see #setCancelView * @see #isCancelRequest(javax.servlet.http.HttpServletRequest) * @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object) + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public class CancellableFormController extends SimpleFormController { /** diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/SimpleFormController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/SimpleFormController.java index aab02005a04..dda32c093a7 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/SimpleFormController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/SimpleFormController.java @@ -97,7 +97,9 @@ import org.springframework.web.servlet.ModelAndView; * @author Juergen Hoeller * @author Rob Harrop * @since 05.05.2003 + * @deprecated as of Spring 3.0, in favor of annotated controllers */ +@Deprecated public class SimpleFormController extends AbstractFormController { private String formView; diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java index 5d6fc1e9611..38ac7792944 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,10 @@ package org.springframework.web.servlet.mvc; +import java.util.Enumeration; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -50,7 +49,7 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle private UrlPathHelper urlPathHelper = new UrlPathHelper(); - private Map cacheMappings = new HashMap(); + private Map cacheMappings = new HashMap(); private PathMatcher pathMatcher = new AntPathMatcher(); @@ -111,8 +110,9 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle */ public void setCacheMappings(Properties cacheMappings) { this.cacheMappings.clear(); - for (Iterator it = cacheMappings.keySet().iterator(); it.hasNext();) { - String path = (String) it.next(); + Enumeration propNames = cacheMappings.propertyNames(); + while (propNames.hasMoreElements()) { + String path = (String) propNames.nextElement(); this.cacheMappings.put(path, Integer.valueOf(cacheMappings.getProperty(path))); } } @@ -143,7 +143,7 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle if (logger.isDebugEnabled()) { logger.debug("Applying " + cacheSeconds + " cache seconds to [" + lookupPath + "]"); } - checkAndPrepare(request, response, cacheSeconds.intValue(), handler instanceof LastModified); + checkAndPrepare(request, response, cacheSeconds, handler instanceof LastModified); } else { if (logger.isDebugEnabled()) { @@ -166,13 +166,12 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle */ protected Integer lookupCacheSeconds(String urlPath) { // direct match? - Integer cacheSeconds = (Integer) this.cacheMappings.get(urlPath); + Integer cacheSeconds = this.cacheMappings.get(urlPath); if (cacheSeconds == null) { // pattern match? - for (Iterator it = this.cacheMappings.keySet().iterator(); it.hasNext();) { - String registeredPath = (String) it.next(); + for (String registeredPath : this.cacheMappings.keySet()) { if (this.pathMatcher.match(registeredPath, urlPath)) { - cacheSeconds = (Integer) this.cacheMappings.get(registeredPath); + cacheSeconds = this.cacheMappings.get(registeredPath); } } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java index 64c77b456ed..2ed0bfa1c10 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java @@ -24,10 +24,7 @@ import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.generic.GenericBeanFactoryAccessor; import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Controller; import org.springframework.util.ReflectionUtils; @@ -108,11 +105,7 @@ public class DefaultAnnotationHandlerMapping extends AbstractDetectingUrlHandler protected String[] determineUrlsForHandler(String beanName) { ApplicationContext context = getApplicationContext(); Class handlerType = context.getType(beanName); - ListableBeanFactory bf = (context instanceof ConfigurableApplicationContext ? - ((ConfigurableApplicationContext) context).getBeanFactory() : context); - GenericBeanFactoryAccessor bfa = new GenericBeanFactoryAccessor(bf); - RequestMapping mapping = bfa.findAnnotationOnBean(beanName, RequestMapping.class); - + RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class); if (mapping != null) { // @RequestMapping found at type level this.cachedMappings.put(handlerType, mapping); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/MultiActionController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/MultiActionController.java index 85e600f297e..5508de66f64 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/MultiActionController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/MultiActionController.java @@ -22,8 +22,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -164,13 +162,13 @@ public class MultiActionController extends AbstractController implements LastMod private WebBindingInitializer webBindingInitializer; /** Handler methods, keyed by name */ - private final Map handlerMethodMap = new HashMap(); + private final Map handlerMethodMap = new HashMap(); /** LastModified methods, keyed by handler method name (without LAST_MODIFIED_SUFFIX) */ - private final Map lastModifiedMethodMap = new HashMap(); + private final Map lastModifiedMethodMap = new HashMap(); /** Methods, keyed by exception class */ - private final Map exceptionHandlerMap = new HashMap(); + private final Map exceptionHandlerMap = new HashMap(); /** @@ -271,9 +269,8 @@ public class MultiActionController extends AbstractController implements LastMod // Look at all methods in the subclass, trying to find // methods that are validators according to our criteria Method[] methods = delegate.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { + for (Method method : methods) { // We're looking for methods with given parameters. - Method method = methods[i]; if (isExceptionHandlerMethod(method)) { registerExceptionHandlerMethod(method); } @@ -370,12 +367,12 @@ public class MultiActionController extends AbstractController implements LastMod public long getLastModified(HttpServletRequest request) { try { String handlerMethodName = this.methodNameResolver.getHandlerMethodName(request); - Method lastModifiedMethod = (Method) this.lastModifiedMethodMap.get(handlerMethodName); + Method lastModifiedMethod = this.lastModifiedMethodMap.get(handlerMethodName); if (lastModifiedMethod != null) { try { // Invoke the last-modified method... - Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, new Object[] {request}); - return (wrappedLong != null ? wrappedLong.longValue() : -1); + Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, request); + return (wrappedLong != null ? wrappedLong : -1); } catch (Exception ex) { // We encountered an error invoking the last-modified method. @@ -443,14 +440,14 @@ public class MultiActionController extends AbstractController implements LastMod protected final ModelAndView invokeNamedMethod( String methodName, HttpServletRequest request, HttpServletResponse response) throws Exception { - Method method = (Method) this.handlerMethodMap.get(methodName); + Method method = this.handlerMethodMap.get(methodName); if (method == null) { throw new NoSuchRequestHandlingMethodException(methodName, getClass()); } try { Class[] paramTypes = method.getParameterTypes(); - List params = new ArrayList(4); + List params = new ArrayList(4); params.add(request); params.add(response); @@ -489,6 +486,7 @@ public class MultiActionController extends AbstractController implements LastMod * null or an instance of {@link ModelAndView}. When returning a {@link Map}, * the {@link Map} instance is wrapped in a new {@link ModelAndView} instance. */ + @SuppressWarnings("unchecked") private ModelAndView massageReturnValueIfNecessary(Object returnValue) { if (returnValue instanceof ModelAndView) { return (ModelAndView) returnValue; @@ -533,9 +531,9 @@ public class MultiActionController extends AbstractController implements LastMod ServletRequestDataBinder binder = createBinder(request, command); binder.bind(request); if (this.validators != null) { - for (int i = 0; i < this.validators.length; i++) { - if (this.validators[i].supports(command.getClass())) { - ValidationUtils.invokeValidator(this.validators[i], command, binder.getBindingResult()); + for (Validator validator : this.validators) { + if (validator.supports(command.getClass())) { + ValidationUtils.invokeValidator(validator, command, binder.getBindingResult()); } } } @@ -594,16 +592,6 @@ public class MultiActionController extends AbstractController implements LastMod if (this.webBindingInitializer != null) { this.webBindingInitializer.initBinder(binder, new ServletWebRequest(request)); } - initBinder((ServletRequest) request, binder); - } - - /** - * Initialize the given binder instance, for example with custom editors. - * @deprecated as of Spring 2.0: - * use initBinder(HttpServletRequest, ServletRequestDataBinder) instead - */ - @Deprecated - protected void initBinder(ServletRequest request, ServletRequestDataBinder binder) throws Exception { } @@ -618,13 +606,13 @@ public class MultiActionController extends AbstractController implements LastMod if (logger.isDebugEnabled()) { logger.debug("Trying to find handler for exception class [" + exceptionClass.getName() + "]"); } - Method handler = (Method) this.exceptionHandlerMap.get(exceptionClass); + Method handler = this.exceptionHandlerMap.get(exceptionClass); while (handler == null && !exceptionClass.equals(Throwable.class)) { if (logger.isDebugEnabled()) { logger.debug("Trying to find handler for exception superclass [" + exceptionClass.getName() + "]"); } exceptionClass = exceptionClass.getSuperclass(); - handler = (Method) this.exceptionHandlerMap.get(exceptionClass); + handler = this.exceptionHandlerMap.get(exceptionClass); } return handler; } @@ -646,7 +634,7 @@ public class MultiActionController extends AbstractController implements LastMod logger.debug("Invoking exception handler [" + handler + "] for exception: " + ex); } try { - Object returnValue = handler.invoke(this.delegate, new Object[] {request, response, ex}); + Object returnValue = handler.invoke(this.delegate, request, response, ex); return massageReturnValueIfNecessary(returnValue); } catch (InvocationTargetException ex2) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java index 6dfc33d1cdd..81f62223569 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,8 @@ import org.springframework.util.StringUtils; import org.springframework.web.util.WebUtils; /** - * Implementation of MethodNameResolver which supports several strategies for - * mapping parameter values to the names of methods to invoke. + * Implementation of {@link MethodNameResolver} which supports several strategies + * for mapping parameter values to the names of methods to invoke. * *

The simplest strategy looks for a specific named parameter, whose value is * considered the name of the method to invoke. The name of the parameter may be @@ -163,8 +163,7 @@ public class ParameterMethodNameResolver implements MethodNameResolver { // Check parameter names where the very existence of each parameter // means that a method of the same name should be invoked, if any. if (this.methodParamNames != null) { - for (int i = 0; i < this.methodParamNames.length; ++i) { - String candidate = this.methodParamNames[i]; + for (String candidate : this.methodParamNames) { if (WebUtils.hasSubmitParameter(request, candidate)) { methodName = candidate; if (logger.isDebugEnabled()) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/PropertiesMethodNameResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/PropertiesMethodNameResolver.java index 09831f00e9b..62759f96e64 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/PropertiesMethodNameResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/PropertiesMethodNameResolver.java @@ -1,12 +1,12 @@ /* - * Copyright 2002-2005 the original author or authors. - * + * Copyright 2002-2008 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,7 +16,7 @@ package org.springframework.web.servlet.mvc.multiaction; -import java.util.Iterator; +import java.util.Enumeration; import java.util.Properties; import org.springframework.beans.factory.InitializingBean; @@ -25,7 +25,7 @@ import org.springframework.util.Assert; import org.springframework.util.PathMatcher; /** - * The most flexible out-of-the-box implementation of the MethodNameResolver + * The most flexible out-of-the-box implementation of the {@link MethodNameResolver} * interface. Uses java.util.Properties to define the mapping * between the URL of incoming requests and the corresponding method name. * Such properties can be held in an XML document. @@ -85,8 +85,9 @@ public class PropertiesMethodNameResolver extends AbstractUrlMethodNameResolver if (methodName != null) { return methodName; } - for (Iterator it = this.mappings.keySet().iterator(); it.hasNext();) { - String registeredPath = (String) it.next(); + Enumeration propNames = this.mappings.propertyNames(); + while (propNames.hasMoreElements()) { + String registeredPath = (String) propNames.nextElement(); if (this.pathMatcher.match(registeredPath, urlPath)) { return (String) this.mappings.get(registeredPath); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerBeanNameHandlerMapping.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerBeanNameHandlerMapping.java index 97b405d3beb..357834ca292 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerBeanNameHandlerMapping.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerBeanNameHandlerMapping.java @@ -66,11 +66,11 @@ public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandl @Override protected String[] buildUrlsForHandler(String beanName, Class beanClass) { - List urls = new ArrayList(); + List urls = new ArrayList(); urls.add(generatePathMapping(beanName)); String[] aliases = getApplicationContext().getAliases(beanName); - for (int i = 0; i < aliases.length; i++) { - urls.add(generatePathMapping(aliases[i])); + for (String alias : aliases) { + urls.add(generatePathMapping(alias)); } return StringUtils.toStringArray(urls); } @@ -80,7 +80,7 @@ public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandl */ protected String generatePathMapping(String beanName) { String name = (beanName.startsWith("/") ? beanName : "/" + beanName); - StringBuffer path = new StringBuffer(); + StringBuilder path = new StringBuilder(); if (!name.startsWith(this.urlPrefix)) { path.append(this.urlPrefix); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java index 1f7a0ddb34c..aea281b3ab3 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java @@ -134,7 +134,7 @@ public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHand * @return the URL path mappings for the given controller */ protected String[] generatePathMappings(Class beanClass) { - StringBuffer pathMapping = buildPathPrefix(beanClass); + StringBuilder pathMapping = buildPathPrefix(beanClass); String className = ClassUtils.getShortName(beanClass); String path = (className.endsWith(CONTROLLER_SUFFIX) ? className.substring(0, className.indexOf(CONTROLLER_SUFFIX)) : className); @@ -159,8 +159,8 @@ public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHand * @param beanClass the controller bean class to generate a mapping for * @return the path prefix, potentially including subpackage names as path elements */ - private StringBuffer buildPathPrefix(Class beanClass) { - StringBuffer pathMapping = new StringBuffer(); + private StringBuilder buildPathPrefix(Class beanClass) { + StringBuilder pathMapping = new StringBuilder(); if (this.pathPrefix != null) { pathMapping.append(this.pathPrefix); pathMapping.append("/"); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/BindStatus.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/BindStatus.java index c3ceeff6e62..123632c6b31 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/BindStatus.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/BindStatus.java @@ -325,7 +325,7 @@ public class BindStatus { @Override public String toString() { - StringBuffer sb = new StringBuffer("BindStatus: "); + StringBuilder sb = new StringBuilder("BindStatus: "); sb.append("expression=[").append(this.expression).append("]; "); sb.append("value=[").append(this.value).append("]"); if (isError()) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java index 134e26952c9..1fc7a5f36a5 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,10 @@ package org.springframework.web.servlet.support; import java.util.Locale; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.jstl.core.Config; -import org.springframework.util.ClassUtils; - /** * JSP-aware (and JSTL-aware) subclass of RequestContext, allowing for * population of the context from a javax.servlet.jsp.PageContext. @@ -57,7 +54,7 @@ public class JspAwareRequestContext extends RequestContext { * @param model the model attributes for the current view * (can be null, using the request attributes for Errors retrieval) */ - public JspAwareRequestContext(PageContext pageContext, Map model) { + public JspAwareRequestContext(PageContext pageContext, Map model) { initContext(pageContext, model); } @@ -68,7 +65,7 @@ public class JspAwareRequestContext extends RequestContext { * @param model the model attributes for the current view * (can be null, using the request attributes for Errors retrieval) */ - protected void initContext(PageContext pageContext, Map model) { + protected void initContext(PageContext pageContext, Map model) { if (!(pageContext.getRequest() instanceof HttpServletRequest)) { throw new IllegalArgumentException("RequestContext only supports HTTP requests"); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java index dd3857fd4d3..2256c5c15ea 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContext.java @@ -91,7 +91,7 @@ public class RequestContext { private HttpServletRequest request; - private Map model; + private Map model; private WebApplicationContext webApplicationContext; @@ -103,7 +103,7 @@ public class RequestContext { private UrlPathHelper urlPathHelper; - private Map errorsMap; + private Map errorsMap; /** @@ -153,7 +153,7 @@ public class RequestContext { * @see org.springframework.web.servlet.DispatcherServlet * @see #RequestContext(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext, Map) */ - public RequestContext(HttpServletRequest request, Map model) { + public RequestContext(HttpServletRequest request, Map model) { initContext(request, null, model); } @@ -172,7 +172,7 @@ public class RequestContext { * @see org.springframework.web.context.WebApplicationContext * @see org.springframework.web.servlet.DispatcherServlet */ - public RequestContext(HttpServletRequest request, ServletContext servletContext, Map model) { + public RequestContext(HttpServletRequest request, ServletContext servletContext, Map model) { initContext(request, servletContext, model); } @@ -199,7 +199,7 @@ public class RequestContext { * @see org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_ATTRIBUTE * @see org.springframework.web.servlet.DispatcherServlet#THEME_RESOLVER_ATTRIBUTE */ - protected void initContext(HttpServletRequest request, ServletContext servletContext, Map model) { + protected void initContext(HttpServletRequest request, ServletContext servletContext, Map model) { this.request = request; this.model = model; @@ -326,7 +326,7 @@ public class RequestContext { * @see org.springframework.web.util.WebUtils#isDefaultHtmlEscape */ public void setDefaultHtmlEscape(boolean defaultHtmlEscape) { - this.defaultHtmlEscape = Boolean.valueOf(defaultHtmlEscape); + this.defaultHtmlEscape = defaultHtmlEscape; } /** @@ -334,7 +334,7 @@ public class RequestContext { * Falls back to false in case of no explicit default given. */ public boolean isDefaultHtmlEscape() { - return (this.defaultHtmlEscape != null && this.defaultHtmlEscape.booleanValue()); + return (this.defaultHtmlEscape != null && this.defaultHtmlEscape); } /** @@ -640,16 +640,13 @@ public class RequestContext { */ public Errors getErrors(String name, boolean htmlEscape) { if (this.errorsMap == null) { - this.errorsMap = new HashMap(); + this.errorsMap = new HashMap(); } - Errors errors = (Errors) this.errorsMap.get(name); + Errors errors = this.errorsMap.get(name); boolean put = false; if (errors == null) { errors = (Errors) getModelObject(BindingResult.MODEL_KEY_PREFIX + name); // Check old BindException prefix for backwards compatibility. - if (errors == null) { - errors = (Errors) getModelObject(BindException.ERROR_KEY_PREFIX + name); - } if (errors instanceof BindException) { errors = ((BindException) errors).getBindingResult(); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java index b5cf436e9f5..b906f5bd142 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu /** Whether we should cache views, once resolved */ private boolean cache = true; - /** Map from view name to View instance */ - private final Map viewCache = new HashMap(); + /** Map from view key to View instance */ + private final Map viewCache = new HashMap(); /** @@ -72,7 +72,7 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu else { Object cacheKey = getCacheKey(viewName, locale); synchronized (this.viewCache) { - View view = (View) this.viewCache.get(cacheKey); + View view = this.viewCache.get(cacheKey); if (view == null) { // Ask the subclass to create the View object. view = createView(viewName, locale); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractTemplateView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractTemplateView.java index 1180b2268b8..39268daf51f 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractTemplateView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractTemplateView.java @@ -114,7 +114,7 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView { @Override protected final void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { if (this.exposeRequestAttributes) { for (Enumeration en = request.getAttributeNames(); en.hasMoreElements();) { @@ -191,6 +191,6 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView { * @throws Exception if rendering failed */ protected abstract void renderMergedTemplateModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractUrlBasedView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractUrlBasedView.java index 4b4caedc0d4..8c98feeab9b 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractUrlBasedView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractUrlBasedView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,7 +78,7 @@ public abstract class AbstractUrlBasedView extends AbstractView implements Initi @Override public String toString() { - StringBuffer sb = new StringBuffer(super.toString()); + StringBuilder sb = new StringBuilder(super.toString()); sb.append("; URL [").append(getUrl()).append("]"); return sb.toString(); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractView.java index 83b62a1d579..25074f97411 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/AbstractView.java @@ -20,7 +20,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; @@ -69,7 +68,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement private String requestContextAttribute; /** Map of static attributes, keyed by attribute name (String) */ - private final Map staticAttributes = new HashMap(); + private final Map staticAttributes = new HashMap(); /** @@ -178,17 +177,10 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement *

Can be populated with a "map" or "props" element in XML bean definitions. * @param attributes Map with name Strings as keys and attribute objects as values */ - public void setAttributesMap(Map attributes) { + public void setAttributesMap(Map attributes) { if (attributes != null) { - Iterator it = attributes.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - Object key = entry.getKey(); - if (!(key instanceof String)) { - throw new IllegalArgumentException( - "Invalid attribute key [" + key + "]: only Strings allowed"); - } - addStaticAttribute((String) key, entry.getValue()); + for (Map.Entry entry : attributes.entrySet()) { + addStaticAttribute(entry.getKey(), entry.getValue()); } } } @@ -200,7 +192,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement * "attributesMap[myKey]". This is particularly useful for * adding or overriding entries in child view definitions. */ - public Map getAttributesMap() { + public Map getAttributesMap() { return this.staticAttributes; } @@ -235,14 +227,15 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement * Delegates to renderMergedOutputModel for the actual rendering. * @see #renderMergedOutputModel */ - public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isTraceEnabled()) { logger.trace("Rendering view with name '" + this.beanName + "' with model " + model + " and static attributes " + this.staticAttributes); } // Consolidate static and dynamic model attributes. - Map mergedModel = new HashMap(this.staticAttributes.size() + (model != null ? model.size() : 0)); + Map mergedModel = + new HashMap(this.staticAttributes.size() + (model != null ? model.size() : 0)); mergedModel.putAll(this.staticAttributes); if (model != null) { mergedModel.putAll(model); @@ -268,7 +261,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement * @see #setRequestContextAttribute * @see org.springframework.web.servlet.support.RequestContext */ - protected RequestContext createRequestContext(HttpServletRequest request, Map model) { + protected RequestContext createRequestContext(HttpServletRequest request, Map model) { return new RequestContext(request, getServletContext(), model); } @@ -313,7 +306,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement * @throws Exception if rendering failed */ protected abstract void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; /** @@ -323,15 +316,9 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement * @param model Map of model objects to expose * @param request current HTTP request */ - protected void exposeModelAsRequestAttributes(Map model, HttpServletRequest request) throws Exception { - Iterator it = model.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - if (!(entry.getKey() instanceof String)) { - throw new IllegalArgumentException( - "Invalid key [" + entry.getKey() + "] in model Map: only Strings allowed as model keys"); - } - String modelName = (String) entry.getKey(); + protected void exposeModelAsRequestAttributes(Map model, HttpServletRequest request) throws Exception { + for (Map.Entry entry : model.entrySet()) { + String modelName = entry.getKey(); Object modelValue = entry.getValue(); if (modelValue != null) { request.setAttribute(modelName, modelValue); @@ -379,7 +366,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement @Override public String toString() { - StringBuffer sb = new StringBuffer(getClass().getName()); + StringBuilder sb = new StringBuilder(getClass().getName()); if (getBeanName() != null) { sb.append(": name '").append(getBeanName()).append("'"); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/InternalResourceView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/InternalResourceView.java index 1fffbcd1f6c..072cbdf4251 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/InternalResourceView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/InternalResourceView.java @@ -128,7 +128,7 @@ public class InternalResourceView extends AbstractUrlBasedView { * feature exists for Servlet 2.3 containers and misbehaving 2.4 containers. */ public void setExposeForwardAttributes(boolean exposeForwardAttributes) { - this.exposeForwardAttributes = Boolean.valueOf(exposeForwardAttributes); + this.exposeForwardAttributes = exposeForwardAttributes; } /** @@ -200,7 +200,7 @@ public class InternalResourceView extends AbstractUrlBasedView { */ @Override protected void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Determine which request handle to expose to the RequestDispatcher. HttpServletRequest requestToExpose = getRequestToExpose(request); @@ -331,7 +331,7 @@ public class InternalResourceView extends AbstractUrlBasedView { * @see org.springframework.web.util.WebUtils#exposeForwardRequestAttributes */ protected void exposeForwardRequestAttributes(HttpServletRequest request) { - if (this.exposeForwardAttributes != null && this.exposeForwardAttributes.booleanValue()) { + if (this.exposeForwardAttributes != null && this.exposeForwardAttributes) { WebUtils.exposeForwardRequestAttributes(request); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java index 386759454d3..d033186b6b5 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java @@ -26,7 +26,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -191,10 +190,11 @@ public class RedirectView extends AbstractUrlBasedView { */ @Override protected void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws IOException { + Map model, HttpServletRequest request, HttpServletResponse response) + throws IOException { // Prepare target URL. - StringBuffer targetUrl = new StringBuffer(); + StringBuilder targetUrl = new StringBuilder(); if (this.contextRelative && getUrl().startsWith("/")) { // Do not apply context path to relative URLs. targetUrl.append(request.getContextPath()); @@ -217,13 +217,13 @@ public class RedirectView extends AbstractUrlBasedView { /** * Append query properties to the redirect URL. * Stringifies, URL-encodes and formats model attributes as query properties. - * @param targetUrl the StringBuffer to append the properties to + * @param targetUrl the StringBuilder to append the properties to * @param model Map that contains model attributes * @param encodingScheme the encoding scheme to use * @throws UnsupportedEncodingException if string encoding failed * @see #queryProperties */ - protected void appendQueryProperties(StringBuffer targetUrl, Map model, String encodingScheme) + protected void appendQueryProperties(StringBuilder targetUrl, Map model, String encodingScheme) throws UnsupportedEncodingException { // Extract anchor fragment, if any. @@ -236,10 +236,7 @@ public class RedirectView extends AbstractUrlBasedView { // If there aren't already some parameters, we need a "?". boolean first = (getUrl().indexOf('?') < 0); - Iterator entries = queryProperties(model).entrySet().iterator(); - while (entries.hasNext()) { - Map.Entry entry = (Map.Entry) entries.next(); - String key = entry.getKey().toString(); + for (Map.Entry entry : queryProperties(model).entrySet()) { Object rawValue = entry.getValue(); Iterator valueIter = null; if (rawValue != null && rawValue.getClass().isArray()) { @@ -260,7 +257,7 @@ public class RedirectView extends AbstractUrlBasedView { else { targetUrl.append('&'); } - String encodedKey = urlEncode(key, encodingScheme); + String encodedKey = urlEncode(entry.getKey(), encodingScheme); String encodedValue = (value != null ? urlEncode(value.toString(), encodingScheme) : ""); targetUrl.append(encodedKey).append('=').append(encodedValue); } @@ -282,14 +279,11 @@ public class RedirectView extends AbstractUrlBasedView { * @return the filtered Map of eligible query properties * @see #isEligibleProperty(String, Object) */ - protected Map queryProperties(Map model) { - Map result = new LinkedHashMap(); - for (Iterator it = model.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String key = entry.getKey().toString(); - Object value = entry.getValue(); - if (isEligibleProperty(key, value)) { - result.put(key, value); + protected Map queryProperties(Map model) { + Map result = new LinkedHashMap(); + for (Map.Entry entry : model.entrySet()) { + if (isEligibleProperty(entry.getKey(), entry.getValue())) { + result.put(entry.getKey(), entry.getValue()); } } return result; @@ -332,8 +326,7 @@ public class RedirectView extends AbstractUrlBasedView { if (coll.isEmpty()) { return false; } - for (Iterator it = coll.iterator(); it.hasNext();) { - Object element = it.next(); + for (Object element : coll) { if (!isEligibleValue(element)) { return false; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java index ebc1d1fe647..3d8670d6de4 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,10 +78,12 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl private Locale[] localesToInitialize; /* Locale -> BeanFactory */ - private final Map localeCache = new HashMap(); + private final Map localeCache = + new HashMap(); /* List of ResourceBundle -> BeanFactory */ - private final Map bundleCache = new HashMap(); + private final Map, ConfigurableApplicationContext> bundleCache = + new HashMap, ConfigurableApplicationContext>(); public void setOrder(int order) { @@ -177,8 +179,8 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl @Override protected void initApplicationContext() throws BeansException { if (this.localesToInitialize != null) { - for (int i = 0; i < this.localesToInitialize.length; i++) { - initFactory(this.localesToInitialize[i]); + for (Locale locale : this.localesToInitialize) { + initFactory(locale); } } } @@ -187,7 +189,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl protected View loadView(String viewName, Locale locale) throws Exception { BeanFactory factory = initFactory(locale); try { - return (View) factory.getBean(viewName, View.class); + return factory.getBean(viewName, View.class); } catch (NoSuchBeanDefinitionException ex) { // to allow for ViewResolver chaining @@ -207,23 +209,23 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl // Try to find cached factory for Locale: // Have we already encountered that Locale before? if (isCache()) { - BeanFactory cachedFactory = (BeanFactory) this.localeCache.get(locale); + BeanFactory cachedFactory = this.localeCache.get(locale); if (cachedFactory != null) { return cachedFactory; } } // Build list of ResourceBundle references for Locale. - List bundles = new LinkedList(); - for (int i = 0; i < this.basenames.length; i++) { - ResourceBundle bundle = getBundle(this.basenames[i], locale); + List bundles = new LinkedList(); + for (String basename : this.basenames) { + ResourceBundle bundle = getBundle(basename, locale); bundles.add(bundle); } // Try to find cached factory for ResourceBundle list: // even if Locale was different, same bundles might have been found. if (isCache()) { - BeanFactory cachedFactory = (BeanFactory) this.bundleCache.get(bundles); + BeanFactory cachedFactory = this.bundleCache.get(bundles); if (cachedFactory != null) { this.localeCache.put(locale, cachedFactory); return cachedFactory; @@ -238,8 +240,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl // Load bean definitions from resource bundle. PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(factory); reader.setDefaultParentBean(this.defaultParentView); - for (int i = 0; i < bundles.size(); i++) { - ResourceBundle bundle = (ResourceBundle) bundles.get(i); + for (ResourceBundle bundle : bundles) { reader.registerBeanDefinitions(bundle); } @@ -271,8 +272,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl * Close the bundle View factories on context shutdown. */ public void destroy() throws BeansException { - for (Iterator it = this.bundleCache.values().iterator(); it.hasNext();) { - ConfigurableApplicationContext factory = (ConfigurableApplicationContext) it.next(); + for (ConfigurableApplicationContext factory : this.bundleCache.values()) { factory.close(); } this.localeCache.clear(); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java index 9832aa60987..ddc0831afa5 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.util.Properties; import org.springframework.beans.BeanUtils; import org.springframework.core.Ordered; +import org.springframework.util.CollectionUtils; import org.springframework.util.PatternMatchUtils; import org.springframework.web.servlet.View; @@ -115,7 +116,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements private int order = Integer.MAX_VALUE; /** Map of static attributes, keyed by attribute name (String) */ - private final Map staticAttributes = new HashMap(); + private final Map staticAttributes = new HashMap(); /** @@ -271,7 +272,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements * @see AbstractView#setAttributes */ public void setAttributes(Properties props) { - setAttributesMap(props); + CollectionUtils.mergePropertiesIntoMap(props, this.staticAttributes); } /** @@ -281,7 +282,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements * @param attributes Map with name Strings as keys and attribute objects as values * @see AbstractView#setAttributesMap */ - public void setAttributesMap(Map attributes) { + public void setAttributesMap(Map attributes) { if (attributes != null) { this.staticAttributes.putAll(attributes); } @@ -294,7 +295,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements * "attributesMap[myKey]". This is particularly useful for * adding or overriding entries in child view definitions. */ - public Map getAttributesMap() { + public Map getAttributesMap() { return this.staticAttributes; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractExcelView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractExcelView.java index 0cde8e7be6c..c40cefe5ae7 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractExcelView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractExcelView.java @@ -18,12 +18,12 @@ package org.springframework.web.servlet.view.document; import java.util.Locale; import java.util.Map; - import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -55,9 +55,9 @@ import org.springframework.web.servlet.view.AbstractView; * *

As an example, you can try this snippet: * - *

+ * 
  * protected void buildExcelDocument(
- *     Map model, HSSFWorkbook workbook,
+ *     Map<String, Object> model, HSSFWorkbook workbook,
  *     HttpServletRequest request, HttpServletResponse response) {
  *
  *   // Go to the first sheet.
@@ -131,7 +131,7 @@ public abstract class AbstractExcelView extends AbstractView {
 	 */
 	@Override
 	protected final void renderMergedOutputModel(
-			Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
+			Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
 
 		HSSFWorkbook workbook;
 		if (this.url != null) {
@@ -185,7 +185,7 @@ public abstract class AbstractExcelView extends AbstractView {
 	 * @param response in case we need to set cookies. Shouldn't write to it.
 	 */
 	protected abstract void buildExcelDocument(
-			Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
+			Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
 			throws Exception;
 
 
@@ -217,7 +217,7 @@ public abstract class AbstractExcelView extends AbstractView {
 	 */
 	protected void setText(HSSFCell cell, String text) {
 		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
-		cell.setCellValue(text);
+		cell.setCellValue(new HSSFRichTextString(text));
 	}
 
 }
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractJExcelView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractJExcelView.java
index 16755145a0d..2a920bc6349 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractJExcelView.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractJExcelView.java
@@ -56,16 +56,18 @@ import org.springframework.web.servlet.view.AbstractView;
  * 
  * 

As an example, you can try this snippet: * - *

- * protected void buildExcelDocument(Map model, WritableWorkbook workbook, HttpServletRequest request,
- * 		HttpServletResponse response) {
- * 	if (workbook.getNumberOfSheets() == 0) {
- * 		workbook.createSheet("Spring", 0);
- * 	}
+ * 
+ * protected void buildExcelDocument(
+ *      Map<String, Object> model, WritableWorkbook workbook,
+ * 		HttpServletRequest request, HttpServletResponse response) {
+ *
+ * 	 if (workbook.getNumberOfSheets() == 0) {
+ * 	     workbook.createSheet("Spring", 0);
+ *   }
  * 
- * 	WritableSheet sheet = workbook.getSheet("Spring");
- * 	Label label = new Label(0, 0, "This is a nice label");
- * 	sheet.addCell(label);
+ * 	 WritableSheet sheet = workbook.getSheet("Spring");
+ * 	 Label label = new Label(0, 0, "This is a nice label");
+ * 	 sheet.addCell(label);
  * }
* * The use of this view is close to the AbstractExcelView class, @@ -117,7 +119,7 @@ public abstract class AbstractJExcelView extends AbstractView { */ @Override protected final void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Set the content type and get the output stream. response.setContentType(getContentType()); @@ -171,8 +173,7 @@ public abstract class AbstractJExcelView extends AbstractView { * @param response in case we need to set cookies. Shouldn't write to it. * @throws Exception in case of failure */ - protected abstract void buildExcelDocument( - Map model, WritableWorkbook workbook, HttpServletRequest request, HttpServletResponse response) - throws Exception; + protected abstract void buildExcelDocument(Map model, WritableWorkbook workbook, + HttpServletRequest request, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfStamperView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfStamperView.java index 9c291eeae16..79883878ccf 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfStamperView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfStamperView.java @@ -41,9 +41,9 @@ import org.springframework.web.servlet.view.AbstractUrlBasedView; */ public abstract class AbstractPdfStamperView extends AbstractUrlBasedView { - public AbstractPdfStamperView(){ - setContentType("application/pdf"); - } + public AbstractPdfStamperView(){ + setContentType("application/pdf"); + } @Override @@ -51,21 +51,21 @@ public abstract class AbstractPdfStamperView extends AbstractUrlBasedView { return true; } - @Override - protected final void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception{ + @Override + protected final void renderMergedOutputModel( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // IE workaround: write into byte array first. ByteArrayOutputStream baos = createTemporaryOutputStream(); - PdfReader reader = readPdfResource(); - PdfStamper stamper = new PdfStamper(reader, baos); - mergePdfDocument(model, stamper, request, response); - stamper.close(); + PdfReader reader = readPdfResource(); + PdfStamper stamper = new PdfStamper(reader, baos); + mergePdfDocument(model, stamper, request, response); + stamper.close(); // Flush to HTTP response. writeToResponse(response, baos); - } + } /** * Read the raw PDF resource into an iText PdfReader. @@ -79,34 +79,33 @@ public abstract class AbstractPdfStamperView extends AbstractUrlBasedView { return new PdfReader(getApplicationContext().getResource(getUrl()).getInputStream()); } - /** + /** * Subclasses must implement this method to merge the PDF form * with the given model data. - *

This is where you are able to set values on the AcroForm. - * An example of what can be done at this level is: + *

This is where you are able to set values on the AcroForm. + * An example of what can be done at this level is: *

-   * // get the form from the document
-   * AcroFields form = stamper.getAcroFields();
-   *
-   * // set some values on the form
-   * form.setField("field1", "value1");
-   * form.setField("field2", "Vvlue2");
+	 * // get the form from the document
+	 * AcroFields form = stamper.getAcroFields();
 	 *
-   * // set the disposition and filename
-   * response.setHeader("Content-disposition", "attachment; FILENAME=someName.pdf");
+ * // set some values on the form + * form.setField("field1", "value1"); + * form.setField("field2", "Vvlue2"); + * + * // set the disposition and filename + * response.setHeader("Content-disposition", "attachment; FILENAME=someName.pdf");
*

Note that the passed-in HTTP response is just supposed to be used * for setting cookies or other HTTP headers. The built PDF document itself * will automatically get written to the response after this method returns. * @param model the model Map - * @param stamper the PdfStamper instance that will contain the AcroFields. + * @param stamper the PdfStamper instance that will contain the AcroFields. * You may also customize this PdfStamper instance according to your needs, * e.g. setting the "formFlattening" property. * @param request in case we need locale etc. Shouldn't look at attributes. * @param response in case we need to set cookies. Shouldn't write to it. * @throws Exception any exception that occured during document building - */ - protected abstract void mergePdfDocument( - Map model, PdfStamper stamper, HttpServletRequest request, HttpServletResponse response) - throws Exception; + */ + protected abstract void mergePdfDocument(Map model, PdfStamper stamper, + HttpServletRequest request, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfView.java index 568c32bb12e..1f4fd24a9bd 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/document/AbstractPdfView.java @@ -19,7 +19,6 @@ package org.springframework.web.servlet.view.document; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -63,7 +62,7 @@ public abstract class AbstractPdfView extends AbstractView { @Override protected final void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // IE workaround: write into byte array first. ByteArrayOutputStream baos = createTemporaryOutputStream(); @@ -120,7 +119,7 @@ public abstract class AbstractPdfView extends AbstractView { * @see com.lowagie.text.pdf.PdfWriter#setViewerPreferences * @see #getViewerPreferences() */ - protected void prepareWriter(Map model, PdfWriter writer, HttpServletRequest request) + protected void prepareWriter(Map model, PdfWriter writer, HttpServletRequest request) throws DocumentException { writer.setViewerPreferences(getViewerPreferences()); @@ -137,7 +136,7 @@ public abstract class AbstractPdfView extends AbstractView { * @see com.lowagie.text.pdf.PdfWriter#PageLayoutSinglePage */ protected int getViewerPreferences() { - return PdfWriter.AllowPrinting | PdfWriter.PageLayoutSinglePage; + return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage; } /** @@ -158,7 +157,7 @@ public abstract class AbstractPdfView extends AbstractView { * @see com.lowagie.text.Document#addCreationDate * @see com.lowagie.text.Document#addHeader */ - protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) { + protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) { } /** @@ -177,9 +176,7 @@ public abstract class AbstractPdfView extends AbstractView { * @see com.lowagie.text.Document#open() * @see com.lowagie.text.Document#close() */ - protected abstract void buildPdfDocument( - Map model, Document document, PdfWriter writer, - HttpServletRequest request, HttpServletResponse response) - throws Exception; + protected abstract void buildPdfDocument(Map model, Document document, PdfWriter writer, + HttpServletRequest request, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractAtomFeedView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractAtomFeedView.java index 659f3251fb6..86a99ae5f16 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractAtomFeedView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractAtomFeedView.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,16 +26,19 @@ import com.sun.syndication.feed.atom.Entry; import com.sun.syndication.feed.atom.Feed; /** - * Abstract superclass for Atom Feed views, using java.net's ROME package. - * Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a - * template. + * Abstract superclass for Atom Feed views, using java.net's + * ROME package. * - *

Main entry points are the {@link #buildFeedMetadata(Map, WireFeed, HttpServletRequest)} and + *

Application-specific view classes will extend this class. + * The view will be held in the subclass itself, not in a template. + * + *

Main entry points are the {@link #buildFeedMetadata(Map, WireFeed, HttpServletRequest)} and * {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)}. * - * @author Jettro Coenradie - * @author Sergio Bossa + *

Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype! + * * @author Arjen Poutsma + * @author Juergen Hoeller * @since 3.0 * @see #buildFeedMetadata(Map, WireFeed, HttpServletRequest) * @see #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse) @@ -46,16 +49,14 @@ public abstract class AbstractAtomFeedView extends AbstractFeedView { private String feedType = DEFAULT_FEED_TYPE; - /** Sets the appropriate content type: "application/atom+xml". */ + public AbstractAtomFeedView() { setContentType("application/atom+xml"); } /** * Sets the Rome feed type to use. - *

- * Defaults to Atom 1.0. - * + *

Defaults to Atom 1.0. * @see Feed#setFeedType(String) * @see #DEFAULT_FEED_TYPE */ @@ -64,42 +65,41 @@ public abstract class AbstractAtomFeedView extends AbstractFeedView { } /** - * Create a new feed to hold the entries. - *

- * By default returns an Atom 1.0 feed, but the subclass can specify any Feed. - * - * @return the newly created Feed instance + * Create a new Feed instance to hold the entries. + *

By default returns an Atom 1.0 feed, but the subclass can specify any Feed. * @see #setFeedType(String) - * @see com.sun.syndication.feed.atom.Feed#Feed(String) */ @Override protected Feed newFeed() { - return new Feed(feedType); + return new Feed(this.feedType); } - /** Invokes {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)} to get a list of feed entries. */ + /** + * Invokes {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)} + * to get a list of feed entries. + */ @Override - protected final void buildFeedEntries(Map model, - Feed feed, - HttpServletRequest request, - HttpServletResponse response) throws Exception { + protected final void buildFeedEntries(Map model, Feed feed, + HttpServletRequest request, HttpServletResponse response) throws Exception { + List entries = buildFeedEntries(model, request, response); feed.setEntries(entries); } /** * Subclasses must implement this method to build feed entries, given the model. - *

- * Note that the passed-in HTTP response is just supposed to be used for setting cookies or other HTTP headers. The - * built feed itself will automatically get written to the response after this method returns. - * + *

Note that the passed-in HTTP response is just supposed to be used for + * setting cookies or other HTTP headers. The built feed itself will automatically + * get written to the response after this method returns. * @param model the model Map - * @param request in case we need locale etc. Shouldn't look at attributes. + * @param request in case we need locale etc. Shouldn't look at attributes. * @param response in case we need to set cookies. Shouldn't write to it. * @return the feed entries to be added to the feed * @throws Exception any exception that occured during document building * @see Entry */ - protected abstract List buildFeedEntries(Map model, HttpServletRequest request, HttpServletResponse response) + protected abstract List buildFeedEntries( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; + } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractFeedView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractFeedView.java index 4f754ccc8f5..b2a1563570e 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractFeedView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractFeedView.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,22 +29,27 @@ import org.springframework.util.StringUtils; import org.springframework.web.servlet.view.AbstractView; /** - * Abstract base class for Atom and RSS Feed views, using java.net's ROME - * package. TypApplication-specific view classes will typically extends either {@link AbstractRssFeedView} or {@link - * AbstractAtomFeedView}, not this class. + * Abstract base class for Atom and RSS Feed views, using java.net's + * ROME package. + * + *

Application-specific view classes will typically extend from either + * {@link AbstractRssFeedView} or {@link AbstractAtomFeedView} instead of from this class. + * + *

Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype! * - * @author Jettro Coenradie - * @author Sergio Bossa * @author Arjen Poutsma + * @author Juergen Hoeller + * @since 3.0 * @see AbstractRssFeedView * @see AbstractAtomFeedView - * @since 3.0 */ public abstract class AbstractFeedView extends AbstractView { @Override - protected final void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) + protected final void renderMergedOutputModel( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + T wireFeed = newFeed(); buildFeedMetadata(model, wireFeed, request); buildFeedEntries(model, wireFeed, request, response); @@ -62,40 +67,33 @@ public abstract class AbstractFeedView extends AbstractView /** * Create a new feed to hold the entries. - * * @return the newly created Feed instance */ protected abstract T newFeed(); /** * Populate the feed metadata (title, link, description, etc.). - *

- * Default is an empty implementation. Subclasses can override this method to add meta fields such as title, link - * description, etc. - * - * @param model the model, in case meta information must be populated from it - * @param feed the feed being populated + *

Default is an empty implementation. Subclasses can override this method + * to add meta fields such as title, link description, etc. + * @param model the model, in case meta information must be populated from it + * @param feed the feed being populated * @param request in case we need locale etc. Shouldn't look at attributes. */ - protected void buildFeedMetadata(Map model, T feed, HttpServletRequest request) { + protected void buildFeedMetadata(Map model, T feed, HttpServletRequest request) { } /** * Subclasses must implement this method to build feed entries, given the model. - *

- * Note that the passed-in HTTP response is just supposed to be used for setting cookies or other HTTP headers. The - * built feed itself will automatically get written to the response after this method returns. - * - * @param model the model Map - * @param feed the feed to add entries to - * @param request in case we need locale etc. Shouldn't look at attributes. + *

Note that the passed-in HTTP response is just supposed to be used for + * setting cookies or other HTTP headers. The built feed itself will automatically + * get written to the response after this method returns. + * @param model the model Map + * @param feed the feed to add entries to + * @param request in case we need locale etc. Shouldn't look at attributes. * @param response in case we need to set cookies. Shouldn't write to it. * @throws Exception any exception that occured during building */ - protected abstract void buildFeedEntries(Map model, - T feed, - HttpServletRequest request, - HttpServletResponse response) throws Exception; - + protected abstract void buildFeedEntries(Map model, T feed, + HttpServletRequest request, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractRssFeedView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractRssFeedView.java index 192e93a34ff..8c180824513 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractRssFeedView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/feed/AbstractRssFeedView.java @@ -26,56 +26,55 @@ import com.sun.syndication.feed.rss.Channel; import com.sun.syndication.feed.rss.Item; /** - * Abstract superclass for RSS Feed views, using java.net's ROME package. - * Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a - * template. + * Abstract superclass for RSS Feed views, using java.net's + * ROME package. * - *

Main entry points are the {@link #buildFeedMetadata(Map, WireFeed , HttpServletRequest)} and {@link - * #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)}. + *

Application-specific view classes will extend this class. + * The view will be held in the subclass itself, not in a template. + * + *

Main entry points are the {@link #buildFeedMetadata(Map, WireFeed , HttpServletRequest)} + * and {@link #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)}. + * + *

Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype! * - * @author Jettro Coenradie - * @author Sergio Bossa * @author Arjen Poutsma + * @author Juergen Hoeller + * @since 3.0 * @see #buildFeedMetadata(Map, WireFeed , HttpServletRequest) * @see #buildFeedItems(Map, HttpServletRequest, HttpServletResponse) - * @since 3.0 */ public abstract class AbstractRssFeedView extends AbstractFeedView { - /** Sets the appropriate content type: "application/rss+xml". */ - protected AbstractRssFeedView() { + public AbstractRssFeedView() { setContentType("application/rss+xml"); } /** - * Create a new channel to hold the entries. - * - *

By default returns an RSS 2.0 channel, but the subclass can specify any channel. - * - * @return the newly created Feed instance - * @see Channel#Channel(String) + * Create a new Channel instance to hold the entries. + *

By default returns an RSS 2.0 channel, but the subclass can specify any channel. */ @Override protected Channel newFeed() { return new Channel("rss_2.0"); } - /** Invokes {@link #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)} to get a list of feed items. */ + /** + * Invokes {@link #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)} + * to get a list of feed items. + */ @Override - protected final void buildFeedEntries(Map model, - Channel channel, - HttpServletRequest request, - HttpServletResponse response) throws Exception { + protected final void buildFeedEntries(Map model, Channel channel, + HttpServletRequest request, HttpServletResponse response) throws Exception { + List items = buildFeedItems(model, request, response); channel.setItems(items); } /** * Subclasses must implement this method to build feed items, given the model. - * - *

Note that the passed-in HTTP response is just supposed to be used for setting cookies or other HTTP headers. The - * built feed itself will automatically get written to the response after this method returns. - * + *

Note that the passed-in HTTP response is just supposed to be used for + * setting cookies or other HTTP headers. The built feed itself will automatically + * get written to the response after this method returns. * @param model the model Map * @param request in case we need locale etc. Shouldn't look at attributes. * @param response in case we need to set cookies. Shouldn't write to it. @@ -83,6 +82,8 @@ public abstract class AbstractRssFeedView extends AbstractFeedView { * @throws Exception any exception that occured during document building * @see Item */ - protected abstract List buildFeedItems(Map model, HttpServletRequest request, HttpServletResponse response) + protected abstract List buildFeedItems( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception; + } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/freemarker/FreeMarkerView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/freemarker/FreeMarkerView.java index 23cb487ac28..8231495e34a 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/freemarker/FreeMarkerView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/freemarker/FreeMarkerView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ package org.springframework.web.servlet.view.freemarker; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; +import java.util.HashSet; import java.util.Locale; import java.util.Map; - import javax.servlet.GenericServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @@ -171,7 +171,7 @@ public class FreeMarkerView extends AbstractTemplateView { */ protected FreeMarkerConfig autodetectConfiguration() throws BeansException { try { - return (FreeMarkerConfig) BeanFactoryUtils.beanOfTypeIncludingAncestors( + return BeanFactoryUtils.beanOfTypeIncludingAncestors( getApplicationContext(), FreeMarkerConfig.class, true, false); } catch (NoSuchBeanDefinitionException ex) { @@ -221,7 +221,7 @@ public class FreeMarkerView extends AbstractTemplateView { */ @Override protected void renderMergedTemplateModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { exposeHelpers(model, request); doRender(model, request, response); @@ -237,7 +237,7 @@ public class FreeMarkerView extends AbstractTemplateView { * @throws Exception if there's a fatal error while we're adding information to the context * @see #renderMergedTemplateModel */ - protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception { + protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception { } /** @@ -263,7 +263,7 @@ public class FreeMarkerView extends AbstractTemplateView { * @see #processTemplate * @see freemarker.ext.servlet.FreemarkerServlet */ - protected void doRender(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + protected void doRender(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Expose model to JSP tags (as request attributes). exposeModelAsRequestAttributes(model, request); @@ -340,7 +340,7 @@ public class FreeMarkerView extends AbstractTemplateView { * @throws TemplateException if thrown by FreeMarker * @see freemarker.template.Template#process(Object, java.io.Writer) */ - protected void processTemplate(Template template, Map model, HttpServletResponse response) + protected void processTemplate(Template template, Map model, HttpServletResponse response) throws IOException, TemplateException { template.process(model, response.getWriter()); @@ -378,8 +378,8 @@ public class FreeMarkerView extends AbstractTemplateView { return null; } - public Enumeration getInitParameterNames() { - return Collections.enumeration(Collections.EMPTY_SET); + public Enumeration getInitParameterNames() { + return Collections.enumeration(new HashSet()); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsSingleFormatView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsSingleFormatView.java index 5bc4d3af504..0b5fa831cea 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsSingleFormatView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsSingleFormatView.java @@ -17,10 +17,7 @@ package org.springframework.web.servlet.view.jasperreports; import java.io.ByteArrayOutputStream; -import java.util.HashMap; -import java.util.Iterator; import java.util.Map; - import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JRExporter; @@ -57,13 +54,12 @@ public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasp * for a pre-defined output format. */ @Override - protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response) + protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response) throws Exception { JRExporter exporter = createExporter(); - // Set exporter parameters - overriding with values from the Model. - Map mergedExporterParameters = mergeExporterParameters(model); + Map mergedExporterParameters = getConvertedExporterParameters(); if (!CollectionUtils.isEmpty(mergedExporterParameters)) { exporter.setParameters(mergedExporterParameters); } @@ -76,28 +72,6 @@ public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasp } } - /** - * Merges the configured JRExporterParameters with any specified in the supplied model data. - * JRExporterParameters in the model override those specified in the configuration. - * @see #setExporterParameters(java.util.Map) - */ - protected Map mergeExporterParameters(Map model) { - Map mergedParameters = new HashMap(); - Map convertedExporterParameters = getConvertedExporterParameters(); - if (!CollectionUtils.isEmpty(convertedExporterParameters)) { - mergedParameters.putAll(convertedExporterParameters); - } - for (Iterator it = model.keySet().iterator(); it.hasNext();) { - Object key = it.next(); - if (key instanceof JRExporterParameter) { - Object value = model.get(key); - Object convertedValue = convertParameterValue((JRExporterParameter) key, value); - mergedParameters.put(key, convertedValue); - } - } - return mergedParameters; - } - /** * We need to write text to the response Writer. * @param exporter the JasperReports exporter to use @@ -113,7 +87,7 @@ public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasp String encoding = (String) exporter.getParameter(JRExporterParameter.CHARACTER_ENCODING); if (encoding != null) { // Only apply encoding if content type is specified but does not contain charset clause already. - if (contentType != null && contentType.toLowerCase().indexOf(WebUtils.CONTENT_TYPE_CHARSET_PREFIX) == -1) { + if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) { contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding; } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsView.java index 39e5171053f..5c1994b3f12 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsView.java @@ -23,7 +23,6 @@ import java.sql.SQLException; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; import javax.servlet.http.HttpServletRequest; @@ -35,11 +34,10 @@ import net.sf.jasperreports.engine.JRDataSourceProvider; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JRParameter; +import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; -import net.sf.jasperreports.engine.design.JRCompiler; -import net.sf.jasperreports.engine.design.JRDefaultCompiler; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.engine.xml.JRXmlLoader; @@ -151,23 +149,18 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * Stores the exporter parameters passed in by the user as passed in by the user. May be keyed as * Strings with the fully qualified name of the exporter parameter field. */ - private Map exporterParameters = new HashMap(); + private Map exporterParameters = new HashMap(); /** * Stores the converted exporter parameters - keyed by JRExporterParameter. */ - private Map convertedExporterParameters; + private Map convertedExporterParameters; /** * Stores the DataSource, if any, used as the report data source. */ private DataSource jdbcDataSource; - /** - * Holds the JRCompiler implementation to use for compiling reports on-the-fly. - */ - private JRCompiler reportCompiler = JRDefaultCompiler.getInstance(); - /** * The JasperReport that is used to render the view. */ @@ -176,7 +169,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { /** * Holds mappings between sub-report keys and JasperReport objects. */ - private Map subReports; + private Map subReports; /** @@ -251,26 +244,21 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * (e.g. "net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI") * and the value you wish to assign to the parameter as value */ - public void setExporterParameters(Map parameters) { - // NOTE: Removed conversion from here since configuration of parameters - // can also happen through access to the underlying Map using - // getExporterParameters(). Conversion now happens in initApplicationContext, - // and subclasses use getConvertedExporterParameters() to access the converted - // parameter Map - robh. + public void setExporterParameters(Map parameters) { this.exporterParameters = parameters; } /** * Return the exporter parameters that this view uses, if any. */ - public Map getExporterParameters() { + public Map getExporterParameters() { return this.exporterParameters; } /** * Allows subclasses to retrieve the converted exporter parameters. */ - protected Map getConvertedExporterParameters() { + protected Map getConvertedExporterParameters() { return this.convertedExporterParameters; } @@ -289,24 +277,6 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { return this.jdbcDataSource; } - /** - * Specify the JRCompiler implementation to use for compiling a ".jrxml" - * report file on-the-fly into a report class. - *

By default, a JRDefaultCompiler will be used, delegating to the - * Eclipse JDT compiler or the Sun JDK compiler underneath. - * @see net.sf.jasperreports.engine.design.JRDefaultCompiler - */ - public void setReportCompiler(JRCompiler reportCompiler) { - this.reportCompiler = (reportCompiler != null ? reportCompiler : JRDefaultCompiler.getInstance()); - } - - /** - * Return the JRCompiler instance to use for compiling ".jrxml" report files. - */ - protected JRCompiler getReportCompiler() { - return this.reportCompiler; - } - /** * JasperReports views do not strictly required a 'url' value. @@ -333,7 +303,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { throw new ApplicationContextException( "'reportDataKey' for main report is required when specifying a value for 'subReportDataKeys'"); } - this.subReports = new HashMap(this.subReportUrls.size()); + this.subReports = new HashMap(this.subReportUrls.size()); for (Enumeration urls = this.subReportUrls.propertyNames(); urls.hasMoreElements();) { String key = (String) urls.nextElement(); String path = this.subReportUrls.getProperty(key); @@ -373,9 +343,8 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { */ protected final void convertExporterParameters() { if (!CollectionUtils.isEmpty(this.exporterParameters)) { - this.convertedExporterParameters = new HashMap(this.exporterParameters.size()); - for (Iterator it = this.exporterParameters.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + this.convertedExporterParameters = new HashMap(this.exporterParameters.size()); + for (Map.Entry entry : this.exporterParameters.entrySet()) { JRExporterParameter exporterParameter = getExporterParameter(entry.getKey()); this.convertedExporterParameters.put( exporterParameter, convertParameterValue(exporterParameter, entry.getValue())); @@ -522,7 +491,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { logger.info("Compiling Jasper Report loaded from " + resource); } JasperDesign design = JRXmlLoader.load(resource.getInputStream()); - return getReportCompiler().compileReport(design); + return JasperCompileManager.compileReport(design); } else { throw new IllegalArgumentException( @@ -549,8 +518,8 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * @see #getReportData */ @Override - protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) - throws Exception { + protected void renderMergedOutputModel( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { if (this.subReports != null) { // Expose sub-reports as model attributes. @@ -558,8 +527,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { // Transform any collections etc into JRDataSources for sub reports. if (this.subReportDataKeys != null) { - for (int i = 0; i < this.subReportDataKeys.length; i++) { - String key = this.subReportDataKeys[i]; + for (String key : this.subReportDataKeys) { model.put(key, convertReportData(model.get(key))); } } @@ -591,7 +559,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * @see net.sf.jasperreports.engine.JRParameter#REPORT_RESOURCE_BUNDLE * @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext */ - protected void exposeLocalizationContext(Map model, HttpServletRequest request) { + protected void exposeLocalizationContext(Map model, HttpServletRequest request) { RequestContext rc = new RequestContext(request, getServletContext()); model.put(JRParameter.REPORT_LOCALE, rc.getLocale()); JasperReport report = getReport(); @@ -623,7 +591,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * @see #getReportData * @see #setJdbcDataSource */ - protected JasperPrint fillReport(Map model) throws Exception { + protected JasperPrint fillReport(Map model) throws Exception { // Determine main report. JasperReport report = getReport(); if (report == null) { @@ -646,15 +614,14 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { } else { Collection values = model.values(); - jrDataSource = (JRDataSource) CollectionUtils.findValueOfType(values, JRDataSource.class); + jrDataSource = CollectionUtils.findValueOfType(values, JRDataSource.class); if (jrDataSource == null) { - JRDataSourceProvider provider = - (JRDataSourceProvider) CollectionUtils.findValueOfType(values, JRDataSourceProvider.class); + JRDataSourceProvider provider = CollectionUtils.findValueOfType(values, JRDataSourceProvider.class); if (provider != null) { jrDataSource = createReport(provider); } else { - jdbcDataSourceToUse = (DataSource) CollectionUtils.findValueOfType(values, DataSource.class); + jdbcDataSourceToUse = CollectionUtils.findValueOfType(values, DataSource.class); if (jdbcDataSourceToUse == null) { jdbcDataSourceToUse = this.jdbcDataSource; } @@ -689,12 +656,12 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { /** * Fill the given report using the given JDBC DataSource and model. */ - private JasperPrint doFillReport(JasperReport report, Map model, DataSource dataSource) throws Exception { + private JasperPrint doFillReport(JasperReport report, Map model, DataSource ds) throws Exception { // Use the JDBC DataSource. if (logger.isDebugEnabled()) { - logger.debug("Filling report using JDBC DataSource [" + dataSource + "]"); + logger.debug("Filling report using JDBC DataSource [" + ds + "]"); } - Connection con = dataSource.getConnection(); + Connection con = ds.getConnection(); try { return JasperFillManager.fillReport(report, model, con); } @@ -747,7 +714,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * @see #convertReportData * @see #getReportDataTypes */ - protected JRDataSource getReportData(Map model) { + protected JRDataSource getReportData(Map model) { // Try to find matching attribute, of given prioritized types. Object value = CollectionUtils.findValueOfType(model.values(), getReportDataTypes()); return (value != null ? convertReportData(value) : null); @@ -820,7 +787,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * @param model the map containing report parameters * @throws Exception if post-processing failed */ - protected void postProcessReport(JasperPrint populatedReport, Map model) throws Exception { + protected void postProcessReport(JasperPrint populatedReport, Map model) throws Exception { } /** @@ -841,7 +808,8 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { * @see javax.servlet.ServletResponse#setContentType * @see javax.servlet.ServletResponse#setCharacterEncoding */ - protected abstract void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response) + protected abstract void renderReport( + JasperPrint populatedReport, Map model, HttpServletResponse response) throws Exception; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatView.java index 807c89acff1..2488a3d622b 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsMultiFormatView.java @@ -16,18 +16,15 @@ package org.springframework.web.servlet.view.jasperreports; -import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; - import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JasperPrint; import org.springframework.beans.BeanUtils; -import org.springframework.context.ApplicationContextException; -import org.springframework.util.ClassUtils; +import org.springframework.util.CollectionUtils; /** * Jasper Reports view class that allows for the actual rendering format to be @@ -41,7 +38,7 @@ import org.springframework.util.ClassUtils; * Controller: * *

- * Map model = new HashMap();
+ * Map model = new HashMap();
  * model.put("format", "pdf");
* * Here format is the format key and pdf is @@ -85,7 +82,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView { * Stores the format mappings, with the format discriminator * as key and the corresponding view class as value. */ - private Map formatMappings; + private Map formatMappings; /** * Stores the mappings of mapping keys to Content-Disposition header values. @@ -98,7 +95,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView { * with a default set of mappings. */ public JasperReportsMultiFormatView() { - this.formatMappings = new HashMap(4); + this.formatMappings = new HashMap(4); this.formatMappings.put("csv", JasperReportsCsvView.class); this.formatMappings.put("html", JasperReportsHtmlView.class); this.formatMappings.put("pdf", JasperReportsPdfView.class); @@ -123,26 +120,11 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView { *
  • xls - JasperReportsXlsView
  • * */ - public void setFormatMappings(Properties mappingsWithClassNames) { - if (mappingsWithClassNames == null || mappingsWithClassNames.isEmpty()) { - throw new IllegalArgumentException("formatMappings must not be empty"); - } - - this.formatMappings = new HashMap(mappingsWithClassNames.size()); - for (Enumeration discriminators = mappingsWithClassNames.propertyNames(); discriminators.hasMoreElements();) { - String discriminator = (String) discriminators.nextElement(); - String className = mappingsWithClassNames.getProperty(discriminator); - try { - if (logger.isDebugEnabled()) { - logger.debug("Mapped view class [" + className + "] to mapping key [" + discriminator + "]"); - } - this.formatMappings.put(discriminator, ClassUtils.forName(className)); - } - catch (ClassNotFoundException ex) { - throw new ApplicationContextException( - "Class [" + className + "] mapped to format [" + discriminator + "] cannot be found", ex); - } + public void setFormatMappings(Map formatMappings) { + if (CollectionUtils.isEmpty(formatMappings)) { + throw new IllegalArgumentException("'formatMappings' must not be empty"); } + this.formatMappings = formatMappings; } /** @@ -179,7 +161,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView { * report is then delegated to an instance of that view class. */ @Override - protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response) + protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response) throws Exception { String format = (String) model.get(this.formatKey); @@ -191,7 +173,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView { logger.debug("Rendering report using format mapping key [" + format + "]"); } - Class viewClass = (Class) this.formatMappings.get(format); + Class viewClass = this.formatMappings.get(format); if (viewClass == null) { throw new IllegalArgumentException("Format discriminator [" + format + "] is not a configured mapping"); } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsViewResolver.java index 8a741e6055e..db22a77e1f8 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsViewResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package org.springframework.web.servlet.view.jasperreports; import java.util.HashMap; import java.util.Map; import java.util.Properties; - import javax.sql.DataSource; import net.sf.jasperreports.engine.design.JRCompiler; @@ -45,7 +44,7 @@ public class JasperReportsViewResolver extends UrlBasedViewResolver { private Properties headers; - private Map exporterParameters = new HashMap(); + private Map exporterParameters = new HashMap(); private DataSource jdbcDataSource; @@ -96,7 +95,7 @@ public class JasperReportsViewResolver extends UrlBasedViewResolver { * Set the exporterParameters the view class should use. * @see AbstractJasperReportsView#setExporterParameters */ - public void setExporterParameters(Map exporterParameters) { + public void setExporterParameters(Map exporterParameters) { this.exporterParameters = exporterParameters; } @@ -108,30 +107,16 @@ public class JasperReportsViewResolver extends UrlBasedViewResolver { this.jdbcDataSource = jdbcDataSource; } - /** - * Set the {@link JRCompiler} the view class should use. - * @see AbstractJasperReportsView#setReportCompiler - */ - public void setReportCompiler(JRCompiler reportCompiler) { - this.reportCompiler = reportCompiler; - } - @Override protected AbstractUrlBasedView buildView(String viewName) throws Exception { AbstractJasperReportsView view = (AbstractJasperReportsView) super.buildView(viewName); - view.setReportDataKey(this.reportDataKey); view.setSubReportUrls(this.subReportUrls); view.setSubReportDataKeys(this.subReportDataKeys); view.setHeaders(this.headers); view.setExporterParameters(this.exporterParameters); view.setJdbcDataSource(this.jdbcDataSource); - - if (this.reportCompiler != null) { - view.setReportCompiler(this.reportCompiler); - } - return view; } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/TilesView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/TilesView.java index 850ac27c379..a1bdeb3eba7 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/TilesView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/TilesView.java @@ -50,8 +50,8 @@ import org.springframework.web.util.WebUtils; public class TilesView extends AbstractUrlBasedView { @Override - protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) - throws Exception { + protected void renderMergedOutputModel( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { ServletContext servletContext = getServletContext(); TilesContainer container = TilesAccess.getContainer(servletContext); @@ -73,7 +73,7 @@ public class TilesView extends AbstractUrlBasedView { } } - container.render(getUrl(), new Object[] {request, response}); + container.render(getUrl(), request, response); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityToolboxView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityToolboxView.java index a4485153902..cb18282dfdc 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityToolboxView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityToolboxView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import org.apache.velocity.context.Context; import org.apache.velocity.tools.view.ToolboxManager; import org.apache.velocity.tools.view.context.ChainedContext; import org.apache.velocity.tools.view.servlet.ServletToolboxManager; -import org.apache.velocity.tools.view.tools.ViewTool; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -56,7 +55,7 @@ import org.springframework.util.ReflectionUtils; * *

    This is a separate class mainly to avoid a required dependency on * the view package of Velocity Tools in {@link VelocityView} itself. - * As of Spring 2.0, this class requires Velocity Tools 1.2 or higher. + * As of Spring 3.0, this class requires Velocity Tools 1.3 or higher. * * @author Juergen Hoeller * @since 1.1.3 @@ -64,7 +63,6 @@ import org.springframework.util.ReflectionUtils; * @see #initTool * @see org.apache.velocity.tools.view.context.ViewContext * @see org.apache.velocity.tools.view.context.ChainedContext - * @see org.apache.velocity.tools.view.tools.ViewTool * @see org.apache.velocity.tools.view.tools.LinkTool */ public class VelocityToolboxView extends VelocityView { @@ -102,7 +100,7 @@ public class VelocityToolboxView extends VelocityView { */ @Override protected Context createVelocityContext( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Create a ChainedContext instance. ChainedContext velocityContext = new ChainedContext( @@ -123,26 +121,14 @@ public class VelocityToolboxView extends VelocityView { * Overridden to check for the ViewContext interface which is part of the * view package of Velocity Tools. This requires a special Velocity context, * like ChainedContext as set up by {@link #createVelocityContext} in this class. - * @see org.apache.velocity.tools.view.tools.ViewTool#init(Object) * @see org.apache.velocity.tools.view.tools.LinkTool#init(Object) */ @Override protected void initTool(Object tool, Context velocityContext) throws Exception { - // Initialize ViewTool instances with the Velocity context. - // Despite having an "init(Object)" method, all known ViewTool - // implementations expect a ViewContext implementation as argument. - // ChainedContext implements the ViewContext interface. - if (tool instanceof ViewTool) { - // Velocity Tools 1.2: an actual ViewTool implementation. - ((ViewTool) tool).init(velocityContext); - } - else { - // Velocity Tools 1.3: a class-level "init(Object)" method. - Method initMethod = - ClassUtils.getMethodIfAvailable(tool.getClass(), "init", new Class[] {Object.class}); - if (initMethod != null) { - ReflectionUtils.invokeMethod(initMethod, tool, new Object[] {velocityContext}); - } + // Velocity Tools 1.3: a class-level "init(Object)" method. + Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class); + if (initMethod != null) { + ReflectionUtils.invokeMethod(initMethod, tool, new Object[] {velocityContext}); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityView.java index 111863e0bfe..572605f0d69 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,14 @@ package org.springframework.web.servlet.view.velocity; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; import java.util.Locale; import java.util.Map; -import java.util.Properties; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.app.tools.VelocityFormatter; import org.apache.velocity.context.Context; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ResourceNotFoundException; @@ -40,7 +34,6 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContextException; -import org.springframework.util.ClassUtils; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.servlet.view.AbstractTemplateView; import org.springframework.web.util.NestedServletException; @@ -90,9 +83,7 @@ import org.springframework.web.util.NestedServletException; */ public class VelocityView extends AbstractTemplateView { - private Map toolAttributes; - - private String velocityFormatterAttribute; + private Map toolAttributes; private String dateToolAttribute; @@ -135,31 +126,8 @@ public class VelocityView extends AbstractTemplateView { * @see #setDateToolAttribute * @see #setNumberToolAttribute */ - public void setToolAttributes(Properties toolAttributes) { - this.toolAttributes = new HashMap(toolAttributes.size()); - for (Enumeration attributeNames = toolAttributes.propertyNames(); attributeNames.hasMoreElements();) { - String attributeName = (String) attributeNames.nextElement(); - String className = toolAttributes.getProperty(attributeName); - Class toolClass = null; - try { - toolClass = ClassUtils.forName(className); - } - catch (ClassNotFoundException ex) { - throw new IllegalArgumentException( - "Invalid definition for tool '" + attributeName + "' - tool class not found: " + ex.getMessage()); - } - this.toolAttributes.put(attributeName, toolClass); - } - } - - /** - * Set the name of the VelocityFormatter helper object to expose in the - * Velocity context of this view, or null if not needed. - *

    VelocityFormatter is part of the standard Velocity distribution. - * @see org.apache.velocity.app.tools.VelocityFormatter - */ - public void setVelocityFormatterAttribute(String velocityFormatterAttribute) { - this.velocityFormatterAttribute = velocityFormatterAttribute; + public void setToolAttributes(Map toolAttributes) { + this.toolAttributes = toolAttributes; } /** @@ -269,9 +237,8 @@ public class VelocityView extends AbstractTemplateView { */ protected VelocityEngine autodetectVelocityEngine() throws BeansException { try { - VelocityConfig velocityConfig = (VelocityConfig) - BeanFactoryUtils.beanOfTypeIncludingAncestors( - getApplicationContext(), VelocityConfig.class, true, false); + VelocityConfig velocityConfig = BeanFactoryUtils.beanOfTypeIncludingAncestors( + getApplicationContext(), VelocityConfig.class, true, false); return velocityConfig.getVelocityEngine(); } catch (NoSuchBeanDefinitionException ex) { @@ -311,7 +278,7 @@ public class VelocityView extends AbstractTemplateView { */ @Override protected void renderMergedTemplateModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { exposeHelpers(model, request); @@ -332,7 +299,7 @@ public class VelocityView extends AbstractTemplateView { * @throws Exception if there's a fatal error while we're adding model attributes * @see #renderMergedTemplateModel */ - protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception { + protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception { } /** @@ -356,7 +323,7 @@ public class VelocityView extends AbstractTemplateView { * @see VelocityToolboxView */ protected Context createVelocityContext( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { return createVelocityContext(model); } @@ -372,7 +339,7 @@ public class VelocityView extends AbstractTemplateView { * @throws Exception if there's a fatal error while creating the context * @see org.apache.velocity.VelocityContext */ - protected Context createVelocityContext(Map model) throws Exception { + protected Context createVelocityContext(Map model) throws Exception { return new VelocityContext(model); } @@ -415,7 +382,6 @@ public class VelocityView extends AbstractTemplateView { * @param velocityContext Velocity context that will be passed to the template * @param request current HTTP request * @throws Exception if there's a fatal error while we're adding model attributes - * @see #setVelocityFormatterAttribute * @see #setDateToolAttribute * @see #setNumberToolAttribute * @see #exposeHelpers(Map, HttpServletRequest) @@ -424,10 +390,9 @@ public class VelocityView extends AbstractTemplateView { protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception { // Expose generic attributes. if (this.toolAttributes != null) { - for (Iterator it = this.toolAttributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String attributeName = (String) entry.getKey(); - Class toolClass = (Class) entry.getValue(); + for (Map.Entry entry : this.toolAttributes.entrySet()) { + String attributeName = entry.getKey(); + Class toolClass = entry.getValue(); try { Object tool = toolClass.newInstance(); initTool(tool, velocityContext); @@ -439,11 +404,6 @@ public class VelocityView extends AbstractTemplateView { } } - // Expose VelocityFormatter attribute. - if (this.velocityFormatterAttribute != null) { - velocityContext.put(this.velocityFormatterAttribute, new VelocityFormatter(velocityContext)); - } - // Expose locale-aware DateTool/NumberTool attributes. if (this.dateToolAttribute != null || this.numberToolAttribute != null) { Locale locale = RequestContextUtils.getLocale(request); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityViewResolver.java index 350d270b363..b143b04fb1e 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityViewResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/velocity/VelocityViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver; import org.springframework.web.servlet.view.AbstractUrlBasedView; /** - * Convenience subclass of UrlBasedViewResolver that supports VelocityView - * (that is Velocity templates) and custom subclasses of it. + * Convenience subclass of {@link org.springframework.web.servlet.view.UrlBasedViewResolver} + * that supports VelocityView (i.e. Velocity templates) and custom subclasses of it. * *

    The view class for all views generated by this resolver can be specified * via setViewClass. See UrlBasedViewResolver's javadoc for details. @@ -44,8 +44,6 @@ import org.springframework.web.servlet.view.AbstractUrlBasedView; */ public class VelocityViewResolver extends AbstractTemplateViewResolver { - private String velocityFormatterAttribute; - private String dateToolAttribute; private String numberToolAttribute; @@ -71,17 +69,6 @@ public class VelocityViewResolver extends AbstractTemplateViewResolver { return VelocityView.class; } - /** - * Set the name of the VelocityFormatter helper object to expose in the - * Velocity context of this view, or null if not needed. - * VelocityFormatter is part of the standard Velocity distribution. - * @see org.apache.velocity.app.tools.VelocityFormatter - * @see VelocityView#setVelocityFormatterAttribute - */ - public void setVelocityFormatterAttribute(String velocityFormatterAttribute) { - this.velocityFormatterAttribute = velocityFormatterAttribute; - } - /** * Set the name of the DateTool helper object to expose in the Velocity context * of this view, or null if not needed. DateTool is part of Velocity Tools 1.0. @@ -143,7 +130,6 @@ public class VelocityViewResolver extends AbstractTemplateViewResolver { @Override protected AbstractUrlBasedView buildView(String viewName) throws Exception { VelocityView view = (VelocityView) super.buildView(viewName); - view.setVelocityFormatterAttribute(this.velocityFormatterAttribute); view.setDateToolAttribute(this.dateToolAttribute); view.setNumberToolAttribute(this.numberToolAttribute); if (this.toolboxConfigLocation != null) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/AbstractXsltView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/AbstractXsltView.java index 271c788a0f2..90342b2b28f 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/AbstractXsltView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/AbstractXsltView.java @@ -20,10 +20,8 @@ import java.io.BufferedOutputStream; import java.io.IOException; import java.net.URL; import java.util.Enumeration; -import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.ErrorListener; @@ -320,7 +318,7 @@ public abstract class AbstractXsltView extends AbstractView { @Override protected final void renderMergedOutputModel( - Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(getContentType()); @@ -330,7 +328,7 @@ public abstract class AbstractXsltView extends AbstractView { Object singleModel = null; if (this.useSingleModelNameAsRoot && model.size() == 1) { - docRoot = (String) model.keySet().iterator().next(); + docRoot = model.keySet().iterator().next(); if (logger.isDebugEnabled()) { logger.debug("Single model object received, key [" + docRoot + "] will be used as root tag"); } @@ -370,7 +368,7 @@ public abstract class AbstractXsltView extends AbstractView { * @throws Exception if an error occurs */ protected Source createXsltSource( - Map model, String root, HttpServletRequest request, HttpServletResponse response) + Map model, String root, HttpServletRequest request, HttpServletResponse response) throws Exception { return null; @@ -393,10 +391,10 @@ public abstract class AbstractXsltView extends AbstractView { * @see #useWriter() */ protected void doTransform( - Map model, Source source, HttpServletRequest request, HttpServletResponse response) + Map model, Source source, HttpServletRequest request, HttpServletResponse response) throws Exception { - Map parameters = getParameters(model, request); + Map parameters = getParameters(model, request); Result result = (useWriter() ? new StreamResult(response.getWriter()) : new StreamResult(new BufferedOutputStream(response.getOutputStream()))); @@ -416,7 +414,7 @@ public abstract class AbstractXsltView extends AbstractView { * @see #getParameters() * @see javax.xml.transform.Transformer#setParameter */ - protected Map getParameters(Map model, HttpServletRequest request) { + protected Map getParameters(Map model, HttpServletRequest request) { return getParameters(request); } @@ -424,25 +422,13 @@ public abstract class AbstractXsltView extends AbstractView { * Return a Map of transformer parameters to be applied to the stylesheet. *

    Subclasses can override this method in order to apply one or more * parameters to the transformation process. - *

    The default implementation delegates to the simple - * {@link #getParameters()} variant. + *

    The default implementation simply returns null. * @param request current HTTP request * @return a Map of parameters to apply to the transformation process * @see #getParameters(Map, HttpServletRequest) * @see javax.xml.transform.Transformer#setParameter */ protected Map getParameters(HttpServletRequest request) { - return getParameters(); - } - - /** - * Return a Map of transformer parameters to be applied to the stylesheet. - * @return a Map of parameters to apply to the transformation process - * @deprecated as of Spring 2.0.4, in favor of the - * {@link #getParameters(HttpServletRequest)} variant - */ - @Deprecated - protected Map getParameters() { return null; } @@ -471,7 +457,7 @@ public abstract class AbstractXsltView extends AbstractView { * @param encoding the preferred character encoding that the underlying Transformer should use * @throws Exception if an error occurs */ - protected void doTransform(Source source, Map parameters, Result result, String encoding) + protected void doTransform(Source source, Map parameters, Result result, String encoding) throws Exception { try { @@ -519,7 +505,7 @@ public abstract class AbstractXsltView extends AbstractView { * @throws TransformerConfigurationException if the Transformer object * could not be built */ - protected Transformer buildTransformer(Map parameters) throws TransformerConfigurationException { + protected Transformer buildTransformer(Map parameters) throws TransformerConfigurationException { Templates templates = getTemplates(); Transformer transformer = (templates != null ? templates.newTransformer() : getTransformerFactory().newTransformer()); @@ -562,11 +548,10 @@ public abstract class AbstractXsltView extends AbstractView { * (as determined by {@link #getParameters(Map, HttpServletRequest)}) * @param transformer the Transformer to aply the parameters */ - protected void applyTransformerParameters(Map parameters, Transformer transformer) { + protected void applyTransformerParameters(Map parameters, Transformer transformer) { if (parameters != null) { - for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - transformer.setParameter(entry.getKey().toString(), entry.getValue()); + for (Map.Entry entry : parameters.entrySet()) { + transformer.setParameter(entry.getKey(), entry.getValue()); } } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java index b040e185fdf..0dbb27b025e 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java @@ -20,10 +20,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Enumeration; -import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.ErrorListener; @@ -48,7 +46,6 @@ import org.springframework.context.ApplicationContextException; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; -import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.SimpleTransformErrorListener; import org.springframework.util.xml.TransformerUtils; @@ -222,7 +219,8 @@ public class XsltView extends AbstractUrlBasedView { @Override - protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) + protected void renderMergedOutputModel( + Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { Templates templates = this.cachedTemplates; @@ -270,7 +268,7 @@ public class XsltView extends AbstractUrlBasedView { * @see #setSourceKey * @see #convertSource */ - protected Source locateSource(Map model) throws Exception { + protected Source locateSource(Map model) throws Exception { if (this.sourceKey != null) { return convertSource(model.get(this.sourceKey)); } @@ -335,7 +333,7 @@ public class XsltView extends AbstractUrlBasedView { * @see #copyOutputProperties(Transformer) * @see #configureIndentation(Transformer) */ - protected void configureTransformer(Map model, HttpServletResponse response, Transformer transformer) { + protected void configureTransformer(Map model, HttpServletResponse response, Transformer transformer) { copyModelParameters(model, transformer); copyOutputProperties(transformer); configureIndentation(transformer); @@ -379,8 +377,10 @@ public class XsltView extends AbstractUrlBasedView { * @param model merged output Map (never null) * @param transformer the target transformer */ - protected final void copyModelParameters(Map model, Transformer transformer) { - copyMapEntriesToTransformerParameters(model, transformer); + protected final void copyModelParameters(Map model, Transformer transformer) { + for (Map.Entry entry : model.entrySet()) { + transformer.setParameter(entry.getKey(), entry.getValue()); + } } /** @@ -394,7 +394,7 @@ public class XsltView extends AbstractUrlBasedView { * @param response current HTTP response * @param transformer the target transformer */ - protected void configureResponse(Map model, HttpServletResponse response, Transformer transformer) { + protected void configureResponse(Map model, HttpServletResponse response, Transformer transformer) { String contentType = getContentType(); String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE); String encoding = transformer.getOutputProperty(OutputKeys.ENCODING); @@ -403,7 +403,7 @@ public class XsltView extends AbstractUrlBasedView { } if (StringUtils.hasText(encoding)) { // Only apply encoding if content type is specified but does not contain charset clause already. - if (contentType != null && contentType.toLowerCase().indexOf(WebUtils.CONTENT_TYPE_CHARSET_PREFIX) == -1) { + if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) { contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding; } } @@ -464,18 +464,6 @@ public class XsltView extends AbstractUrlBasedView { } } - /** - * Copy all {@link Map.Entry entries} from the supplied {@link Map} into the - * {@link Transformer#setParameter(String, Object) parameter set} of the supplied - * {@link Transformer}. - */ - private void copyMapEntriesToTransformerParameters(Map map, Transformer transformer) { - for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) { - Map.Entry entry = (Map.Entry) iterator.next(); - transformer.setParameter(ObjectUtils.nullSafeToString(entry.getKey()), entry.getValue()); - } - } - /** * Close the underlying resource managed by the supplied {@link Source} if applicable. *

    Only works for {@link StreamSource StreamSources}. @@ -489,6 +477,7 @@ public class XsltView extends AbstractUrlBasedView { streamSource.getReader().close(); } catch (IOException ex) { + // ignore } } if (streamSource.getInputStream() != null) { @@ -496,6 +485,7 @@ public class XsltView extends AbstractUrlBasedView { streamSource.getInputStream().close(); } catch (IOException ex) { + // ignore } } } diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java b/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java index 36b9a08b554..2c2b810d752 100644 --- a/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java +++ b/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java @@ -20,7 +20,6 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; - import javax.jws.WebService; import javax.xml.ws.Endpoint; @@ -30,7 +29,6 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.core.task.TaskExecutor; -import org.springframework.core.task.support.ConcurrentExecutorAdapter; /** * Abstract exporter for JAX-WS services, autodetecting annotated service beans @@ -82,7 +80,7 @@ public abstract class AbstractJaxWsServiceExporter implements BeanFactoryAware, * @see javax.xml.ws.Endpoint#setExecutor */ public void setTaskExecutor(TaskExecutor executor) { - this.executor = new ConcurrentExecutorAdapter(executor); + this.executor = executor; } /** diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java b/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java index ecab0d89de6..7d4df473aa6 100644 --- a/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java +++ b/org.springframework.web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,11 @@ package org.springframework.remoting.jaxws; import java.net.URL; import java.util.concurrent.Executor; - import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.handler.HandlerResolver; import org.springframework.core.task.TaskExecutor; -import org.springframework.core.task.support.ConcurrentExecutorAdapter; /** * Factory for locally defined JAX-WS {@link javax.xml.ws.Service} references. @@ -112,7 +110,7 @@ public class LocalJaxWsServiceFactory { * @see javax.xml.ws.Service#setExecutor */ public void setTaskExecutor(TaskExecutor executor) { - this.executor = new ConcurrentExecutorAdapter(executor); + this.executor = executor; } /** diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java b/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java index 3619fdda8b5..40b226124d3 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java @@ -465,9 +465,10 @@ public abstract class WebUtils { * @param request current HTTP request * @param attributes the attributes Map */ - public static void exposeRequestAttributes(ServletRequest request, Map attributes) { + public static void exposeRequestAttributes(ServletRequest request, Map attributes) { Assert.notNull(request, "Request must not be null"); - for (Map.Entry entry : attributes.entrySet()) { + Assert.notNull(attributes, "Attributes Map must not be null"); + for (Map.Entry entry : attributes.entrySet()) { request.setAttribute(entry.getKey(), entry.getValue()); } }