diff --git a/org.springframework.aop/aop.iml b/org.springframework.aop/aop.iml index c3670a9e8f8..c366ae70a66 100644 --- a/org.springframework.aop/aop.iml +++ b/org.springframework.aop/aop.iml @@ -1,111 +1,111 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java index 441e69b22b7..d25616741b6 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AbstractAspectJAdvice.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,6 @@ import org.springframework.aop.interceptor.ExposeInvocationInterceptor; import org.springframework.aop.support.ComposablePointcut; import org.springframework.aop.support.MethodMatchers; import org.springframework.aop.support.StaticMethodMatcher; -import org.springframework.core.JdkVersion; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.PrioritizedParameterNameDiscoverer; @@ -136,7 +135,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence */ private int joinPointStaticPartArgumentIndex = -1; - private Map argumentBindings = null; + private Map argumentBindings = null; private boolean argumentsIntrospected = false; @@ -454,7 +453,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence } private void bindExplicitArguments(int numArgumentsLeftToBind) { - this.argumentBindings = new HashMap(); + this.argumentBindings = new HashMap(); int numExpectedArgumentNames = this.aspectJAdviceMethod.getParameterTypes().length; if (this.argumentNames.length != numExpectedArgumentNames) { @@ -466,7 +465,7 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence // So we match in number... int argumentIndexOffset = this.adviceInvocationArgumentCount - numArgumentsLeftToBind; for (int i = argumentIndexOffset; i < this.argumentNames.length; i++) { - this.argumentBindings.put(this.argumentNames[i],new Integer(i)); + this.argumentBindings.put(this.argumentNames[i], i); } // Check that returning and throwing were in the argument names list if @@ -477,12 +476,9 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence + this.returningName + "' was not bound in advice arguments"); } else { - Integer index = (Integer) this.argumentBindings.get(this.returningName); - this.discoveredReturningType = this.aspectJAdviceMethod.getParameterTypes()[index.intValue()]; - if (JdkVersion.isAtLeastJava15()) { - this.discoveredReturningGenericType = - this.aspectJAdviceMethod.getGenericParameterTypes()[index.intValue()]; - } + Integer index = this.argumentBindings.get(this.returningName); + this.discoveredReturningType = this.aspectJAdviceMethod.getParameterTypes()[index]; + this.discoveredReturningGenericType = this.aspectJAdviceMethod.getGenericParameterTypes()[index]; } } if (this.throwingName != null) { @@ -491,8 +487,8 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence + this.throwingName + "' was not bound in advice arguments"); } else { - Integer index = (Integer) this.argumentBindings.get(this.throwingName); - this.discoveredThrowingType = this.aspectJAdviceMethod.getParameterTypes()[index.intValue()]; + Integer index = this.argumentBindings.get(this.throwingName); + this.discoveredThrowingType = this.aspectJAdviceMethod.getParameterTypes()[index]; } } @@ -564,24 +560,23 @@ public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedence // binding from pointcut match if (jpMatch != null) { PointcutParameter[] parameterBindings = jpMatch.getParameterBindings(); - for (int i = 0; i < parameterBindings.length; i++) { - PointcutParameter parameter = parameterBindings[i]; + for (PointcutParameter parameter : parameterBindings) { String name = parameter.getName(); - Integer index = (Integer) this.argumentBindings.get(name); - adviceInvocationArgs[index.intValue()] = parameter.getBinding(); + Integer index = this.argumentBindings.get(name); + adviceInvocationArgs[index] = parameter.getBinding(); numBound++; } } // binding from returning clause if (this.returningName != null) { - Integer index = (Integer) this.argumentBindings.get(this.returningName); - adviceInvocationArgs[index.intValue()] = returnValue; + Integer index = this.argumentBindings.get(this.returningName); + adviceInvocationArgs[index] = returnValue; numBound++; } // binding from thrown exception if (this.throwingName != null) { - Integer index = (Integer) this.argumentBindings.get(this.throwingName); - adviceInvocationArgs[index.intValue()] = ex; + Integer index = this.argumentBindings.get(this.throwingName); + adviceInvocationArgs[index] = ex; numBound++; } } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java index f983be0110c..31c6471673e 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java @@ -655,7 +655,7 @@ public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscov return new PointcutBody(0, currentToken.substring(bodyStart + 1, currentToken.length() - 1)); } else { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (bodyStart >= 0 && bodyStart != (currentToken.length() - 1)) { sb.append(currentToken.substring(bodyStart + 1)); sb.append(" "); 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 6df302bd6ca..a51ae393673 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 @@ -411,7 +411,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("AspectJExpressionPointcut: "); if (this.pointcutParameterNames != null && this.pointcutParameterTypes != null) { sb.append("("); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java index be4a5aadbaa..76e9c47535b 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java @@ -146,7 +146,7 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); Advice advice = this.advisor.getAdvice(); sb.append(ClassUtils.getShortName(advice.getClass())); sb.append(": "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java b/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java index 6b4dffb6d94..36eda243298 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/config/AdvisorComponentDefinition.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,14 +78,14 @@ public class AdvisorComponentDefinition extends AbstractComponentDefinition { } private String buildDescription(BeanReference adviceReference, BeanDefinition pointcutDefinition) { - return new StringBuffer("Advisor ").toString(); } private String buildDescription(BeanReference adviceReference, BeanReference pointcutReference) { - return new StringBuffer("Advisor ").toString(); } 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 ce796cc430b..201518315bd 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 @@ -20,10 +20,10 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.aopalliance.aop.Advice; @@ -36,7 +36,6 @@ import org.springframework.aop.support.DefaultIntroductionAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.target.EmptyTargetSource; import org.springframework.aop.target.SingletonTargetSource; -import org.springframework.core.CollectionFactory; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -80,19 +79,19 @@ public class AdvisedSupport extends ProxyConfig implements Advised { AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory(); /** Cache with Method as key and advisor chain List as value */ - private transient Map methodCache; + private transient Map> methodCache; /** * Interfaces to be implemented by the proxy. Held in List to keep the order * of registration, to create JDK proxy with specified order of interfaces. */ - private List interfaces = new ArrayList(); + private List interfaces = new ArrayList(); /** * List of Advisors. If an Advice is added, it will be wrapped * in an Advisor before being added to this List. */ - private List advisors = new LinkedList(); + private List advisors = new LinkedList(); /** * Array updated on changes to the advisors list, which is easier @@ -121,7 +120,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * Initialize the method cache. */ private void initMethodCache() { - this.methodCache = CollectionFactory.createConcurrentMapIfPossible(32); + this.methodCache = new ConcurrentHashMap>(32); } @@ -195,8 +194,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { public void setInterfaces(Class[] interfaces) { Assert.notNull(interfaces, "Interfaces must not be null"); this.interfaces.clear(); - for (int i = 0; i < interfaces.length; i++) { - addInterface(interfaces[i]); + for (Class ifc : interfaces) { + addInterface(ifc); } } @@ -227,12 +226,11 @@ public class AdvisedSupport extends ProxyConfig implements Advised { } public Class[] getProxiedInterfaces() { - return (Class[]) this.interfaces.toArray(new Class[this.interfaces.size()]); + return this.interfaces.toArray(new Class[this.interfaces.size()]); } public boolean isInterfaceProxied(Class intf) { - for (Iterator it = this.interfaces.iterator(); it.hasNext();) { - Class proxyIntf = (Class) it.next(); + for (Class proxyIntf : this.interfaces) { if (intf.isAssignableFrom(proxyIntf)) { return true; } @@ -277,7 +275,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { "This configuration only has " + this.advisors.size() + " advisors."); } - Advisor advisor = (Advisor) this.advisors.get(index); + Advisor advisor = this.advisors.get(index); if (advisor instanceof IntroductionAdvisor) { IntroductionAdvisor ia = (IntroductionAdvisor) advisor; // We need to remove introduction interfaces. @@ -317,8 +315,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { throw new AopConfigException("Cannot add advisor: Configuration is frozen."); } if (!ObjectUtils.isEmpty(advisors)) { - for (int i = 0; i < advisors.length; i++) { - Advisor advisor = advisors[i]; + for (Advisor advisor : advisors) { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } @@ -334,8 +331,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { advisor.validateInterfaces(); // If the advisor passed validation, we can make the change. Class[] ifcs = advisor.getInterfaces(); - for (int i = 0; i < ifcs.length; i++) { - addInterface(ifcs[i]); + for (Class ifc : ifcs) { + addInterface(ifc); } } @@ -357,7 +354,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * Bring the array up to date with the list. */ protected final void updateAdvisorArray() { - this.advisorArray = (Advisor[]) this.advisors.toArray(new Advisor[this.advisors.size()]); + this.advisorArray = this.advisors.toArray(new Advisor[this.advisors.size()]); } /** @@ -408,7 +405,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { public int indexOf(Advice advice) { Assert.notNull(advice, "Advice must not be null"); for (int i = 0; i < this.advisors.size(); i++) { - Advisor advisor = (Advisor) this.advisors.get(i); + Advisor advisor = this.advisors.get(i); if (advisor.getAdvice() == advice) { return i; } @@ -422,11 +419,11 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @return whether this advice instance is included */ public boolean adviceIncluded(Advice advice) { - Assert.notNull(advice, "Advice must not be null"); - for (int i = 0; i < this.advisors.size(); i++) { - Advisor advisor = (Advisor) this.advisors.get(i); - if (advisor.getAdvice() == advice) { - return true; + if (advice != null) { + for (Advisor advisor : this.advisors) { + if (advisor.getAdvice() == advice) { + return true; + } } } return false; @@ -438,13 +435,12 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @return the count of the interceptors of this class or subclasses */ public int countAdvicesOfType(Class adviceClass) { - Assert.notNull(adviceClass, "Advice class must not be null"); int count = 0; - for (int i = 0; i < this.advisors.size(); i++) { - Advisor advisor = (Advisor) this.advisors.get(i); - if (advisor.getAdvice() != null && - adviceClass.isAssignableFrom(advisor.getAdvice().getClass())) { - count++; + if (adviceClass != null) { + for (Advisor advisor : this.advisors) { + if (adviceClass.isInstance(advisor.getAdvice())) { + count++; + } } } return count; @@ -460,7 +456,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { */ public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) { MethodCacheKey cacheKey = new MethodCacheKey(method); - List cached = (List) this.methodCache.get(cacheKey); + List cached = this.methodCache.get(cacheKey); if (cached == null) { cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice( this, method, targetClass); @@ -484,7 +480,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @param other the AdvisedSupport object to copy configuration from */ protected void copyConfigurationFrom(AdvisedSupport other) { - copyConfigurationFrom(other, other.targetSource, new ArrayList(other.advisors)); + copyConfigurationFrom(other, other.targetSource, new ArrayList(other.advisors)); } /** @@ -494,13 +490,12 @@ public class AdvisedSupport extends ProxyConfig implements Advised { * @param targetSource the new TargetSource * @param advisors the Advisors for the chain */ - protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List advisors) { + protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List advisors) { copyFrom(other); this.targetSource = targetSource; this.advisorChainFactory = other.advisorChainFactory; - this.interfaces = new ArrayList(other.interfaces); - for (Iterator it = advisors.iterator(); it.hasNext();) { - Advisor advisor = (Advisor) it.next(); + this.interfaces = new ArrayList(other.interfaces); + for (Advisor advisor : advisors) { if (advisor instanceof IntroductionAdvisor) { validateIntroductionAdvisor((IntroductionAdvisor) advisor); } @@ -549,8 +544,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised { */ @Override public String toString() { - StringBuffer sb = new StringBuffer(getClass().getName() + ": "); - sb.append(this.interfaces.size()).append(" interfaces "); + StringBuilder sb = new StringBuilder(getClass().getName()); + sb.append(": ").append(this.interfaces.size()).append(" interfaces "); sb.append(ClassUtils.classNamesToString(this.interfaces)).append("; "); sb.append(this.advisors.size()).append(" advisors "); sb.append(this.advisors).append("; "); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java index fcaaf7d33e5..53bb3b19c55 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AdvisorChainFactory.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. @@ -35,6 +35,7 @@ public interface AdvisorChainFactory { * @param targetClass the target class * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers) */ - List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass); + List getInterceptorsAndDynamicInterceptionAdvice( + Advised config, Method method, Class targetClass); } diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java index 0d78453adff..54e73e13a12 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.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.aop.framework; import java.util.Arrays; import org.springframework.aop.SpringProxy; -import org.springframework.aop.support.AopUtils; import org.springframework.util.Assert; /** @@ -35,27 +34,6 @@ import org.springframework.util.Assert; */ public abstract class AopProxyUtils { - /** - * Determine the target class of the given bean instance, - * which might be an AOP proxy. - *

Returns the target class for an AOP proxy and the plain class else. - * @param candidate the instance to check (might be an AOP proxy) - * @return the target class (or the plain class of the given object as fallback) - * @deprecated as of Spring 2.0.3, in favor of AopUtils.getTargetClass - * @see org.springframework.aop.support.AopUtils#getTargetClass(Object) - */ - @Deprecated - public static Class getTargetClass(Object candidate) { - Assert.notNull(candidate, "Candidate object must not be null"); - if (AopUtils.isCglibProxy(candidate)) { - return candidate.getClass().getSuperclass(); - } - if (candidate instanceof Advised) { - return ((Advised) candidate).getTargetSource().getTargetClass(); - } - return candidate.getClass(); - } - /** * Determine the complete set of interfaces to proxy for the given AOP configuration. *

This will always add the {@link Advised} interface unless the AdvisedSupport's diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java index 84c04967591..806e3602bc9 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/DefaultAdvisorChainFactory.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. @@ -45,15 +45,15 @@ import org.springframework.aop.support.MethodMatchers; */ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable { - public List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass) { + public List getInterceptorsAndDynamicInterceptionAdvice( + Advised config, Method method, Class targetClass) { + // This is somewhat tricky... we have to process introductions first, // but we need to preserve order in the ultimate list. - List interceptorList = new ArrayList(config.getAdvisors().length); + List interceptorList = new ArrayList(config.getAdvisors().length); boolean hasIntroductions = hasMatchingIntroductions(config, targetClass); AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance(); - Advisor[] advisors = config.getAdvisors(); - for (int i = 0; i < advisors.length; i++) { - Advisor advisor = advisors[i]; + for (Advisor advisor : config.getAdvisors()) { if (advisor instanceof PointcutAdvisor) { // Add it conditionally. PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; @@ -64,8 +64,8 @@ public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializ if (mm.isRuntime()) { // Creating a new object instance in the getInterceptors() method // isn't a problem as we normally cache created chains. - for (int j = 0; j < interceptors.length; j++) { - interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptors[j], mm)); + for (MethodInterceptor interceptor : interceptors) { + interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm)); } } else { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java index 905fb85a83f..a256e95c362 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/ProxyConfig.java @@ -160,7 +160,7 @@ public class ProxyConfig implements Serializable { @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("proxyTargetClass=").append(this.proxyTargetClass).append("; "); sb.append("optimize=").append(this.optimize).append("; "); sb.append("opaque=").append(this.opaque).append("; "); 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 1290a301594..c487b512fa3 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 @@ -265,7 +265,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea @Override public String toString() { // Don't do toString on target, it may be proxied. - StringBuffer sb = new StringBuffer("ReflectiveMethodInvocation: "); + StringBuilder sb = new StringBuilder("ReflectiveMethodInvocation: "); sb.append(this.method).append("; "); if (this.target == null) { sb.append("target is null"); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java index 36b14384014..56262b29889 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.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,6 +19,7 @@ package org.springframework.aop.framework.autoproxy; import java.util.Collections; import java.util.List; +import org.springframework.aop.Advisor; import org.springframework.aop.TargetSource; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactory; @@ -82,9 +83,9 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @see #sortAdvisors * @see #extendAdvisors */ - protected List findEligibleAdvisors(Class beanClass, String beanName) { - List candidateAdvisors = findCandidateAdvisors(); - List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); + protected List findEligibleAdvisors(Class beanClass, String beanName) { + List candidateAdvisors = findCandidateAdvisors(); + List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); if (!eligibleAdvisors.isEmpty()) { eligibleAdvisors = sortAdvisors(eligibleAdvisors); } @@ -96,7 +97,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * Find all candidate Advisors to use in auto-proxying. * @return the List of candidate Advisors */ - protected List findCandidateAdvisors() { + protected List findCandidateAdvisors() { return this.advisorRetrievalHelper.findAdvisorBeans(); } @@ -109,7 +110,9 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @return the List of applicable Advisors * @see ProxyCreationContext#getCurrentProxiedBeanName() */ - protected List findAdvisorsThatCanApply(List candidateAdvisors, Class beanClass, String beanName) { + protected List findAdvisorsThatCanApply( + List candidateAdvisors, Class beanClass, String beanName) { + ProxyCreationContext.setCurrentProxiedBeanName(beanName); try { return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); @@ -137,7 +140,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @see org.springframework.core.Ordered * @see org.springframework.core.OrderComparator */ - protected List sortAdvisors(List advisors) { + protected List sortAdvisors(List advisors) { Collections.sort(advisors, new OrderComparator()); return advisors; } @@ -151,7 +154,7 @@ public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyC * @param candidateAdvisors Advisors that have already been identified as * applying to a given bean */ - protected void extendAdvisors(List candidateAdvisors) { + protected void extendAdvisors(List candidateAdvisors) { } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java index 8376f97b5b9..d735500922a 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java @@ -25,6 +25,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.aopalliance.aop.Advice; import org.apache.commons.logging.Log; @@ -46,7 +47,6 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; -import org.springframework.core.CollectionFactory; import org.springframework.core.Ordered; import org.springframework.util.ClassUtils; @@ -136,20 +136,15 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig private BeanFactory beanFactory; - /** - * Set of bean name Strings, referring to all beans that this auto-proxy creator - * created a custom TargetSource for. Used to detect own pre-built proxies (from - * "postProcessBeforeInstantiation") in the "postProcessAfterInitialization" method. - */ - private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); + private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); - private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); + private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); - private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); + private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); - private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); + private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); - private final Map proxyTypes = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map proxyTypes = new ConcurrentHashMap(); /** @@ -260,7 +255,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig public Class predictBeanType(Class beanClass, String beanName) { Object cacheKey = getCacheKey(beanClass, beanName); - return (Class) this.proxyTypes.get(cacheKey); + return this.proxyTypes.get(cacheKey); } public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { @@ -280,7 +275,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig if (this.advisedBeans.contains(cacheKey) || this.nonAdvisedBeans.contains(cacheKey)) { return null; } - if (isInfrastructureClass(beanClass, beanName) || shouldSkip(beanClass, beanName)) { + if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { this.nonAdvisedBeans.add(cacheKey); return null; } @@ -355,7 +350,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig if (this.nonAdvisedBeans.contains(cacheKey)) { return bean; } - if (isInfrastructureClass(bean.getClass(), beanName) || shouldSkip(bean.getClass(), beanName)) { + if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.nonAdvisedBeans.add(cacheKey); return bean; } @@ -373,17 +368,6 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig return bean; } - /** - * Return whether the given bean class and bean name represents an - * infrastructure class that should never be proxied. - * @deprecated in favor of isInfrastructureClass(beanClass) - * @see #isInfrastructureClass(Class) - */ - @Deprecated - protected boolean isInfrastructureClass(Class beanClass, String beanName) { - return isInfrastructureClass(beanClass); - } - /** * Return whether the given bean class represents an infrastructure class * that should never be proxied. @@ -432,8 +416,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // We can't create fancy target sources for directly registered singletons. if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) { - for (int i = 0; i < this.customTargetSourceCreators.length; i++) { - TargetSourceCreator tsc = this.customTargetSourceCreators[i]; + for (TargetSourceCreator tsc : this.customTargetSourceCreators) { TargetSource ts = tsc.getTargetSource(beanClass, beanName); if (ts != null) { // Found a matching TargetSource. @@ -472,14 +455,14 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // Must allow for introductions; can't just set interfaces to // the target's interfaces only. Class[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader); - for (int i = 0; i < targetInterfaces.length; i++) { - proxyFactory.addInterface(targetInterfaces[i]); + for (Class targetInterface : targetInterfaces) { + proxyFactory.addInterface(targetInterface); } } Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); - for (int i = 0; i < advisors.length; i++) { - proxyFactory.addAdvisor(advisors[i]); + for (Advisor advisor : advisors) { + proxyFactory.addAdvisor(advisor); } proxyFactory.setTargetSource(targetSource); @@ -536,7 +519,7 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig // Handle prototypes correctly... Advisor[] commonInterceptors = resolveInterceptorNames(); - List allInterceptors = new ArrayList(); + List allInterceptors = new ArrayList(); if (specificInterceptors != null) { allInterceptors.addAll(Arrays.asList(specificInterceptors)); if (commonInterceptors != null) { @@ -567,17 +550,16 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig * @see #setInterceptorNames */ private Advisor[] resolveInterceptorNames() { - ConfigurableBeanFactory cbf = - (this.beanFactory instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) this.beanFactory : null); - List advisors = new ArrayList(); - for (int i = 0; i < this.interceptorNames.length; i++) { - String beanName = this.interceptorNames[i]; + ConfigurableBeanFactory cbf = (this.beanFactory instanceof ConfigurableBeanFactory) ? + (ConfigurableBeanFactory) this.beanFactory : null; + List advisors = new ArrayList(); + for (String beanName : this.interceptorNames) { if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) { Object next = this.beanFactory.getBean(beanName); advisors.add(this.advisorAdapterRegistry.wrap(next)); } } - return (Advisor[]) advisors.toArray(new Advisor[advisors.size()]); + return advisors.toArray(new Advisor[advisors.size()]); } /** diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java index 40ed9e85e71..49a964f1b27 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.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. @@ -79,12 +79,11 @@ public class BeanFactoryAdvisorRetrievalHelper { return new LinkedList(); } - List advisors = new LinkedList(); - for (int i = 0; i < advisorNames.length; i++) { - String name = advisorNames[i]; + List advisors = new LinkedList(); + for (String name : advisorNames) { if (isEligibleBean(name) && !this.beanFactory.isCurrentlyInCreation(name)) { try { - advisors.add(this.beanFactory.getBean(name)); + advisors.add(this.beanFactory.getBean(name, Advisor.class)); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java index 084c906f1d9..cec7f9907b1 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.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. @@ -17,7 +17,6 @@ package org.springframework.aop.framework.autoproxy; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.springframework.aop.TargetSource; @@ -45,7 +44,7 @@ import org.springframework.util.StringUtils; */ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { - private List beanNames; + private List beanNames; /** @@ -62,9 +61,9 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { */ public void setBeanNames(String[] beanNames) { Assert.notEmpty(beanNames, "'beanNames' must not be empty"); - this.beanNames = new ArrayList(beanNames.length); - for (int i = 0; i < beanNames.length; i++) { - this.beanNames.add(StringUtils.trimWhitespace(beanNames[i])); + this.beanNames = new ArrayList(beanNames.length); + for (String mappedName : beanNames) { + this.beanNames.add(StringUtils.trimWhitespace(mappedName)); } } @@ -75,8 +74,7 @@ public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { @Override protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { if (this.beanNames != null) { - for (Iterator it = this.beanNames.iterator(); it.hasNext();) { - String mappedName = (String) it.next(); + for (String mappedName : this.beanNames) { if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { continue; diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java index 3ce05a06811..0c257c1c506 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java @@ -95,7 +95,7 @@ public abstract class AbstractMonitoringInterceptor extends AbstractTraceInterce * @see #setSuffix */ protected String createInvocationTraceName(MethodInvocation invocation) { - StringBuffer sb = new StringBuffer(getPrefix()); + StringBuilder sb = new StringBuilder(getPrefix()); Method method = invocation.getMethod(); Class clazz = method.getDeclaringClass(); if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java index fa20d21a2d8..db00bcbbf6f 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java @@ -423,7 +423,7 @@ public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { * here for JDK 1.4 compliance reasons only. */ private String escape(String input) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == '\\') { diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java b/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java index 43cab6981ae..2f441102cbd 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/support/AopUtils.java @@ -20,7 +20,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -35,7 +34,6 @@ import org.springframework.aop.PointcutAdvisor; import org.springframework.aop.SpringProxy; import org.springframework.aop.TargetClassAware; import org.springframework.core.BridgeMethodResolver; -import org.springframework.core.JdkVersion; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -88,7 +86,7 @@ public abstract class AopUtils { * @param clazz the class to check */ public static boolean isCglibProxyClass(Class clazz) { - return (clazz != null && clazz.getName().indexOf(ClassUtils.CGLIB_CLASS_SEPARATOR) != -1); + return (clazz != null && clazz.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)); } /** @@ -162,10 +160,7 @@ public abstract class AopUtils { public static Method getMostSpecificMethod(Method method, Class targetClass) { Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the original method. - if (JdkVersion.isAtLeastJava15()) { - resolvedMethod = BridgeMethodResolver.findBridgedMethod(resolvedMethod); - } - return resolvedMethod; + return BridgeMethodResolver.findBridgedMethod(resolvedMethod); } @@ -202,15 +197,14 @@ public abstract class AopUtils { introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; } - Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); + Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); classes.add(targetClass); - for (Iterator it = classes.iterator(); it.hasNext();) { - Class clazz = (Class) it.next(); + for (Class clazz : classes) { Method[] methods = clazz.getMethods(); - for (int j = 0; j < methods.length; j++) { + for (Method method : methods) { if ((introductionAwareMethodMatcher != null && - introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) || - methodMatcher.matches(methods[j], targetClass)) { + introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) || + methodMatcher.matches(method, targetClass)) { return true; } } @@ -263,20 +257,18 @@ public abstract class AopUtils { * @return sublist of Advisors that can apply to an object of the given class * (may be the incoming List as-is) */ - public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { + public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { if (candidateAdvisors.isEmpty()) { return candidateAdvisors; } - List eligibleAdvisors = new LinkedList(); - for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { - Advisor candidate = (Advisor) it.next(); + List eligibleAdvisors = new LinkedList(); + for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { eligibleAdvisors.add(candidate); } } boolean hasIntroductions = !eligibleAdvisors.isEmpty(); - for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { - Advisor candidate = (Advisor) it.next(); + for (Advisor candidate : candidateAdvisors) { if (candidate instanceof IntroductionAdvisor) { // already processed continue; diff --git a/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java b/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java index fcd7bc862f7..f8a0e3a50d7 100644 --- a/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java +++ b/org.springframework.aop/src/main/java/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java @@ -204,7 +204,7 @@ public abstract class AbstractBeanFactoryBasedTargetSource @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(ClassUtils.getShortName(getClass())); sb.append(" for target bean '").append(this.targetBeanName).append("'"); if (this.targetClass != null) { diff --git a/org.springframework.beans/beans.iml b/org.springframework.beans/beans.iml index 595f99187d4..733bb27def4 100644 --- a/org.springframework.beans/beans.iml +++ b/org.springframework.beans/beans.iml @@ -1,99 +1,99 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java index 40942327957..2df53e11b02 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.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,7 +17,6 @@ package org.springframework.beans; import java.util.Arrays; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -66,11 +65,10 @@ public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySup public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid) throws BeansException { - List propertyAccessExceptions = null; - List propertyValues = (pvs instanceof MutablePropertyValues ? + List propertyAccessExceptions = null; + List propertyValues = (pvs instanceof MutablePropertyValues ? ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues())); - for (Iterator it = propertyValues.iterator(); it.hasNext();) { - PropertyValue pv = (PropertyValue) it.next(); + for (PropertyValue pv : propertyValues) { try { // This method may throw any BeansException, which won't be caught // here, if there is a critical failure such as no matching field. @@ -91,7 +89,7 @@ public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySup } catch (PropertyAccessException ex) { if (propertyAccessExceptions == null) { - propertyAccessExceptions = new LinkedList(); + propertyAccessExceptions = new LinkedList(); } propertyAccessExceptions.add(ex); } @@ -99,7 +97,7 @@ public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySup // If we encountered individual exceptions, throw the composite exception. if (propertyAccessExceptions != null) { - PropertyAccessException[] paeArray = (PropertyAccessException[]) + PropertyAccessException[] paeArray = propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]); throw new PropertyBatchUpdateException(paeArray); } 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 d41cb645aa1..1c69257f064 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 @@ -56,7 +56,8 @@ public abstract class BeanUtils { private static final Log logger = LogFactory.getLog(BeanUtils.class); - private static final Map unknownEditorTypes = Collections.synchronizedMap(new WeakHashMap()); + private static final Map unknownEditorTypes = + Collections.synchronizedMap(new WeakHashMap()); /** @@ -75,7 +76,7 @@ public abstract class BeanUtils { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { - return instantiateClass(clazz.getDeclaredConstructor((Class[]) null), null); + return instantiateClass(clazz.getDeclaredConstructor()); } catch (NoSuchMethodException ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); @@ -93,7 +94,7 @@ public abstract class BeanUtils { * @return the new instance * @throws BeanInstantiationException if the bean cannot be instantiated */ - public static Object instantiateClass(Constructor ctor, Object[] args) throws BeanInstantiationException { + public static Object instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException { Assert.notNull(ctor, "Constructor must not be null"); try { ReflectionUtils.makeAccessible(ctor); @@ -224,12 +225,11 @@ public abstract class BeanUtils { Method targetMethod = null; int numMethodsFoundWithCurrentMinimumArgs = 0; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(methodName)) { - int numParams = methods[i].getParameterTypes().length; - if (targetMethod == null || - numParams < targetMethod.getParameterTypes().length) { - targetMethod = methods[i]; + for (Method method : methods) { + if (method.getName().equals(methodName)) { + int numParams = method.getParameterTypes().length; + if (targetMethod == null || numParams < targetMethod.getParameterTypes().length) { + targetMethod = method; numMethodsFoundWithCurrentMinimumArgs = 1; } else { @@ -341,8 +341,7 @@ public abstract class BeanUtils { public static PropertyDescriptor findPropertyForMethod(Method method) throws BeansException { Assert.notNull(method, "Method must not be null"); PropertyDescriptor[] pds = getPropertyDescriptors(method.getDeclaringClass()); - for (int i = 0; i < pds.length; i++) { - PropertyDescriptor pd = pds[i]; + for (PropertyDescriptor pd : pds) { if (method.equals(pd.getReadMethod()) || method.equals(pd.getWriteMethod())) { return pd; } @@ -360,7 +359,7 @@ public abstract class BeanUtils { * @return the corresponding editor, or null if none found */ public static PropertyEditor findEditorByConvention(Class targetType) { - if (targetType == null || unknownEditorTypes.containsKey(targetType)) { + if (targetType == null || targetType.isArray() || unknownEditorTypes.containsKey(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); @@ -400,8 +399,8 @@ public abstract class BeanUtils { */ public static Class findPropertyType(String propertyName, Class[] beanClasses) { if (beanClasses != null) { - for (int i = 0; i < beanClasses.length; i++) { - PropertyDescriptor pd = getPropertyDescriptor(beanClasses[i], propertyName); + for (Class beanClass : beanClasses) { + PropertyDescriptor pd = getPropertyDescriptor(beanClass, propertyName); if (pd != null) { return pd.getPropertyType(); } @@ -455,36 +454,6 @@ public abstract class BeanUtils { clazz.equals(Locale.class) || clazz.equals(Class.class); } - /** - * Determine if the given target type is assignable from the given value - * type, assuming setting by reflection. Considers primitive wrapper - * classes as assignable to the corresponding primitive types. - * @param targetType the target type - * @param valueType the value type that should be assigned to the target type - * @return if the target type is assignable from the value type - * @deprecated as of Spring 2.0, in favor of ClassUtils.isAssignable - * @see org.springframework.util.ClassUtils#isAssignable(Class, Class) - */ - @Deprecated - public static boolean isAssignable(Class targetType, Class valueType) { - return ClassUtils.isAssignable(targetType, valueType); - } - - /** - * Determine if the given type is assignable from the given value, - * assuming setting by reflection. Considers primitive wrapper classes - * as assignable to the corresponding primitive types. - * @param type the target type - * @param value the value that should be assigned to the type - * @return if the type is assignable from the value - * @deprecated as of Spring 2.0, in favor of ClassUtils.isAssignableValue - * @see org.springframework.util.ClassUtils#isAssignableValue(Class, Object) - */ - @Deprecated - public static boolean isAssignable(Class type, Object value) { - return ClassUtils.isAssignableValue(type, value); - } - /** * Copy the property values of the given source bean into the target bean. @@ -571,8 +540,7 @@ public abstract class BeanUtils { PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; - for (int i = 0; i < targetPds.length; i++) { - PropertyDescriptor targetPd = targetPds[i]; + for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); @@ -582,12 +550,12 @@ public abstract class BeanUtils { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } - Object value = readMethod.invoke(source, new Object[0]); + Object value = readMethod.invoke(source); Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } - writeMethod.invoke(target, new Object[] {value}); + writeMethod.invoke(target, value); } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java index 3a294a66c38..3e18122ba74 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapper.java @@ -52,15 +52,6 @@ import java.beans.PropertyDescriptor; */ public interface BeanWrapper extends ConfigurablePropertyAccessor { - /** - * Change the wrapped JavaBean object. - * @param obj the bean instance to wrap - * @deprecated as of Spring 2.5, - * in favor of recreating a BeanWrapper per target instance - */ - @Deprecated - void setWrappedInstance(Object obj); - /** * Return the bean instance wrapped by this object, if any. * @return the bean instance, or null if none set 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 c596c8ed159..1b4251b7f91 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 @@ -33,7 +33,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.GenericCollectionTypeResolver; -import org.springframework.core.JdkVersion; import org.springframework.core.MethodParameter; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; @@ -349,15 +348,6 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra return false; } - /** - * @deprecated in favor of convertIfNecessary - * @see #convertIfNecessary(Object, Class) - */ - @Deprecated - public Object doTypeConversionIfNecessary(Object value, Class requiredType) throws TypeMismatchException { - return convertIfNecessary(value, requiredType, null); - } - public Object convertIfNecessary( Object value, Class requiredType, MethodParameter methodParam) throws TypeMismatchException { try { @@ -584,10 +574,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra } else if (value instanceof Map) { Map map = (Map) value; - Class mapKeyType = null; - if (JdkVersion.isAtLeastJava15()) { - mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); - } + Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. Object convertedMapKey = this.typeConverterDelegate.convertIfNecessary(key, mapKeyType); @@ -711,11 +698,8 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra } else if (propValue instanceof List) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); - Class requiredType = null; - if (JdkVersion.isAtLeastJava15()) { - requiredType = GenericCollectionTypeResolver.getCollectionReturnType( - pd.getReadMethod(), tokens.keys.length); - } + Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType( + pd.getReadMethod(), tokens.keys.length); List list = (List) propValue; int index = Integer.parseInt(key); Object oldValue = null; @@ -751,14 +735,10 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra } else if (propValue instanceof Map) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); - Class mapKeyType = null; - Class mapValueType = null; - if (JdkVersion.isAtLeastJava15()) { - mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType( - pd.getReadMethod(), tokens.keys.length); - mapValueType = GenericCollectionTypeResolver.getMapValueReturnType( - pd.getReadMethod(), tokens.keys.length); - } + Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType( + pd.getReadMethod(), tokens.keys.length); + Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType( + pd.getReadMethod(), tokens.keys.length); Map map = (Map) propValue; Object convertedMapKey = null; Object convertedMapValue = null; @@ -870,7 +850,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra @Override public String toString() { - StringBuffer sb = new StringBuffer(getClass().getName()); + StringBuilder sb = new StringBuilder(getClass().getName()); if (this.object != null) { sb.append(": wrapping object [").append(ObjectUtils.identityToString(this.object)).append("]"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java b/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java index dcbbb3af6ae..64f5e776441 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java @@ -33,7 +33,6 @@ import java.util.WeakHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.core.JdkVersion; import org.springframework.util.ClassUtils; /** @@ -64,14 +63,14 @@ public class CachedIntrospectionResults { * Set of ClassLoaders that this CachedIntrospectionResults class will always * accept classes from, even if the classes do not qualify as cache-safe. */ - static final Set acceptedClassLoaders = Collections.synchronizedSet(new HashSet()); + static final Set acceptedClassLoaders = Collections.synchronizedSet(new HashSet()); /** * Map keyed by class containing CachedIntrospectionResults. * Needs to be a WeakHashMap with WeakReferences as values to allow * for proper garbage collection in case of multiple class loaders. */ - static final Map classCache = Collections.synchronizedMap(new WeakHashMap()); + static final Map classCache = Collections.synchronizedMap(new WeakHashMap()); /** @@ -150,7 +149,7 @@ public class CachedIntrospectionResults { if (logger.isDebugEnabled()) { logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe"); } - classCache.put(beanClass, new WeakReference(results)); + classCache.put(beanClass, new WeakReference(results)); } } return results; @@ -166,9 +165,9 @@ public class CachedIntrospectionResults { private static boolean isClassLoaderAccepted(ClassLoader classLoader) { // Iterate over array copy in order to avoid synchronization for the entire // ClassLoader check (avoiding a synchronized acceptedClassLoaders Iterator). - Object[] acceptedLoaderArray = acceptedClassLoaders.toArray(); - for (int i = 0; i < acceptedLoaderArray.length; i++) { - ClassLoader registeredLoader = (ClassLoader) acceptedLoaderArray[i]; + ClassLoader[] acceptedLoaderArray = + acceptedClassLoaders.toArray(new ClassLoader[acceptedClassLoaders.size()]); + for (ClassLoader registeredLoader : acceptedLoaderArray) { if (isUnderneathClassLoader(classLoader, registeredLoader)) { return true; } @@ -204,7 +203,7 @@ public class CachedIntrospectionResults { private final BeanInfo beanInfo; /** PropertyDescriptor objects keyed by property name String */ - private final Map propertyDescriptorCache; + private final Map propertyDescriptorCache; /** @@ -233,23 +232,19 @@ public class CachedIntrospectionResults { if (logger.isTraceEnabled()) { logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]"); } - this.propertyDescriptorCache = new HashMap(); + this.propertyDescriptorCache = new HashMap(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); - for (int i = 0; i < pds.length; i++) { - PropertyDescriptor pd = pds[i]; + for (PropertyDescriptor pd : pds) { if (logger.isTraceEnabled()) { logger.trace("Found bean property '" + pd.getName() + "'" + - (pd.getPropertyType() != null ? - " of type [" + pd.getPropertyType().getName() + "]" : "") + + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") + (pd.getPropertyEditorClass() != null ? - "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); - } - if (JdkVersion.isAtLeastJava15()) { - pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), - pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass()); + "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); } + pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(), + pd.getWriteMethod(), pd.getPropertyEditorClass()); this.propertyDescriptorCache.put(pd.getName(), pd); } } @@ -267,7 +262,7 @@ public class CachedIntrospectionResults { } PropertyDescriptor getPropertyDescriptor(String propertyName) { - return (PropertyDescriptor) this.propertyDescriptorCache.get(propertyName); + return this.propertyDescriptorCache.get(propertyName); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java b/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java index 8396a72a841..33c14976c2f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/MutablePropertyValues.java @@ -19,7 +19,6 @@ package org.springframework.beans; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -39,9 +38,9 @@ import org.springframework.util.StringUtils; public class MutablePropertyValues implements PropertyValues, Serializable { /** List of PropertyValue objects */ - private final List propertyValueList; + private final List propertyValueList; - private Set processedProperties; + private Set processedProperties; private volatile boolean converted = false; @@ -53,7 +52,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { * @see #addPropertyValue(String, Object) */ public MutablePropertyValues() { - this.propertyValueList = new ArrayList(); + this.propertyValueList = new ArrayList(); } /** @@ -68,14 +67,13 @@ public class MutablePropertyValues implements PropertyValues, Serializable { // There is no replacement of existing property values. if (original != null) { PropertyValue[] pvs = original.getPropertyValues(); - this.propertyValueList = new ArrayList(pvs.length); - for (int i = 0; i < pvs.length; i++) { - PropertyValue newPv = new PropertyValue(pvs[i]); - this.propertyValueList.add(newPv); + this.propertyValueList = new ArrayList(pvs.length); + for (PropertyValue pv : pvs) { + this.propertyValueList.add(new PropertyValue(pv)); } } else { - this.propertyValueList = new ArrayList(0); + this.propertyValueList = new ArrayList(0); } } @@ -84,20 +82,17 @@ public class MutablePropertyValues implements PropertyValues, Serializable { * @param original Map with property values keyed by property name Strings * @see #addPropertyValues(Map) */ - public MutablePropertyValues(Map original) { + public MutablePropertyValues(Map original) { // We can optimize this because it's all new: // There is no replacement of existing property values. if (original != null) { - this.propertyValueList = new ArrayList(original.size()); - Iterator it = original.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - PropertyValue newPv = new PropertyValue((String) entry.getKey(), entry.getValue()); - this.propertyValueList.add(newPv); + this.propertyValueList = new ArrayList(original.size()); + for (Map.Entry entry : original.entrySet()) { + this.propertyValueList.add(new PropertyValue(entry.getKey().toString(), entry.getValue())); } } else { - this.propertyValueList = new ArrayList(0); + this.propertyValueList = new ArrayList(0); } } @@ -108,8 +103,9 @@ public class MutablePropertyValues implements PropertyValues, Serializable { * It is not intended for typical programmatic use. * @param propertyValueList List of PropertyValue objects */ - public MutablePropertyValues(List propertyValueList) { - this.propertyValueList = (propertyValueList != null ? propertyValueList : new ArrayList()); + public MutablePropertyValues(List propertyValueList) { + this.propertyValueList = + (propertyValueList != null ? propertyValueList : new ArrayList()); } @@ -119,7 +115,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { *

This is an accessor for optimized access to all PropertyValue objects. * It is not intended for typical programmatic use. */ - public List getPropertyValueList() { + public List getPropertyValueList() { return this.propertyValueList; } @@ -134,9 +130,8 @@ public class MutablePropertyValues implements PropertyValues, Serializable { public MutablePropertyValues addPropertyValues(PropertyValues other) { if (other != null) { PropertyValue[] pvs = other.getPropertyValues(); - for (int i = 0; i < pvs.length; i++) { - PropertyValue newPv = new PropertyValue(pvs[i]); - addPropertyValue(newPv); + for (PropertyValue pv : pvs) { + addPropertyValue(new PropertyValue(pv)); } } return this; @@ -149,13 +144,10 @@ public class MutablePropertyValues implements PropertyValues, Serializable { * @return this object to allow creating objects, adding multiple * PropertyValues in a single statement */ - public MutablePropertyValues addPropertyValues(Map other) { + public MutablePropertyValues addPropertyValues(Map other) { if (other != null) { - Iterator it = other.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - PropertyValue newPv = new PropertyValue((String) entry.getKey(), entry.getValue()); - addPropertyValue(newPv); + for (Map.Entry entry : other.entrySet()) { + addPropertyValue(new PropertyValue(entry.getKey().toString(), entry.getValue())); } } return this; @@ -170,7 +162,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { */ public MutablePropertyValues addPropertyValue(PropertyValue pv) { for (int i = 0; i < this.propertyValueList.size(); i++) { - PropertyValue currentPv = (PropertyValue) this.propertyValueList.get(i); + PropertyValue currentPv = this.propertyValueList.get(i); if (currentPv.getName().equals(pv.getName())) { pv = mergeIfRequired(pv, currentPv); setPropertyValueAt(pv, i); @@ -243,13 +235,11 @@ public class MutablePropertyValues implements PropertyValues, Serializable { public PropertyValue[] getPropertyValues() { - return (PropertyValue[]) - this.propertyValueList.toArray(new PropertyValue[this.propertyValueList.size()]); + return this.propertyValueList.toArray(new PropertyValue[this.propertyValueList.size()]); } public PropertyValue getPropertyValue(String propertyName) { - for (int i = 0; i < this.propertyValueList.size(); i++) { - PropertyValue pv = (PropertyValue) this.propertyValueList.get(i); + for (PropertyValue pv : this.propertyValueList) { if (pv.getName().equals(propertyName)) { return pv; } @@ -267,7 +257,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { */ public void registerProcessedProperty(String propertyName) { if (this.processedProperties == null) { - this.processedProperties = new HashSet(); + this.processedProperties = new HashSet(); } this.processedProperties.add(propertyName); } @@ -292,8 +282,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { } // for each property value in the new set - for (Iterator it = this.propertyValueList.iterator(); it.hasNext();) { - PropertyValue newPv = (PropertyValue) it.next(); + for (PropertyValue newPv : this.propertyValueList) { // if there wasn't an old one, add it PropertyValue pvOld = old.getPropertyValue(newPv.getName()); if (pvOld == null) { @@ -345,7 +334,7 @@ public class MutablePropertyValues implements PropertyValues, Serializable { @Override public String toString() { PropertyValue[] pvs = getPropertyValues(); - StringBuffer sb = new StringBuffer("PropertyValues: length=" + pvs.length + "; "); + StringBuilder sb = new StringBuilder("PropertyValues: length=" + pvs.length + "; "); sb.append(StringUtils.arrayToDelimitedString(pvs, "; ")); return sb.toString(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java index 3e5717e25ec..a433ec959d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyAccessorUtils.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. @@ -141,26 +141,26 @@ public abstract class PropertyAccessorUtils { return ""; } - StringBuffer buf = new StringBuffer(propertyName); + StringBuilder sb = new StringBuilder(propertyName); int searchIndex = 0; while (searchIndex != -1) { - int keyStart = buf.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX, searchIndex); + int keyStart = sb.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX, searchIndex); searchIndex = -1; if (keyStart != -1) { - int keyEnd = buf.indexOf( + int keyEnd = sb.indexOf( PropertyAccessor.PROPERTY_KEY_SUFFIX, keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length()); if (keyEnd != -1) { - String key = buf.substring(keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length(), keyEnd); + String key = sb.substring(keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length(), keyEnd); if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) { - buf.delete(keyStart + 1, keyStart + 2); - buf.delete(keyEnd - 2, keyEnd - 1); + sb.delete(keyStart + 1, keyStart + 2); + sb.delete(keyEnd - 2, keyEnd - 1); keyEnd = keyEnd - 2; } searchIndex = keyEnd + PropertyAccessor.PROPERTY_KEY_SUFFIX.length(); } } } - return buf.toString(); + return sb.toString(); } /** diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java index 0dff5620ec9..f15ba5a45a6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyBatchUpdateException.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. @@ -82,7 +82,7 @@ public class PropertyBatchUpdateException extends BeansException { @Override public String getMessage() { - StringBuffer sb = new StringBuffer("Failed properties: "); + StringBuilder sb = new StringBuilder("Failed properties: "); for (int i = 0; i < this.propertyAccessExceptions.length; i++) { sb.append(this.propertyAccessExceptions[i].getMessage()); if (i < this.propertyAccessExceptions.length - 1) { @@ -94,7 +94,7 @@ public class PropertyBatchUpdateException extends BeansException { @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()).append("; nested PropertyAccessExceptions ("); sb.append(getExceptionCount()).append(") are:"); for (int i = 0; i < this.propertyAccessExceptions.length; i++) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java index 1bda68f1956..688f5dff9d6 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/PropertyMatches.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. @@ -94,29 +94,29 @@ final class PropertyMatches { * indicating the possible property matches. */ public String buildErrorMessage() { - StringBuffer buf = new StringBuffer(); - buf.append("Bean property '"); - buf.append(this.propertyName); - buf.append("' is not writable or has an invalid setter method. "); + StringBuilder msg = new StringBuilder(); + msg.append("Bean property '"); + msg.append(this.propertyName); + msg.append("' is not writable or has an invalid setter method. "); if (ObjectUtils.isEmpty(this.possibleMatches)) { - buf.append("Does the parameter type of the setter match the return type of the getter?"); + msg.append("Does the parameter type of the setter match the return type of the getter?"); } else { - buf.append("Did you mean "); + msg.append("Did you mean "); for (int i = 0; i < this.possibleMatches.length; i++) { - buf.append('\''); - buf.append(this.possibleMatches[i]); + msg.append('\''); + msg.append(this.possibleMatches[i]); if (i < this.possibleMatches.length - 2) { - buf.append("', "); + msg.append("', "); } else if (i == this.possibleMatches.length - 2){ - buf.append("', or "); + msg.append("', or "); } } - buf.append("'?"); + msg.append("'?"); } - return buf.toString(); + return msg.toString(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java index 7d81091cd70..8f3c96e138e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java @@ -18,21 +18,17 @@ package org.springframework.beans; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; -import java.beans.PropertyEditorManager; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.Collection; -import java.util.Collections; import java.util.Iterator; import java.util.Map; -import java.util.WeakHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.CollectionFactory; import org.springframework.core.GenericCollectionTypeResolver; -import org.springframework.core.JdkVersion; import org.springframework.core.MethodParameter; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; @@ -53,8 +49,6 @@ class TypeConverterDelegate { private static final Log logger = LogFactory.getLog(TypeConverterDelegate.class); - private static final Map unknownEditorTypes = Collections.synchronizedMap(new WeakHashMap()); - private final PropertyEditorRegistrySupport propertyEditorRegistry; private final Object targetObject; @@ -195,7 +189,7 @@ class TypeConverterDelegate { } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { String strValue = ((String) convertedValue).trim(); - if (JdkVersion.isAtLeastJava15() && requiredType.isEnum() && "".equals(strValue)) { + if (requiredType.isEnum() && "".equals(strValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } @@ -216,7 +210,7 @@ class TypeConverterDelegate { if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { // Definitely doesn't match: throw IllegalArgumentException. - StringBuffer msg = new StringBuffer(); + StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); if (propertyName != null) { @@ -244,15 +238,7 @@ class TypeConverterDelegate { protected PropertyEditor findDefaultEditor(Class requiredType, PropertyDescriptor descriptor) { PropertyEditor editor = null; if (descriptor != null) { - if (JdkVersion.isAtLeastJava15()) { - editor = descriptor.createPropertyEditor(this.targetObject); - } - else { - Class editorClass = descriptor.getPropertyEditorClass(); - if (editorClass != null) { - editor = (PropertyEditor) BeanUtils.instantiateClass(editorClass); - } - } + editor = descriptor.createPropertyEditor(this.targetObject); } if (editor == null && requiredType != null) { // No custom editor -> check BeanWrapperImpl's default editors. @@ -260,19 +246,6 @@ class TypeConverterDelegate { if (editor == null && !String.class.equals(requiredType)) { // No BeanWrapper default editor -> check standard JavaBean editor. editor = BeanUtils.findEditorByConvention(requiredType); - if (editor == null && !unknownEditorTypes.containsKey(requiredType)) { - // Deprecated global PropertyEditorManager fallback... - editor = PropertyEditorManager.findEditor(requiredType); - if (editor == null) { - // Regular case as of Spring 2.5 - unknownEditorTypes.put(requiredType, Boolean.TRUE); - } - else { - logger.warn("PropertyEditor [" + editor.getClass().getName() + - "] found through deprecated global PropertyEditorManager fallback - " + - "consider using a more isolated form of registration, e.g. on the BeanWrapper/BeanFactory!"); - } - } } } return editor; @@ -425,7 +398,7 @@ class TypeConverterDelegate { Collection original, String propertyName, MethodParameter methodParam) { Class elementType = null; - if (methodParam != null && JdkVersion.isAtLeastJava15()) { + if (methodParam != null) { elementType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam); } if (elementType == null && @@ -475,7 +448,7 @@ class TypeConverterDelegate { protected Map convertToTypedMap(Map original, String propertyName, MethodParameter methodParam) { Class keyType = null; Class valueType = null; - if (methodParam != null && JdkVersion.isAtLeastJava15()) { + if (methodParam != null) { keyType = GenericCollectionTypeResolver.getMapKeyParameterType(methodParam); valueType = GenericCollectionTypeResolver.getMapValueParameterType(methodParam); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java index b08692e472e..486f9248e7d 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanCreationException.java @@ -18,7 +18,6 @@ package org.springframework.beans.factory; import java.io.PrintStream; import java.io.PrintWriter; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -37,7 +36,7 @@ public class BeanCreationException extends FatalBeanException { private String resourceDescription; - private List relatedCauses; + private List relatedCauses; /** @@ -129,7 +128,7 @@ public class BeanCreationException extends FatalBeanException { */ public void addRelatedCause(Throwable ex) { if (this.relatedCauses == null) { - this.relatedCauses = new LinkedList(); + this.relatedCauses = new LinkedList(); } this.relatedCauses.add(ex); } @@ -142,16 +141,15 @@ public class BeanCreationException extends FatalBeanException { if (this.relatedCauses == null) { return null; } - return (Throwable[]) this.relatedCauses.toArray(new Throwable[this.relatedCauses.size()]); + return this.relatedCauses.toArray(new Throwable[this.relatedCauses.size()]); } @Override public String toString() { - StringBuffer sb = new StringBuffer(super.toString()); + StringBuilder sb = new StringBuilder(super.toString()); if (this.relatedCauses != null) { - for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { - Throwable relatedCause = (Throwable) it.next(); + for (Throwable relatedCause : this.relatedCauses) { sb.append("\nRelated cause: "); sb.append(relatedCause); } @@ -164,8 +162,7 @@ public class BeanCreationException extends FatalBeanException { synchronized (ps) { super.printStackTrace(ps); if (this.relatedCauses != null) { - for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { - Throwable relatedCause = (Throwable) it.next(); + for (Throwable relatedCause : this.relatedCauses) { ps.println("Related cause:"); relatedCause.printStackTrace(ps); } @@ -178,8 +175,7 @@ public class BeanCreationException extends FatalBeanException { synchronized (pw) { super.printStackTrace(pw); if (this.relatedCauses != null) { - for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { - Throwable relatedCause = (Throwable) it.next(); + for (Throwable relatedCause : this.relatedCauses) { pw.println("Related cause:"); relatedCause.printStackTrace(pw); } @@ -193,8 +189,7 @@ public class BeanCreationException extends FatalBeanException { return true; } if (this.relatedCauses != null) { - for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { - Throwable relatedCause = (Throwable) it.next(); + for (Throwable relatedCause : this.relatedCauses) { if (relatedCause instanceof NestedRuntimeException && ((NestedRuntimeException) relatedCause).contains(exClass)) { return true; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java new file mode 100644 index 00000000000..ab2f2531b0d --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanExpressionException.java @@ -0,0 +1,47 @@ +/* + * 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; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception that indicates an expression evaluation attempt having failed. + * + * @author Juergen Hoeller + * @since 3.0 + */ +public class BeanExpressionException extends FatalBeanException { + + /** + * Create a new BeanExpressionException with the specified message. + * @param msg the detail message + */ + public BeanExpressionException(String msg) { + super(msg); + } + + /** + * Create a new BeanExpressionException with the specified message + * and root cause. + * @param msg the detail message + * @param cause the root cause + */ + public BeanExpressionException(String msg, Throwable cause) { + super(msg, cause); + } + +} \ No newline at end of file diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java index 98e4441121a..c31a4c8338e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.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. @@ -147,7 +147,7 @@ public interface BeanFactory { * @throws BeanNotOfRequiredTypeException if the bean is not of the required type * @throws BeansException if the bean could not be created */ - Object getBean(String name, Class requiredType) throws BeansException; + T getBean(String name, Class requiredType) throws BeansException; /** * Return an instance, which may be shared or independent, of the specified bean. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java index 501b52fab40..f2b4cbd4583 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java @@ -18,7 +18,6 @@ package org.springframework.beans.factory; import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -146,10 +145,9 @@ public abstract class BeanFactoryUtils { if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { String[] parentResult = beanNamesForTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type); - List resultList = new ArrayList(); + List resultList = new ArrayList(); resultList.addAll(Arrays.asList(result)); - for (int i = 0; i < parentResult.length; i++) { - String beanName = parentResult[i]; + for (String beanName : parentResult) { if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) { resultList.add(beanName); } @@ -190,10 +188,9 @@ public abstract class BeanFactoryUtils { if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { String[] parentResult = beanNamesForTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); - List resultList = new ArrayList(); + List resultList = new ArrayList(); resultList.addAll(Arrays.asList(result)); - for (int i = 0; i < parentResult.length; i++) { - String beanName = parentResult[i]; + for (String beanName : parentResult) { if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) { resultList.add(beanName); } @@ -216,20 +213,19 @@ public abstract class BeanFactoryUtils { * @return the Map of matching bean instances, or an empty Map if none * @throws BeansException if a bean could not be created */ - public static Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) - throws BeansException { + public static Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(4); result.putAll(lbf.getBeansOfType(type)); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { - Map parentResult = beansOfTypeIncludingAncestors( + Map parentResult = beansOfTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type); - for (Iterator it = parentResult.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String beanName = (String) entry.getKey(); + for (Map.Entry entry : parentResult.entrySet()) { + String beanName = entry.getKey(); if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { result.put(beanName, entry.getValue()); } @@ -261,21 +257,20 @@ public abstract class BeanFactoryUtils { * @return the Map of matching bean instances, or an empty Map if none * @throws BeansException if a bean could not be created */ - public static Map beansOfTypeIncludingAncestors( - ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) - throws BeansException { + public static Map beansOfTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); - Map result = new LinkedHashMap(4); + Map result = new LinkedHashMap(4); result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit)); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { - Map parentResult = beansOfTypeIncludingAncestors( + Map parentResult = beansOfTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); - for (Iterator it = parentResult.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String beanName = (String) entry.getKey(); + for (Map.Entry entry : parentResult.entrySet()) { + String beanName = entry.getKey(); if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { result.put(beanName, entry.getValue()); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java index 8a0472f2bec..4b8247f3689 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/FactoryBean.java @@ -50,7 +50,7 @@ package org.springframework.beans.factory; * @see org.springframework.aop.framework.ProxyFactoryBean * @see org.springframework.jndi.JndiObjectFactoryBean */ -public interface FactoryBean { +public interface FactoryBean { /** * Return an instance (possibly shared or independent) of the object @@ -69,7 +69,7 @@ public interface FactoryBean { * @throws Exception in case of creation errors * @see FactoryBeanNotInitializedException */ - Object getObject() throws Exception; + T getObject() throws Exception; /** * Return the type of object that this FactoryBean creates, @@ -90,7 +90,7 @@ public interface FactoryBean { * or null if not known at the time of the call * @see ListableBeanFactory#getBeansOfType */ - Class getObjectType(); + Class getObjectType(); /** * Is the object managed by this factory a singleton? That is, 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 fe3f909dcd9..c351f20cdc3 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 @@ -172,7 +172,7 @@ $ *

Does not consider any hierarchy this factory may participate in. * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) */ - Map getBeansOfType(Class type) throws BeansException; + Map getBeansOfType(Class type) throws BeansException; /** * Return the bean instances that match the given object type (including @@ -207,7 +207,7 @@ $ *

Does not consider any hierarchy this factory may participate in. * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) */ - Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java index a84d222c0f0..b81ee6ca378 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/ObjectFactory.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. @@ -35,7 +35,7 @@ import org.springframework.beans.BeansException; * @since 1.0.2 * @see FactoryBean */ -public interface ObjectFactory { +public interface ObjectFactory { /** * Return an instance (possibly shared or independent) @@ -43,6 +43,6 @@ public interface ObjectFactory { * @return an instance of the bean (should never be null) * @throws BeansException in case of creation errors */ - Object getObject() throws BeansException; + T getObject() throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java index f429b76acdb..c54676eda1e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/SmartFactoryBean.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,7 +38,7 @@ package org.springframework.beans.factory; * @see #isPrototype() * @see #isSingleton() */ -public interface SmartFactoryBean extends FactoryBean { +public interface SmartFactoryBean extends FactoryBean { /** * Is the object managed by this factory a prototype? That is, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index 4d71b43b409..5832b90cdb5 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -105,6 +105,8 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean private boolean requiredParameterValue = true; + private Class valueAnnotationType = Value.class; + private int order = Ordered.LOWEST_PRECEDENCE - 2; private ConfigurableListableBeanFactory beanFactory; @@ -193,22 +195,25 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean List candidates = new ArrayList(rawCandidates.length); Constructor requiredConstructor = null; Constructor defaultConstructor = null; - for (int i = 0; i < rawCandidates.length; i++) { - Constructor candidate = rawCandidates[i]; + for (Constructor candidate : rawCandidates) { Annotation annotation = candidate.getAnnotation(getAutowiredAnnotationType()); if (annotation != null) { if (requiredConstructor != null) { throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate + - ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); + ". Found another constructor with 'required' Autowired annotation: " + + requiredConstructor); } if (candidate.getParameterTypes().length == 0) { - throw new IllegalStateException("Autowired annotation requires at least one argument: " + candidate); + throw new IllegalStateException( + "Autowired annotation requires at least one argument: " + candidate); } boolean required = determineRequiredStatus(annotation); if (required) { if (!candidates.isEmpty()) { - throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates + - ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); + throw new BeanCreationException( + "Invalid autowire-marked constructors: " + candidates + + ". Found another constructor with 'required' Autowired annotation: " + + requiredConstructor); } requiredConstructor = candidate; } @@ -223,7 +228,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean if (requiredConstructor == null && defaultConstructor != null) { candidates.add(defaultConstructor); } - candidateConstructors = (Constructor[]) candidates.toArray(new Constructor[candidates.size()]); + candidateConstructors = candidates.toArray(new Constructor[candidates.size()]); } else { candidateConstructors = new Constructor[0]; @@ -329,7 +334,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean * @return the target beans, or an empty Collection if no bean of this type is found * @throws BeansException if bean retrieval failed */ - protected Map findAutowireCandidates(Class type) throws BeansException { + protected Map findAutowireCandidates(Class type) throws BeansException { if (this.beanFactory == null) { throw new IllegalStateException("No BeanFactory configured - " + "override the getBeanOfType method or specify the 'beanFactory' property"); @@ -361,12 +366,12 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean */ private void registerDependentBeans(String beanName, Set autowiredBeanNames) { if (beanName != null) { - for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) { - String autowiredBeanName = (String) it.next(); + for (String autowiredBeanName : autowiredBeanNames) { beanFactory.registerDependentBean(autowiredBeanName, beanName); if (logger.isDebugEnabled()) { - logger.debug("Autowiring by type from bean name '" + beanName + - "' to bean named '" + autowiredBeanName + "'"); + logger.debug( + "Autowiring by type from bean name '" + beanName + "' to bean named '" + autowiredBeanName + + "'"); } } } @@ -463,7 +468,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean // Explicit value provided as part of the bean definition. this.skip = Boolean.TRUE; } - if (this.skip != null && this.skip.booleanValue()) { + if (this.skip != null && this.skip) { return; } Method method = (Method) this.member; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java index ec44c70812a..cc1584c8438 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Qualifier.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,8 +32,8 @@ import java.lang.annotation.Target; * @author Juergen Hoeller * @since 2.5 */ -@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Inherited @Documented public @interface Qualifier { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java index 289db5b6427..f4497ad316e 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java @@ -109,7 +109,7 @@ public class QualifierAnnotationAutowireCandidateResolver implements AutowireCan } AbstractBeanDefinition bd = (AbstractBeanDefinition) bdHolder.getBeanDefinition(); SimpleTypeConverter typeConverter = new SimpleTypeConverter(); - Annotation[] annotations = (Annotation[]) descriptor.getAnnotations(); + Annotation[] annotations = descriptor.getAnnotations(); for (Annotation annotation : annotations) { Class type = annotation.annotationType(); if (isQualifier(type)) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java new file mode 100644 index 00000000000..beaba9be815 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/annotation/Value.java @@ -0,0 +1,18 @@ +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Juergen Hoeller + * @since 3.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) +public @interface Value { + + String value(); + +} 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 52c5fabe12a..15138353376 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 @@ -77,8 +77,8 @@ public abstract class AbstractFactoryBean /** - * Set if a singleton should be created, or a new object - * on each request else. Default is true (a singleton). + * Set if a singleton should be created, or a new object on each request + * otherwise. Default is true (a singleton). */ public void setSingleton(boolean singleton) { this.singleton = singleton; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java index 07f26595ecd..24fd58f233a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java @@ -312,6 +312,6 @@ public interface AutowireCapableBeanFactory extends BeanFactory { * @throws BeansException in dependency resolution failed */ Object resolveDependency(DependencyDescriptor descriptor, String beanName, - Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException; + Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException; } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java index 0176a914253..337bb9b93d9 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionHolder.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. @@ -119,7 +119,7 @@ public class BeanDefinitionHolder implements BeanMetadataElement { * @see #getAliases() */ public String getShortDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("Bean definition with name '").append(this.beanName).append("'"); if (this.aliases != null) { sb.append(" and aliases [").append(StringUtils.arrayToCommaDelimitedString(this.aliases)).append("]"); @@ -134,7 +134,7 @@ public class BeanDefinitionHolder implements BeanMetadataElement { * @see #getBeanDefinition() */ public String getLongDescription() { - StringBuffer sb = new StringBuffer(getShortDescription()); + StringBuilder sb = new StringBuilder(getShortDescription()); sb.append(": ").append(this.beanDefinition); return sb.toString(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java index 18e7380ae25..0b16a0557e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanDefinitionVisitor.java @@ -176,12 +176,19 @@ public class BeanDefinitionVisitor { visitBeanDefinition(((BeanDefinitionHolder) value).getBeanDefinition()); } else if (value instanceof RuntimeBeanReference) { - RuntimeBeanReference ref = (RuntimeBeanReference) value; - String newBeanName = resolveStringValue(ref.getBeanName()); + RuntimeBeanReference ref = (RuntimeBeanReference) value; + String newBeanName = resolveStringValue(ref.getBeanName()); if (!newBeanName.equals(ref.getBeanName())) { return new RuntimeBeanReference(newBeanName); } } + else if (value instanceof RuntimeBeanNameReference) { + RuntimeBeanNameReference ref = (RuntimeBeanNameReference) value; + String newBeanName = resolveStringValue(ref.getBeanName()); + if (!newBeanName.equals(ref.getBeanName())) { + return new RuntimeBeanNameReference(newBeanName); + } + } else if (value instanceof List) { visitList((List) value); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java new file mode 100644 index 00000000000..d6111964a25 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionContext.java @@ -0,0 +1,62 @@ +/* + * 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.config; + +import org.springframework.beans.factory.BeanFactory; + +/** + * Context object for evaluating an expression within a bean definition. + * + * @author Juergen Hoeller + * @since 3.0 + */ +public class BeanExpressionContext { + + private final BeanFactory beanFactory; + + private final Scope scope; + + + public BeanExpressionContext(BeanFactory beanFactory, Scope scope) { + this.beanFactory = beanFactory; + this.scope = scope; + } + + public final BeanFactory getBeanFactory() { + return this.beanFactory; + } + + public final Scope getScope() { + return this.scope; + } + + + public boolean containsObject(String key) { + return (this.beanFactory.containsBean(key) || + this.scope.resolveContextualObject(key) != null); + } + + public Object getObject(String key) { + if (this.beanFactory.containsBean(key)) { + return this.beanFactory.getBean(key); + } + else { + return this.scope.resolveContextualObject(key); + } + } + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java new file mode 100644 index 00000000000..589417d1a03 --- /dev/null +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/BeanExpressionResolver.java @@ -0,0 +1,45 @@ +/* + * 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.config; + +import org.springframework.beans.BeansException; + +/** + * Strategy interface for resolving a value through evaluating it + * as an expression, if applicable. + * + *

A raw {@link org.springframework.beans.factory.BeanFactory} does not + * contain a default implementation of this strategy. However, + * {@link org.springframework.context.ApplicationContext} implementations + * will provide expression support out of the box. + * + * @author Juergen Hoeller + * @since 3.0 + */ +public interface BeanExpressionResolver { + + /** + * Evaluate the given value as an expression, if applicable; + * return the value as-is otherwise. + * @param value the value to check + * @param evalContext the evaluation context + * @return the resolved value (potentially the given value as-is) + * @throws BeansException if evaluation failed + */ + Object evaluate(String value, BeanExpressionContext evalContext) throws BeansException; + +} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java index 12e082b3886..f3ec7a27404 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CommonsLogFactoryBean.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,6 +18,7 @@ package org.springframework.beans.factory.config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; @@ -30,10 +31,10 @@ import org.springframework.beans.factory.InitializingBean; * one Log instance per class name, e.g. for common log topics. * * @author Juergen Hoeller - * @see org.apache.commons.logging.Log * @since 16.11.2003 + * @see org.apache.commons.logging.Log */ -public class CommonsLogFactoryBean implements FactoryBean, InitializingBean { +public class CommonsLogFactoryBean implements FactoryBean, InitializingBean { private Log log; @@ -50,15 +51,15 @@ public class CommonsLogFactoryBean implements FactoryBean, InitializingBean { public void afterPropertiesSet() { if (this.log == null) { - throw new IllegalArgumentException("logName is required"); + throw new IllegalArgumentException("'logName' is required"); } } - public Object getObject() { - return log; + public Log getObject() { + return this.log; } - public Class getObjectType() { + public Class getObjectType() { return (this.log != null ? this.log.getClass() : Log.class); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java index a3f514482a9..706bfdedd8c 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java @@ -121,6 +121,19 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single */ boolean isCacheBeanMetadata(); + /** + * Specify the resolution strategy for expressions in bean definition values. + *

There is no expression support active in a BeanFactory by default. + * An ApplicationContext will typically set a standard expression strategy + * here, supporting "#{...}" expressions in a Unified EL compatible style. + */ + void setBeanExpressionResolver(BeanExpressionResolver resolver); + + /** + * Return the resolution strategy for expressions in bean definition values. + */ + BeanExpressionResolver getBeanExpressionResolver(); + /** * Add a PropertyEditorRegistrar to be applied to all bean creation processes. *

Such a registrar creates new PropertyEditor instances and registers them @@ -141,22 +154,7 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single * @param requiredType type of the property * @param propertyEditorClass the {@link PropertyEditor} class to register */ - void registerCustomEditor(Class requiredType, Class propertyEditorClass); - - /** - * Register the given custom property editor for all properties of the - * given type. To be invoked during factory configuration. - *

Note that this method will register a shared custom editor instance; - * access to that instance will be synchronized for thread-safety. It is - * generally preferable to use {@link #addPropertyEditorRegistrar} instead - * of this method, to avoid for the need for synchronization on custom editors. - * @param requiredType type of the property - * @param propertyEditor editor to register - * @deprecated as of Spring 2.0.7, in favor of {@link #addPropertyEditorRegistrar} - * and {@link #registerCustomEditor(Class, Class)} - */ - @Deprecated - void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor); + void registerCustomEditor(Class requiredType, Class propertyEditorClass); /** * Initialize the given PropertyEditorRegistry with the custom editors @@ -186,7 +184,12 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single /** * Add a new BeanPostProcessor that will get applied to beans created * by this factory. To be invoked during factory configuration. - * @param beanPostProcessor the bean processor to register + *

Note: Post-processors submitted here will be applied in the order of + * registration; any ordering semantics expressed through implementing the + * {@link org.springframework.core.Ordered} interface will be ignored. Note + * that autodetected post-processors (e.g. as beans in an ApplicationContext) + * will always be applied after programmatically registered ones. + * @param beanPostProcessor the post-processor to register */ void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 3d82150a72a..acbd3dd01fd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -17,7 +17,6 @@ package org.springframework.beans.factory.config; import java.beans.PropertyEditor; -import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; @@ -90,7 +89,7 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla private PropertyEditorRegistrar[] propertyEditorRegistrars; - private Map customEditors; + private Map customEditors; private boolean ignoreUnresolvableEditors = false; @@ -123,12 +122,10 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla * Specify the custom editors to register via a {@link Map}, using the * class name of the required type as the key and the class name of the * associated {@link PropertyEditor} as value. - *

Also supports {@link PropertyEditor} instances as values; however, - * this is deprecated since Spring 2.0.7 and will be removed in Spring 3.0. - * @param customEditors said Map of editors (can be null) + * @param customEditors said Map of editors (can be null) * @see ConfigurableListableBeanFactory#registerCustomEditor */ - public void setCustomEditors(Map customEditors) { + public void setCustomEditors(Map customEditors) { this.customEditors = customEditors; } @@ -151,45 +148,21 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.propertyEditorRegistrars != null) { - for (int i = 0; i < this.propertyEditorRegistrars.length; i++) { - beanFactory.addPropertyEditorRegistrar(this.propertyEditorRegistrars[i]); + for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) { + beanFactory.addPropertyEditorRegistrar(propertyEditorRegistrar); } } if (this.customEditors != null) { - for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - Object key = entry.getKey(); - Object value = entry.getValue(); + for (Map.Entry entry : this.customEditors.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); Class requiredType = null; try { - if (key instanceof Class) { - requiredType = (Class) key; - } - else if (key instanceof String) { - requiredType = ClassUtils.forName((String) key, this.beanClassLoader); - } - else { - throw new IllegalArgumentException( - "Invalid key [" + key + "] for custom editor: needs to be Class or String."); - } - - if (value instanceof PropertyEditor) { - beanFactory.registerCustomEditor(requiredType, (PropertyEditor) value); - } - else if (value instanceof Class) { - beanFactory.registerCustomEditor(requiredType, (Class) value); - } - else if (value instanceof String) { - Class editorClass = ClassUtils.forName((String) value, this.beanClassLoader); - beanFactory.registerCustomEditor(requiredType, editorClass); - } - else { - throw new IllegalArgumentException("Mapped value [" + value + "] for custom editor key [" + - key + "] is not of required type [" + PropertyEditor.class.getName() + - "] or a corresponding Class or String value indicating a PropertyEditor implementation"); - } + requiredType = ClassUtils.forName(key, this.beanClassLoader); + Class editorClass = ClassUtils.forName(value, this.beanClassLoader); + beanFactory.registerCustomEditor(requiredType, editorClass); } catch (ClassNotFoundException ex) { if (this.ignoreUnresolvableEditors) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java index 612d1b08e23..d2d36879b86 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java @@ -16,15 +16,12 @@ package org.springframework.beans.factory.config; +import java.lang.annotation.Annotation; import java.lang.reflect.Field; -import java.lang.reflect.Method; import org.springframework.core.GenericCollectionTypeResolver; -import org.springframework.core.JdkVersion; import org.springframework.core.MethodParameter; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; /** * Descriptor for a specific dependency that is about to be injected. @@ -36,10 +33,6 @@ import org.springframework.util.ReflectionUtils; */ public class DependencyDescriptor { - private static final Method fieldAnnotationsMethod = - ClassUtils.getMethodIfAvailable(Field.class, "getAnnotations", new Class[0]); - - private MethodParameter methodParameter; private Field field; @@ -48,7 +41,7 @@ public class DependencyDescriptor { private final boolean eager; - private Object[] fieldAnnotations; + private Annotation[] fieldAnnotations; /** @@ -147,9 +140,6 @@ public class DependencyDescriptor { * @return the generic type, or null if none */ public Class getCollectionType() { - if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { - return null; - } return (this.field != null ? GenericCollectionTypeResolver.getCollectionFieldType(this.field) : GenericCollectionTypeResolver.getCollectionParameterType(this.methodParameter)); @@ -160,9 +150,6 @@ public class DependencyDescriptor { * @return the generic type, or null if none */ public Class getMapKeyType() { - if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { - return null; - } return (this.field != null ? GenericCollectionTypeResolver.getMapKeyFieldType(this.field) : GenericCollectionTypeResolver.getMapKeyParameterType(this.methodParameter)); @@ -173,9 +160,6 @@ public class DependencyDescriptor { * @return the generic type, or null if none */ public Class getMapValueType() { - if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { - return null; - } return (this.field != null ? GenericCollectionTypeResolver.getMapValueFieldType(this.field) : GenericCollectionTypeResolver.getMapValueParameterType(this.methodParameter)); @@ -183,20 +167,12 @@ public class DependencyDescriptor { /** * Obtain the annotations associated with the wrapped parameter/field, if any. - * @return the parameter/field annotations, or null if there is - * no annotation support (on JDK < 1.5). The return value is an Object array - * instead of an Annotation array simply for compatibility with older JDKs; - * feel free to cast it to Annotation[] on JDK 1.5 or higher. */ - public Object[] getAnnotations() { + public Annotation[] getAnnotations() { if (this.field != null) { - if (this.fieldAnnotations != null) { - return this.fieldAnnotations; + if (this.fieldAnnotations == null) { + this.fieldAnnotations = this.field.getAnnotations(); } - if (fieldAnnotationsMethod == null) { - return null; - } - this.fieldAnnotations = (Object[]) ReflectionUtils.invokeMethod(fieldAnnotationsMethod, this.field); return this.fieldAnnotations; } else { 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 88a72972094..6d40aba2d69 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 @@ -83,7 +83,7 @@ public class ListFactoryBean extends AbstractFactoryBean { result = new ArrayList(this.sourceList.size()); } Class valueType = null; - if (this.targetListClass != null && JdkVersion.isAtLeastJava15()) { + if (this.targetListClass != null) { valueType = GenericCollectionTypeResolver.getCollectionType(this.targetListClass); } if (valueType != null) { 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 8a6ece50a64..a20f29120dc 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 @@ -84,7 +84,7 @@ public class MapFactoryBean extends AbstractFactoryBean { } Class keyType = null; Class valueType = null; - if (this.targetMapClass != null && JdkVersion.isAtLeastJava15()) { + if (this.targetMapClass != null) { keyType = GenericCollectionTypeResolver.getMapKeyType(this.targetMapClass); valueType = GenericCollectionTypeResolver.getMapValueType(this.targetMapClass); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java index b2ae0b2eb7c..0524a8ecc91 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java @@ -257,16 +257,16 @@ public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver); String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames(); - for (int i = 0; i < beanNames.length; i++) { + for (String curName : beanNames) { // Check that we're not parsing our own bean definition, // to avoid failing on unresolvable placeholders in properties file locations. - if (!(beanNames[i].equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) { - BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]); + if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) { + BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName); try { visitor.visitBeanDefinition(bd); } catch (BeanDefinitionStoreException ex) { - throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i], ex.getMessage()); + throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage()); } } } @@ -287,10 +287,10 @@ public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer * @throws BeanDefinitionStoreException if invalid values are encountered * @see #resolvePlaceholder(String, java.util.Properties, int) */ - protected String parseStringValue(String strVal, Properties props, Set visitedPlaceholders) + protected String parseStringValue(String strVal, Properties props, Set visitedPlaceholders) throws BeanDefinitionStoreException { - StringBuffer buf = new StringBuffer(strVal); + StringBuilder buf = new StringBuilder(strVal); int startIndex = strVal.indexOf(this.placeholderPrefix); while (startIndex != -1) { @@ -443,7 +443,7 @@ public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer } public String resolveStringValue(String strVal) throws BeansException { - String value = parseStringValue(strVal, this.props, new HashSet()); + String value = parseStringValue(strVal, this.props, new HashSet()); return (value.equals(nullValue) ? null : value); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java index 2f52f9d5495..ea590097fd3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/config/Scope.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. @@ -118,6 +118,14 @@ public interface Scope { */ void registerDestructionCallback(String name, Runnable callback); + /** + * Resolve the contextual object for the given key, if any. + * E.g. the HttpServletRequest object for key "request". + * @param key the contextual key + * @return the corresponding object, or null if none found + */ + Object resolveContextualObject(String key); + /** * Return the conversation ID for the current underlying scope, if any. *

The exact meaning of the conversation ID depends on the underlying 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 fa643842815..4b62b57fa5d 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 @@ -23,7 +23,6 @@ import java.util.Set; import org.springframework.beans.BeanUtils; import org.springframework.beans.TypeConverter; import org.springframework.core.GenericCollectionTypeResolver; -import org.springframework.core.JdkVersion; /** * Simple factory for shared Set instances. Allows for central setup @@ -83,7 +82,7 @@ public class SetFactoryBean extends AbstractFactoryBean { result = new LinkedHashSet(this.sourceSet.size()); } Class valueType = null; - if (this.targetSetClass != null && JdkVersion.isAtLeastJava15()) { + if (this.targetSetClass != null) { valueType = GenericCollectionTypeResolver.getCollectionType(this.targetSetClass); } if (valueType != null) { diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java index 96a18a97196..7ef3254da7f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/ParseState.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. @@ -95,7 +95,7 @@ public final class ParseState { */ @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int x = 0; x < this.state.size(); x++) { if (x > 0) { sb.append('\n'); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java index 6fc9f2d6641..b895ad23ba0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/parsing/Problem.java @@ -116,7 +116,7 @@ public class Problem { @Override public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("Configuration problem: "); sb.append(getMessage()); sb.append("\nOffending resource: ").append(getResourceDescription()); diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index fae278edc51..b72628fbced 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -35,6 +35,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; @@ -64,7 +65,6 @@ import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.config.TypedStringValue; -import org.springframework.core.CollectionFactory; import org.springframework.core.MethodParameter; import org.springframework.core.PriorityOrdered; import org.springframework.util.ClassUtils; @@ -122,19 +122,21 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac * Dependency types to ignore on dependency check and autowire, as Set of * Class objects: for example, String. Default is none. */ - private final Set ignoredDependencyTypes = new HashSet(); + private final Set ignoredDependencyTypes = new HashSet(); /** * Dependency interfaces to ignore on dependency check and autowire, as Set of * Class objects. By default, only the BeanFactory interface is ignored. */ - private final Set ignoredDependencyInterfaces = new HashSet(); + private final Set ignoredDependencyInterfaces = new HashSet(); /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ - private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanInstanceCache = + new ConcurrentHashMap(); /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ - private final Map filteredPropertyDescriptorsCache = new HashMap(); + private final Map filteredPropertyDescriptorsCache = + new HashMap(); /** @@ -346,8 +348,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac throws BeansException { Object result = existingBean; - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessBeforeInitialization(result, beanName); } return result; @@ -357,8 +358,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac throws BeansException { Object result = existingBean; - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessAfterInitialization(result, beanName); } return result; @@ -379,7 +379,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac throws BeanCreationException { AccessControlContext acc = AccessController.getContext(); - return AccessController.doPrivileged(new PrivilegedAction() { + return AccessController.doPrivileged(new PrivilegedAction() { public Object run() { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); @@ -436,7 +436,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { - instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName); + instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); @@ -491,9 +491,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); - Set actualDependentBeans = new LinkedHashSet(dependentBeans.length); - for (int i = 0; i < dependentBeans.length; i++) { - String dependentBean = dependentBeans[i]; + Set actualDependentBeans = new LinkedHashSet(dependentBeans.length); + for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } @@ -529,8 +528,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { - BeanPostProcessor bp = (BeanPostProcessor) it.next(); + for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Class processedType = ibp.predictBeanType(beanClass, beanName); @@ -584,9 +582,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac // Can't clearly figure out exact method due to type converting / autowiring! int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount(); Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass); - Set returnTypes = new HashSet(1); - for (int i = 0; i < candidates.length; i++) { - Method factoryMethod = candidates[i]; + Set returnTypes = new HashSet(1); + for (Method factoryMethod : candidates) { if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic && factoryMethod.getName().equals(mbd.getFactoryMethodName()) && factoryMethod.getParameterTypes().length >= minNrOfArgs) { @@ -596,7 +593,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac if (returnTypes.size() == 1) { // Clear return type found: all factory methods return same type. - return (Class) returnTypes.iterator().next(); + return returnTypes.iterator().next(); } else { // Ambiguous return types found: return null to indicate "not determinable". @@ -642,8 +639,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { - BeanPostProcessor bp = (BeanPostProcessor) it.next(); + for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); @@ -669,7 +665,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac */ private FactoryBean getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { synchronized (getSingletonMutex()) { - BeanWrapper bw = (BeanWrapper) this.factoryBeanInstanceCache.get(beanName); + BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName); if (bw != null) { return (FactoryBean) bw.getWrappedInstance(); } @@ -742,10 +738,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class beanType, String beanName) throws BeansException { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); - if (beanProcessor instanceof MergedBeanDefinitionPostProcessor) { - MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) beanProcessor; + for (BeanPostProcessor bp : getBeanPostProcessors()) { + if (bp instanceof MergedBeanDefinitionPostProcessor) { + MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); } } @@ -768,7 +763,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } - mbd.beforeInstantiationResolved = Boolean.valueOf(bean != null); + mbd.beforeInstantiationResolved = (bean != null); } return bean; } @@ -788,10 +783,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) throws BeansException { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); - if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) { - InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor; + for (BeanPostProcessor bp : getBeanPostProcessors()) { + if (bp instanceof InstantiationAwareBeanPostProcessor) { + InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); if (result != null) { return result; @@ -856,10 +850,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac throws BeansException { if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); - if (beanProcessor instanceof SmartInstantiationAwareBeanPostProcessor) { - SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) beanProcessor; + for (BeanPostProcessor bp : getBeanPostProcessors()) { + if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { + SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Constructor[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; @@ -956,10 +949,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac boolean continueWithPropertyPopulation = true; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); - if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) { - InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor; + for (BeanPostProcessor bp : getBeanPostProcessors()) { + if (bp instanceof InstantiationAwareBeanPostProcessor) { + InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; @@ -995,10 +987,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw); if (hasInstAwareBpps) { - for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { - BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); - if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) { - InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor; + for (BeanPostProcessor bp : getBeanPostProcessors()) { + if (bp instanceof InstantiationAwareBeanPostProcessor) { + InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; @@ -1027,15 +1018,15 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); - for (int i = 0; i < propertyNames.length; i++) { - String propertyName = propertyNames[i]; + for (String propertyName : propertyNames) { if (containsBean(propertyName)) { Object bean = getBean(propertyName); pvs.addPropertyValue(propertyName, bean); registerDependentBean(propertyName, beanName); if (logger.isDebugEnabled()) { - logger.debug("Added autowiring by name from bean name '" + beanName + - "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); + logger.debug( + "Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + + "' to bean named '" + propertyName + "'"); } } else { @@ -1066,10 +1057,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac converter = bw; } - Set autowiredBeanNames = new LinkedHashSet(4); + Set autowiredBeanNames = new LinkedHashSet(4); String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); - for (int i = 0; i < propertyNames.length; i++) { - String propertyName = propertyNames[i]; + for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); @@ -1081,12 +1071,12 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac if (autowiredArgument != null) { pvs.addPropertyValue(propertyName, autowiredArgument); } - for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) { - String autowiredBeanName = (String) it.next(); + for (String autowiredBeanName : autowiredBeanNames) { registerDependentBean(autowiredBeanName, beanName); if (logger.isDebugEnabled()) { - logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" + - propertyName + "' to bean named '" + autowiredBeanName + "'"); + logger.debug( + "Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + + "' to bean named '" + autowiredBeanName + "'"); } } autowiredBeanNames.clear(); @@ -1108,13 +1098,13 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac * @see org.springframework.beans.BeanUtils#isSimpleProperty */ protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { - Set result = new TreeSet(); + Set result = new TreeSet(); PropertyValues pvs = mbd.getPropertyValues(); PropertyDescriptor[] pds = bw.getPropertyDescriptors(); - for (int i = 0; i < pds.length; i++) { - if (pds[i].getWriteMethod() != null && !isExcludedFromDependencyCheck(pds[i]) && - !pvs.contains(pds[i].getName()) && !BeanUtils.isSimpleProperty(pds[i].getPropertyType())) { - result.add(pds[i].getName()); + for (PropertyDescriptor pd : pds) { + if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) && + !BeanUtils.isSimpleProperty(pd.getPropertyType())) { + result.add(pd.getName()); } } return StringUtils.toStringArray(result); @@ -1130,17 +1120,17 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac */ protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) { synchronized (this.filteredPropertyDescriptorsCache) { - PropertyDescriptor[] filtered = (PropertyDescriptor[]) - this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass()); + PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass()); if (filtered == null) { - List pds = new LinkedList(Arrays.asList(bw.getPropertyDescriptors())); + List pds = + new LinkedList(Arrays.asList(bw.getPropertyDescriptors())); for (Iterator it = pds.iterator(); it.hasNext();) { PropertyDescriptor pd = (PropertyDescriptor) it.next(); if (isExcludedFromDependencyCheck(pd)) { it.remove(); } } - filtered = (PropertyDescriptor[]) pds.toArray(new PropertyDescriptor[pds.size()]); + filtered = pds.toArray(new PropertyDescriptor[pds.size()]); this.filteredPropertyDescriptorsCache.put(bw.getWrappedClass(), filtered); } return filtered; @@ -1178,15 +1168,14 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac throws UnsatisfiedDependencyException { int dependencyCheck = mbd.getDependencyCheck(); - for (int i = 0; i < pds.length; i++) { - if (pds[i].getWriteMethod() != null && !pvs.contains(pds[i].getName())) { - boolean isSimple = BeanUtils.isSimpleProperty(pds[i].getPropertyType()); + for (PropertyDescriptor pd : pds) { + if (pd.getWriteMethod() != null && !pvs.contains(pd.getName())) { + boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType()); boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) || - (isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) || - (!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS); + (isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) || + (!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS); if (unsatisfied) { - throw new UnsatisfiedDependencyException( - mbd.getResourceDescription(), beanName, pds[i].getName(), + throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(), "Set this property value or disable dependency checking for this bean."); } } @@ -1208,7 +1197,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac } MutablePropertyValues mpvs = null; - List original = null; + List original = null; if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; @@ -1236,10 +1225,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); // Create a deep copy, resolving any references for values. - List deepCopy = new ArrayList(original.size()); + List deepCopy = new ArrayList(original.size()); boolean resolveNecessary = false; - for (Iterator it = original.iterator(); it.hasNext();) { - PropertyValue pv = (PropertyValue) it.next(); + for (PropertyValue pv : original) { if (pv.isConverted()) { deepCopy.add(pv); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java index 31d67835ac7..d8a0041186b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java @@ -985,7 +985,7 @@ public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccess @Override public String toString() { - StringBuffer sb = new StringBuffer("class ["); + StringBuilder sb = new StringBuilder("class ["); sb.append(getBeanClassName()).append("]"); sb.append("; scope=").append(this.scope); sb.append("; abstract=").append(this.abstractFlag); 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 a4e366f4313..f8181f6ade9 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 @@ -22,11 +22,11 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; @@ -51,12 +51,13 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.SmartFactoryBean; import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanExpressionContext; +import org.springframework.beans.factory.config.BeanExpressionResolver; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.config.Scope; -import org.springframework.core.CollectionFactory; import org.springframework.core.DecoratingClassLoader; import org.springframework.core.NamedThreadLocal; import org.springframework.util.Assert; @@ -108,17 +109,22 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp /** Whether to cache bean metadata or rather reobtain it for every access */ private boolean cacheBeanMetadata = true; - /** Custom PropertyEditorRegistrars to apply to the beans of this factory */ - private final Set propertyEditorRegistrars = new LinkedHashSet(4); + /** Resolution strategy for expressions in bean definition values */ + private BeanExpressionResolver beanExpressionResolver; - /** Custom PropertyEditors to apply to the beans of this factory */ - private final Map customEditors = new HashMap(4); + /** Custom PropertyEditorRegistrars to apply to the beans of this factory */ + private final Set propertyEditorRegistrars = + new LinkedHashSet(4); /** A custom TypeConverter to use, overriding the default PropertyEditor mechanism */ private TypeConverter typeConverter; + /** Custom PropertyEditors to apply to the beans of this factory */ + private final Map> customEditors = + new HashMap>(4); + /** BeanPostProcessors to apply in createBean */ - private final List beanPostProcessors = new ArrayList(); + private final List beanPostProcessors = new ArrayList(); /** Indicates whether any InstantiationAwareBeanPostProcessors have been registered */ private boolean hasInstantiationAwareBeanPostProcessors; @@ -127,18 +133,18 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp private boolean hasDestructionAwareBeanPostProcessors; /** Map from scope identifier String to corresponding Scope */ - private final Map scopes = new HashMap(); + private final Map scopes = new HashMap(); /** Map from bean name to merged RootBeanDefinition */ - private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map mergedBeanDefinitions = + new ConcurrentHashMap(); /** Names of beans that have already been created at least once */ - private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); /** Names of beans that are currently in creation */ - private final ThreadLocal prototypesCurrentlyInCreation = - new NamedThreadLocal("Prototype beans currently in creation"); - + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("Prototype beans currently in creation"); /** * Create a new AbstractBeanFactory. @@ -164,7 +170,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp return getBean(name, null, null); } - public Object getBean(String name, Class requiredType) throws BeansException { + public T getBean(String name, Class requiredType) throws BeansException { return getBean(name, requiredType, null); } @@ -181,7 +187,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp * @return an instance of the bean * @throws BeansException if the bean could not be created */ - public Object getBean(String name, Class requiredType, Object[] args) throws BeansException { + public T getBean(String name, Class requiredType, Object[] args) throws BeansException { return doGetBean(name, requiredType, args, false); } @@ -196,8 +202,9 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp * @return an instance of the bean * @throws BeansException if the bean could not be created */ - protected Object doGetBean( - final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { + protected T doGetBean( + final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) + throws BeansException { final String beanName = transformedBeanName(name); Object bean = null; @@ -231,7 +238,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp String nameToLookup = originalBeanName(name); if (args != null) { // Delegation to parent with explicit args. - return parentBeanFactory.getBean(nameToLookup, args); + return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // No args -> delegate to standard getBean method. @@ -249,8 +256,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { - for (int i = 0; i < dependsOn.length; i++) { - String dependsOnBean = dependsOn[i]; + for (String dependsOnBean : dependsOn) { getBean(dependsOnBean); registerDependentBean(dependsOnBean, beanName); } @@ -290,7 +296,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp else { String scopeName = mbd.getScope(); - final Scope scope = (Scope) this.scopes.get(scopeName); + final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } @@ -321,7 +327,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } - return bean; + return (T) bean; } public boolean containsBean(String name) { @@ -505,7 +511,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp @Override public String[] getAliases(String name) { String beanName = transformedBeanName(name); - List aliases = new ArrayList(); + List aliases = new ArrayList(); boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX); String fullBeanName = beanName; if (factoryPrefix) { @@ -515,8 +521,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp aliases.add(fullBeanName); } String[] retrievedAliases = super.getAliases(beanName); - for (int i = 0; i < retrievedAliases.length; i++) { - String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAliases[i]; + for (String retrievedAliase : retrievedAliases) { + String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAliase; if (!alias.equals(name)) { aliases.add(alias); } @@ -581,6 +587,14 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp return this.cacheBeanMetadata; } + public void setBeanExpressionResolver(BeanExpressionResolver resolver) { + this.beanExpressionResolver = resolver; + } + + public BeanExpressionResolver getBeanExpressionResolver() { + return this.beanExpressionResolver; + } + public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) { Assert.notNull(registrar, "PropertyEditorRegistrar must not be null"); this.propertyEditorRegistrars.add(registrar); @@ -589,31 +603,24 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp /** * Return the set of PropertyEditorRegistrars. */ - public Set getPropertyEditorRegistrars() { + public Set getPropertyEditorRegistrars() { return this.propertyEditorRegistrars; } - public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { Assert.notNull(requiredType, "Required type must not be null"); Assert.isAssignable(PropertyEditor.class, propertyEditorClass); this.customEditors.put(requiredType, propertyEditorClass); } - public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { - Assert.notNull(requiredType, "Required type must not be null"); - Assert.notNull(propertyEditor, "PropertyEditor must not be null"); - this.customEditors.put(requiredType, propertyEditor); - } - public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) { registerCustomEditors(registry); } /** - * Return the map of custom editors, with Classes as keys - * and PropertyEditor instances or PropertyEditor classes as values. + * Return the map of custom editors, with Classes as keys and PropertyEditor classes as values. */ - public Map getCustomEditors() { + public Map> getCustomEditors() { return this.customEditors; } @@ -661,7 +668,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp * Return the list of BeanPostProcessors that will get applied * to beans created with this factory. */ - public List getBeanPostProcessors() { + public List getBeanPostProcessors() { return this.beanPostProcessors; } @@ -700,13 +707,14 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp public Scope getRegisteredScope(String scopeName) { Assert.notNull(scopeName, "Scope identifier must not be null"); - return (Scope) this.scopes.get(scopeName); + return this.scopes.get(scopeName); } public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { Assert.notNull(otherFactory, "BeanFactory must not be null"); setBeanClassLoader(otherFactory.getBeanClassLoader()); setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); + setBeanExpressionResolver(otherFactory.getBeanExpressionResolver()); if (otherFactory instanceof AbstractBeanFactory) { AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory; this.customEditors.putAll(otherAbstractFactory.customEditors); @@ -718,6 +726,9 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp otherAbstractFactory.hasDestructionAwareBeanPostProcessors; this.scopes.putAll(otherAbstractFactory.scopes); } + else { + setTypeConverter(otherFactory.getTypeConverter()); + } } /** @@ -771,13 +782,13 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp this.prototypesCurrentlyInCreation.set(beanName); } else if (curVal instanceof String) { - Set beanNameSet = new HashSet(2); - beanNameSet.add(curVal); + Set beanNameSet = new HashSet(2); + beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) curVal; beanNameSet.add(beanName); } } @@ -794,7 +805,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp this.prototypesCurrentlyInCreation.set(null); } else if (curVal instanceof Set) { - Set beanNameSet = (Set) curVal; + Set beanNameSet = (Set) curVal; beanNameSet.remove(beanName); if (beanNameSet.isEmpty()) { this.prototypesCurrentlyInCreation.set(null); @@ -839,7 +850,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp "Bean name '" + beanName + "' does not correspond to an object in a Scope"); } String scopeName = mbd.getScope(); - Scope scope = (Scope) this.scopes.get(scopeName); + Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } @@ -904,8 +915,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp registrySupport.useConfigValueEditors(); } if (!this.propertyEditorRegistrars.isEmpty()) { - for (Iterator it = this.propertyEditorRegistrars.iterator(); it.hasNext();) { - PropertyEditorRegistrar registrar = (PropertyEditorRegistrar) it.next(); + for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) { try { registrar.registerCustomEditors(registry); } @@ -916,8 +926,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp if (isCurrentlyInCreation(bce.getBeanName())) { if (logger.isDebugEnabled()) { logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() + - "] failed because it tried to obtain currently created bean '" + ex.getBeanName() + - "': " + ex.getMessage()); + "] failed because it tried to obtain currently created bean '" + + ex.getBeanName() + "': " + ex.getMessage()); } onSuppressedException(ex); continue; @@ -928,28 +938,11 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp } } if (!this.customEditors.isEmpty()) { - for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - Class requiredType = (Class) entry.getKey(); - Object value = entry.getValue(); - if (value instanceof PropertyEditor) { - PropertyEditor editor = (PropertyEditor) value; - // Register the editor as shared instance, if possible, - // to make it clear that it might be used concurrently. - if (registrySupport != null) { - registrySupport.registerSharedEditor(requiredType, editor); - } - else { - registry.registerCustomEditor(requiredType, editor); - } - } - else if (value instanceof Class) { - Class editorClass = (Class) value; - registry.registerCustomEditor(requiredType, (PropertyEditor) BeanUtils.instantiateClass(editorClass)); - } - else { - throw new IllegalStateException("Illegal custom editor value type: " + value.getClass().getName()); - } + for (Map.Entry> entry : this.customEditors.entrySet()) { + Class requiredType = entry.getKey(); + Class editorClass = entry.getValue(); + registry.registerCustomEditor(requiredType, + (PropertyEditor) BeanUtils.instantiateClass(editorClass)); } } } @@ -965,7 +958,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp */ protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. - RootBeanDefinition mbd = (RootBeanDefinition) this.mergedBeanDefinitions.get(beanName); + RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName); if (mbd != null) { return mbd; } @@ -1005,7 +998,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp // Check with full lock now in order to enforce the same merged instance. if (containingBd == null) { - mbd = (RootBeanDefinition) this.mergedBeanDefinitions.get(beanName); + mbd = this.mergedBeanDefinitions.get(beanName); } if (mbd == null) { @@ -1128,8 +1121,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp if (tempClassLoader != null) { if (tempClassLoader instanceof DecoratingClassLoader) { DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; - for (int i = 0; i < typesToMatch.length; i++) { - dcl.excludeClass(typesToMatch[i].getName()); + for (Class typeToMatch : typesToMatch) { + dcl.excludeClass(typeToMatch.getName()); } } String className = mbd.getBeanClassName(); @@ -1146,6 +1139,22 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp } } + /** + * Evaluate the given String as contained in a bean definition, + * potentially resolving it as an expression. + * @param value the value to check + * @param beanDefinition the bean definition that the value comes from + * @return the resolved value + * @see #setBeanExpressionResolver + */ + protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) { + if (this.beanExpressionResolver == null) { + return value; + } + Scope scope = getRegisteredScope(beanDefinition.getScope()); + return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); + } + /** * Predict the eventual bean type (of the processed bean instance) for the @@ -1199,8 +1208,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp return null; } try { - FactoryBean factoryBean = - (FactoryBean) doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); + FactoryBean factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); return getTypeForFactoryBean(factoryBean); } catch (BeanCreationException ex) { @@ -1339,7 +1347,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp } else { // A bean with a custom scope... - Scope scope = (Scope) this.scopes.get(mbd.getScope()); + Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'"); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java index a13f97a53f9..879f52aa3ed 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java @@ -22,10 +22,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Comparator; -import java.util.Iterator; import java.util.Set; -import org.springframework.core.JdkVersion; import org.springframework.util.ClassUtils; /** @@ -39,10 +37,6 @@ import org.springframework.util.ClassUtils; */ abstract class AutowireUtils { - private static final String QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME = - "org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver"; - - /** * Sort the given constructors, preferring public constructors and "greedy" ones * with a maximum of arguments. The result will contain public constructors first, @@ -51,10 +45,8 @@ abstract class AutowireUtils { * @param constructors the constructor array to sort */ public static void sortConstructors(Constructor[] constructors) { - Arrays.sort(constructors, new Comparator() { - public int compare(Object o1, Object o2) { - Constructor c1 = (Constructor) o1; - Constructor c2 = (Constructor) o2; + Arrays.sort(constructors, new Comparator() { + public int compare(Constructor c1, Constructor c2) { boolean p1 = Modifier.isPublic(c1.getModifiers()); boolean p2 = Modifier.isPublic(c2.getModifiers()); if (p1 != p2) { @@ -62,7 +54,7 @@ abstract class AutowireUtils { } int c1pl = c1.getParameterTypes().length; int c2pl = c2.getParameterTypes().length; - return (new Integer(c1pl)).compareTo(new Integer(c2pl)) * -1; + return (new Integer(c1pl)).compareTo(c2pl) * -1; } }); } @@ -78,7 +70,7 @@ abstract class AutowireUtils { if (wm == null) { return false; } - if (wm.getDeclaringClass().getName().indexOf("$$") == -1) { + if (!wm.getDeclaringClass().getName().contains("$$")) { // Not a CGLIB method so it's OK. return false; } @@ -95,12 +87,11 @@ abstract class AutowireUtils { * @param interfaces the Set of interfaces (Class objects) * @return whether the setter method is defined by an interface */ - public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set interfaces) { + public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set interfaces) { Method setter = pd.getWriteMethod(); if (setter != null) { Class targetClass = setter.getDeclaringClass(); - for (Iterator it = interfaces.iterator(); it.hasNext();) { - Class ifc = (Class) it.next(); + for (Class ifc : interfaces) { if (ifc.isAssignableFrom(targetClass) && ClassUtils.hasMethod(ifc, setter.getName(), setter.getParameterTypes())) { return true; @@ -110,25 +101,4 @@ abstract class AutowireUtils { return false; } - /** - * If at least Java 1.5, this will return an annotation-aware resolver. - * Otherwise it returns a resolver that checks the bean definition only. - */ - public static AutowireCandidateResolver createAutowireCandidateResolver() { - if (JdkVersion.isAtLeastJava15()) { - try { - Class resolverClass = ClassUtils.forName( - QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME, AutowireUtils.class.getClassLoader()); - return (AutowireCandidateResolver) resolverClass.newInstance(); - } - catch (Throwable ex) { - throw new IllegalStateException("Unable to load Java 1.5 dependent class [" + - QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME + "]", ex); - } - } - else { - return new SimpleAutowireCandidateResolver(); - } - } - } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java index 7c808122676..2102eaec2a1 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReader.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,15 +38,6 @@ import org.springframework.core.io.ResourceLoader; */ public interface BeanDefinitionReader { -/** - * Return the bean factory to register the bean definitions with. - *

The factory is exposed through the BeanDefinitionRegistry interface, - * encapsulating the methods that are relevant for bean definition handling. - * @deprecated in favor of the uniformly named {@link #getRegistry()} - */ - @Deprecated - BeanDefinitionRegistry getBeanFactory(); - /** * Return the bean factory to register the bean definitions with. *

The factory is exposed through the BeanDefinitionRegistry interface, diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java index 96efab1690b..da266c1526b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.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. @@ -45,31 +45,6 @@ public class BeanDefinitionReaderUtils { public static final String GENERATED_BEAN_NAME_SEPARATOR = BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR; - /** - * Create a new GenericBeanDefinition for the given - * class name, parent, constructor arguments, and property values. - * @param className the name of the bean class, if any - * @param parentName the name of the parent bean, if any - * @param cargs the constructor arguments, if any - * @param pvs the property values, if any - * @param classLoader the ClassLoader to use for loading bean classes - * (can be null to just register bean classes by name) - * @return the bean definition - * @throws ClassNotFoundException if the bean class could not be loaded - * @deprecated in favor of createBeanDefinition(String, String, ClassLoader) - * @see #createBeanDefinition(String, String, ClassLoader) - */ - @Deprecated - public static AbstractBeanDefinition createBeanDefinition( - String className, String parentName, ConstructorArgumentValues cargs, - MutablePropertyValues pvs, ClassLoader classLoader) throws ClassNotFoundException { - - AbstractBeanDefinition bd = createBeanDefinition(parentName, className, classLoader); - bd.setConstructorArgumentValues(cargs); - bd.setPropertyValues(pvs); - return bd; - } - /** * Create a new GenericBeanDefinition for the given parent name and class name, * eagerly loading the bean class if a ClassLoader has been specified. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java index db4ea3ea266..408010e8589 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java @@ -17,7 +17,6 @@ package org.springframework.beans.factory.support; import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -104,12 +103,13 @@ class BeanDefinitionValueResolver { return resolveReference(argName, ref); } else if (value instanceof RuntimeBeanNameReference) { - String ref = ((RuntimeBeanNameReference) value).getBeanName(); - if (!this.beanFactory.containsBean(ref)) { + String refName = ((RuntimeBeanNameReference) value).getBeanName(); + refName = String.valueOf(evaluate(refName)); + if (!this.beanFactory.containsBean(refName)) { throw new BeanDefinitionStoreException( - "Invalid bean name '" + ref + "' in bean reference for " + argName); + "Invalid bean name '" + refName + "' in bean reference for " + argName); } - return ref; + return refName; } else if (value instanceof BeanDefinitionHolder) { // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases. @@ -123,21 +123,20 @@ class BeanDefinitionValueResolver { } else if (value instanceof ManagedList) { // May need to resolve contained runtime references. - return resolveManagedList(argName, (List) value); + return resolveManagedList(argName, (List) value); } else if (value instanceof ManagedSet) { // May need to resolve contained runtime references. - return resolveManagedSet(argName, (Set) value); + return resolveManagedSet(argName, (Set) value); } else if (value instanceof ManagedMap) { // May need to resolve contained runtime references. - return resolveManagedMap(argName, (Map) value); + return resolveManagedMap(argName, (Map) value); } else if (value instanceof ManagedProperties) { Properties original = (Properties) value; Properties copy = new Properties(); - for (Iterator it = original.entrySet().iterator(); it.hasNext();) { - Map.Entry propEntry = (Map.Entry) it.next(); + for (Map.Entry propEntry : original.entrySet()) { Object propKey = propEntry.getKey(); Object propValue = propEntry.getValue(); if (propKey instanceof TypedStringValue) { @@ -153,14 +152,14 @@ class BeanDefinitionValueResolver { else if (value instanceof TypedStringValue) { // Convert value to target type here. TypedStringValue typedStringValue = (TypedStringValue) value; + Object valueObject = evaluate(typedStringValue.getValue()); try { Class resolvedTargetType = resolveTargetType(typedStringValue); if (resolvedTargetType != null) { - return this.typeConverter.convertIfNecessary(typedStringValue.getValue(), resolvedTargetType); + return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType); } else { - // No target type specified - no conversion necessary... - return typedStringValue.getValue(); + return valueObject; } } catch (Throwable ex) { @@ -171,7 +170,20 @@ class BeanDefinitionValueResolver { } } else { - // No need to resolve value... + return evaluate(value); + } + } + + /** + * Evaluate the given value as an expression, if necessary. + * @param value the candidate value (may be an expression) + * @return the resolved value + */ + protected Object evaluate(Object value) { + if (value instanceof String) { + return this.beanFactory.evaluateBeanDefinitionString((String) value, this.beanDefinition); + } + else { return value; } } @@ -210,8 +222,7 @@ class BeanDefinitionValueResolver { // Guarantee initialization of beans that the inner bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { - for (int i = 0; i < dependsOn.length; i++) { - String dependsOnBean = dependsOn[i]; + for (String dependsOnBean : dependsOn) { this.beanFactory.getBean(dependsOnBean); this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName); } @@ -256,18 +267,20 @@ class BeanDefinitionValueResolver { */ private Object resolveReference(Object argName, RuntimeBeanReference ref) { try { + String refName = ref.getBeanName(); + refName = String.valueOf(evaluate(refName)); if (ref.isToParent()) { if (this.beanFactory.getParentBeanFactory() == null) { throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, - "Can't resolve reference to bean '" + ref.getBeanName() + + "Can't resolve reference to bean '" + refName + "' in parent factory: no parent factory available"); } - return this.beanFactory.getParentBeanFactory().getBean(ref.getBeanName()); + return this.beanFactory.getParentBeanFactory().getBean(refName); } else { - Object bean = this.beanFactory.getBean(ref.getBeanName()); - this.beanFactory.registerDependentBean(ref.getBeanName(), this.beanName); + Object bean = this.beanFactory.getBean(refName); + this.beanFactory.registerDependentBean(refName, this.beanName); return bean; } } @@ -281,7 +294,7 @@ class BeanDefinitionValueResolver { /** * For each element in the ManagedList, resolve reference if necessary. */ - private List resolveManagedList(Object argName, List ml) { + private List resolveManagedList(Object argName, List ml) { List resolved = new ArrayList(ml.size()); for (int i = 0; i < ml.size(); i++) { resolved.add( @@ -295,14 +308,12 @@ class BeanDefinitionValueResolver { /** * For each element in the ManagedList, resolve reference if necessary. */ - private Set resolveManagedSet(Object argName, Set ms) { + private Set resolveManagedSet(Object argName, Set ms) { Set resolved = new LinkedHashSet(ms.size()); int i = 0; - for (Iterator it = ms.iterator(); it.hasNext();) { - resolved.add( - resolveValueIfNecessary( - argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX, - it.next())); + for (Object m : ms) { + resolved.add(resolveValueIfNecessary( + argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX, m)); i++; } return resolved; @@ -311,15 +322,13 @@ class BeanDefinitionValueResolver { /** * For each element in the ManagedMap, resolve reference if necessary. */ - private Map resolveManagedMap(Object argName, Map mm) { + private Map resolveManagedMap(Object argName, Map mm) { Map resolved = new LinkedHashMap(mm.size()); - Iterator it = mm.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry entry : mm.entrySet()) { Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey()); Object resolvedValue = resolveValueIfNecessary( - argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + entry.getKey() + BeanWrapper.PROPERTY_KEY_SUFFIX, - entry.getValue()); + argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + entry.getKey() + + BeanWrapper.PROPERTY_KEY_SUFFIX, entry.getValue()); resolved.put(resolvedKey, resolvedValue); } return resolved; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java index 8dd4278295b..6effd4031e0 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java @@ -172,7 +172,7 @@ public class ChildBeanDefinition extends AbstractBeanDefinition { @Override public String toString() { - StringBuffer sb = new StringBuffer("Child bean with parent '"); + StringBuilder sb = new StringBuilder("Child bean with parent '"); sb.append(this.parentName).append("': ").append(super.toString()); return sb.toString(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index be3eac49ed9..87b2a8aa175 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -41,7 +41,6 @@ import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.core.GenericTypeResolver; -import org.springframework.core.JdkVersion; import org.springframework.core.MethodParameter; import org.springframework.util.MethodInvoker; import org.springframework.util.ObjectUtils; @@ -131,9 +130,7 @@ class ConstructorResolver { for (int i = 0; i < argsToResolve.length; i++) { Object argValue = argsToResolve[i]; MethodParameter methodParam = new MethodParameter(constructorToUse, i); - if (JdkVersion.isAtLeastJava15()) { - GenericTypeResolver.resolveParameterType(methodParam, constructorToUse.getDeclaringClass()); - } + GenericTypeResolver.resolveParameterType(methodParam, constructorToUse.getDeclaringClass()); if (argValue instanceof AutowiredArgumentMarker) { argValue = resolveAutowiredArgument(methodParam, beanName, null, converter); } @@ -318,9 +315,7 @@ class ConstructorResolver { for (int i = 0; i < argsToResolve.length; i++) { Object argValue = argsToResolve[i]; MethodParameter methodParam = new MethodParameter(factoryMethodToUse, i); - if (JdkVersion.isAtLeastJava15()) { - GenericTypeResolver.resolveParameterType(methodParam, factoryClass); - } + GenericTypeResolver.resolveParameterType(methodParam, factoryClass); if (argValue instanceof AutowiredArgumentMarker) { argValue = resolveAutowiredArgument(methodParam, beanName, null, converter); } 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 fefb9b1a2f0..2457d1525b1 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 @@ -19,11 +19,11 @@ package org.springframework.beans.factory.support; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; @@ -38,12 +38,12 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.SmartFactoryBean; +import org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver; import org.springframework.beans.factory.config.BeanDefinition; 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.CollectionFactory; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -91,19 +91,19 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto private boolean configurationFrozen = false; /** Map of bean definition objects, keyed by bean name */ - private final Map beanDefinitionMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map beanDefinitionMap = new ConcurrentHashMap(); /** List of bean definition names, in registration order */ - private final List beanDefinitionNames = new ArrayList(); + private final List beanDefinitionNames = new ArrayList(); /** Cached array of bean definition names in case of frozen configuration */ private String[] frozenBeanDefinitionNames; /** Resolver to use for checking if a bean definition is an autowire candidate */ - private AutowireCandidateResolver autowireCandidateResolver = AutowireUtils.createAutowireCandidateResolver(); + private AutowireCandidateResolver autowireCandidateResolver = new QualifierAnnotationAutowireCandidateResolver(); /** Map from dependency type to corresponding autowired value */ - private final Map resolvableDependencies = new HashMap(); + private final Map resolvableDependencies = new HashMap(); /** @@ -205,25 +205,23 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { - List result = new ArrayList(); + List result = new ArrayList(); // Check all bean definitions. String[] beanDefinitionNames = getBeanDefinitionNames(); - for (int i = 0; i < beanDefinitionNames.length; i++) { - String beanName = beanDefinitionNames[i]; + for (String beanName : beanDefinitionNames) { // Only consider bean as eligible if the bean name // is not defined as alias for some other bean. if (!isAlias(beanName)) { try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. - if (!mbd.isAbstract() && - (allowEagerInit || ((mbd.hasBeanClass() || !mbd.isLazyInit() || this.allowEagerClassLoading)) && + if (!mbd.isAbstract() && (allowEagerInit || + ((mbd.hasBeanClass() || !mbd.isLazyInit() || this.allowEagerClassLoading)) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { // In case of FactoryBean, match object created by FactoryBean. boolean isFactoryBean = isFactoryBean(beanName, mbd); - boolean matchFound = - (allowEagerInit || !isFactoryBean || containsSingleton(beanName)) && + boolean matchFound = (allowEagerInit || !isFactoryBean || containsSingleton(beanName)) && (includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type); if (!matchFound && isFactoryBean) { // In case of FactoryBean, try to match FactoryBean instance itself next. @@ -260,8 +258,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto // Check singletons too, to catch manually registered singletons. String[] singletonNames = getSingletonNames(); - for (int i = 0; i < singletonNames.length; i++) { - String beanName = singletonNames[i]; + for (String beanName : singletonNames) { // Only check if manually registered. if (!containsBeanDefinition(beanName)) { // In case of FactoryBean, match object created by FactoryBean. @@ -295,19 +292,18 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName)); } - public Map getBeansOfType(Class type) throws BeansException { + public Map getBeansOfType(Class type) throws BeansException { return getBeansOfType(type, true, true); } - public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); - Map result = new LinkedHashMap(beanNames.length); - for (int i = 0; i < beanNames.length; i++) { - String beanName = beanNames[i]; + Map result = new LinkedHashMap(beanNames.length); + for (String beanName : beanNames) { try { - result.put(beanName, getBean(beanName)); + result.put(beanName, getBean(beanName, type)); } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); @@ -315,7 +311,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto BeanCreationException bce = (BeanCreationException) rootCause; if (isCurrentlyInCreation(bce.getBeanName())) { if (this.logger.isDebugEnabled()) { - this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " + ex.getMessage()); + this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " + + ex.getMessage()); } onSuppressedException(ex); // Ignore: indicates a circular reference when autowiring constructors. @@ -382,7 +379,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto @Override public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { - BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(beanName); + BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("No bean named '" + beanName + "' found in " + this); @@ -419,8 +416,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } synchronized (this.beanDefinitionMap) { - for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) { - String beanName = (String) it.next(); + for (String beanName : this.beanDefinitionNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { @@ -487,7 +483,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto Assert.hasText(beanName, "'beanName' must not be empty"); synchronized (this.beanDefinitionMap) { - BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.remove(beanName); + BeanDefinition bd = this.beanDefinitionMap.remove(beanName); if (bd == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("No bean named '" + beanName + "' found in " + this); @@ -519,10 +515,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto // Reset all bean definitions that have the given bean as parent // (recursively). - for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) { - String bdName = (String) it.next(); + for (String bdName : this.beanDefinitionNames) { if (!beanName.equals(bdName)) { - BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(bdName); + BeanDefinition bd = this.beanDefinitionMap.get(bdName); if (beanName.equals(bd.getParentName())) { resetBeanDefinition(bdName); } @@ -544,12 +539,12 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto //--------------------------------------------------------------------- public Object resolveDependency(DependencyDescriptor descriptor, String beanName, - Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { + Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Class type = descriptor.getDependencyType(); if (type.isArray()) { Class componentType = type.getComponentType(); - Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor); @@ -570,7 +565,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } return null; } - Map matchingBeans = findAutowireCandidates(beanName, elementType, descriptor); + Map matchingBeans = findAutowireCandidates(beanName, elementType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor); @@ -599,7 +594,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } return null; } - Map matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); + Map matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); @@ -612,7 +607,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto return matchingBeans; } else { - Map matchingBeans = findAutowireCandidates(beanName, type, descriptor); + Map matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { throw new NoSuchBeanDefinitionException(type, @@ -632,7 +627,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto return matchingBeans.get(primaryBeanName); } // We have exactly one match. - Map.Entry entry = (Map.Entry) matchingBeans.entrySet().iterator().next(); + Map.Entry entry = matchingBeans.entrySet().iterator().next(); if (autowiredBeanNames != null) { autowiredBeanNames.add(entry.getKey()); } @@ -653,12 +648,13 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto * @see #autowireByType * @see #autowireConstructor */ - protected Map findAutowireCandidates(String beanName, Class requiredType, DependencyDescriptor descriptor) { + protected Map findAutowireCandidates( + String beanName, Class requiredType, DependencyDescriptor descriptor) { + String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); - Map result = new LinkedHashMap(candidateNames.length); - for (Iterator it = this.resolvableDependencies.keySet().iterator(); it.hasNext();) { - Class autowiringType = (Class) it.next(); + Map result = new LinkedHashMap(candidateNames.length); + for (Class autowiringType : this.resolvableDependencies.keySet()) { if (autowiringType.isAssignableFrom(requiredType)) { Object autowiringValue = this.resolvableDependencies.get(autowiringType); if (autowiringValue instanceof ObjectFactory && !requiredType.isInstance(autowiringValue)) { @@ -670,8 +666,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } } } - for (int i = 0; i < candidateNames.length; i++) { - String candidateName = candidateNames[i]; + for (String candidateName : candidateNames) { if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) { result.put(candidateName, getBean(candidateName)); } @@ -686,11 +681,10 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto * @param type the required type * @return the name of the primary candidate, or null if none found */ - protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + protected String determinePrimaryCandidate(Map candidateBeans, Class type) { String primaryBeanName = null; - for (Iterator it = candidateBeans.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String candidateBeanName = (String) entry.getKey(); + for (Map.Entry entry : candidateBeans.entrySet()) { + String candidateBeanName = entry.getKey(); if (isPrimary(candidateBeanName, entry.getValue())) { if (primaryBeanName != null) { throw new NoSuchBeanDefinitionException(type, @@ -736,7 +730,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto @Override public String toString() { - StringBuffer sb = new StringBuffer(ObjectUtils.identityToString(this)); + StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this)); sb.append(": defining beans ["); sb.append(StringUtils.arrayToCommaDelimitedString(getBeanDefinitionNames())); sb.append("]; "); @@ -745,7 +739,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto sb.append("root of factory hierarchy"); } else { - sb.append("parent: " + ObjectUtils.identityToString(parent)); + sb.append("parent: ").append(ObjectUtils.identityToString(parent)); } return sb.toString(); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java index aa8c77bad1e..52094305701 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java @@ -24,6 +24,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -34,7 +35,6 @@ import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.SingletonBeanRegistry; -import org.springframework.core.CollectionFactory; import org.springframework.core.SimpleAliasRegistry; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -83,37 +83,37 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements protected final Log logger = LogFactory.getLog(getClass()); /** Cache of singleton objects: bean name --> bean instance */ - private final Map singletonObjects = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map singletonObjects = new ConcurrentHashMap(); /** Cache of singleton factories: bean name --> ObjectFactory */ - private final Map singletonFactories = new HashMap(); + private final Map singletonFactories = new HashMap(); /** Cache of early singleton objects: bean name --> bean instance */ - private final Map earlySingletonObjects = new HashMap(); + private final Map earlySingletonObjects = new HashMap(); /** Set of registered singletons, containing the bean names in registration order */ - private final Set registeredSingletons = new LinkedHashSet(16); + private final Set registeredSingletons = new LinkedHashSet(16); /** Names of beans that are currently in creation */ - private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); /** List of suppressed Exceptions, available for associating related causes */ - private Set suppressedExceptions; + private Set suppressedExceptions; /** Flag that indicates whether we're currently within destroySingletons */ private boolean singletonsCurrentlyInDestruction = false; /** Disposable bean instances: bean name --> disposable instance */ - private final Map disposableBeans = new LinkedHashMap(16); + private final Map disposableBeans = new LinkedHashMap(); /** Map between containing bean names: bean name --> Set of bean names that the bean contains */ - private final Map containedBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> containedBeanMap = new ConcurrentHashMap>(); /** Map between dependent bean names: bean name --> Set of dependent bean names */ - private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependentBeanMap = new ConcurrentHashMap>(); /** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */ - private final Map dependenciesForBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map> dependenciesForBeanMap = new ConcurrentHashMap>(); public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { @@ -180,7 +180,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements synchronized (this.singletonObjects) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { - ObjectFactory singletonFactory = (ObjectFactory) this.singletonFactories.get(beanName); + ObjectFactory singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); @@ -216,15 +216,15 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements beforeSingletonCreation(beanName); boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { - this.suppressedExceptions = new LinkedHashSet(); + this.suppressedExceptions = new LinkedHashSet(); } try { singletonObject = singletonFactory.getObject(); } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { - for (Iterator it = this.suppressedExceptions.iterator(); it.hasNext();) { - ex.addRelatedCause((Exception) it.next()); + for (Exception suppressedException : this.suppressedExceptions) { + ex.addRelatedCause(suppressedException); } } throw ex; @@ -346,9 +346,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements */ public void registerContainedBean(String containedBeanName, String containingBeanName) { synchronized (this.containedBeanMap) { - Set containedBeans = (Set) this.containedBeanMap.get(containingBeanName); + Set containedBeans = this.containedBeanMap.get(containingBeanName); if (containedBeans == null) { - containedBeans = new LinkedHashSet(8); + containedBeans = new LinkedHashSet(8); this.containedBeanMap.put(containingBeanName, containedBeans); } containedBeans.add(containedBeanName); @@ -364,17 +364,17 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements */ public void registerDependentBean(String beanName, String dependentBeanName) { synchronized (this.dependentBeanMap) { - Set dependentBeans = (Set) this.dependentBeanMap.get(beanName); + Set dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { - dependentBeans = new LinkedHashSet(8); + dependentBeans = new LinkedHashSet(8); this.dependentBeanMap.put(beanName, dependentBeans); } dependentBeans.add(dependentBeanName); } synchronized (this.dependenciesForBeanMap) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName); if (dependenciesForBean == null) { - dependenciesForBean = new LinkedHashSet(8); + dependenciesForBean = new LinkedHashSet(8); this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean); } dependenciesForBean.add(beanName); @@ -395,11 +395,11 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements * @return the array of dependent bean names, or an empty array if none */ public String[] getDependentBeans(String beanName) { - Set dependentBeans = (Set) this.dependentBeanMap.get(beanName); + Set dependentBeans = this.dependentBeanMap.get(beanName); if (dependentBeans == null) { return new String[0]; } - return (String[]) dependentBeans.toArray(new String[dependentBeans.size()]); + return StringUtils.toStringArray(dependentBeans); } /** @@ -409,11 +409,11 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements * or an empty array if none */ public String[] getDependenciesForBean(String beanName) { - Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(beanName); + Set dependenciesForBean = this.dependenciesForBeanMap.get(beanName); if (dependenciesForBean == null) { return new String[0]; } - return (String[]) dependenciesForBean.toArray(new String[dependenciesForBean.size()]); + return dependenciesForBean.toArray(new String[dependenciesForBean.size()]); } public void destroySingletons() { @@ -470,13 +470,12 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements */ protected void destroyBean(String beanName, DisposableBean bean) { // Trigger destruction of dependent beans first... - Set dependencies = (Set) this.dependentBeanMap.remove(beanName); + Set dependencies = this.dependentBeanMap.remove(beanName); if (dependencies != null) { if (logger.isDebugEnabled()) { logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies); } - for (Iterator it = dependencies.iterator(); it.hasNext();) { - String dependentBeanName = (String) it.next(); + for (String dependentBeanName : dependencies) { destroySingleton(dependentBeanName); } } @@ -492,10 +491,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements } // Trigger destruction of contained beans... - Set containedBeans = (Set) this.containedBeanMap.remove(beanName); + Set containedBeans = this.containedBeanMap.remove(beanName); if (containedBeans != null) { - for (Iterator it = containedBeans.iterator(); it.hasNext();) { - String containedBeanName = (String) it.next(); + for (String containedBeanName : containedBeans) { destroySingleton(containedBeanName); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java index 02d015ecec1..8b600e9b6e3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java @@ -20,13 +20,13 @@ import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBeanNotInitializedException; -import org.springframework.core.CollectionFactory; /** * Support base class for singleton registries which need to handle @@ -41,7 +41,7 @@ import org.springframework.core.CollectionFactory; public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { /** Cache of singleton objects created by FactoryBeans: FactoryBean name --> object */ - private final Map factoryBeanObjectCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map factoryBeanObjectCache = new ConcurrentHashMap(); /** @@ -113,7 +113,7 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg throws BeanCreationException { AccessControlContext acc = AccessController.getContext(); - return AccessController.doPrivileged(new PrivilegedAction() { + return AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Object object; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java index b6d5c71172f..c95430fd63f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedList.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. @@ -31,7 +31,7 @@ import org.springframework.beans.Mergeable; * @author Juergen Hoeller * @since 27.05.2003 */ -public class ManagedList extends ArrayList implements Mergeable, BeanMetadataElement { +public class ManagedList extends ArrayList implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java index c6d379d96c4..5e9fd4571c4 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.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. @@ -30,7 +30,7 @@ import org.springframework.beans.Mergeable; * @author Rob Harrop * @since 27.05.2003 */ -public class ManagedMap extends LinkedHashMap implements Mergeable, BeanMetadataElement { +public class ManagedMap extends LinkedHashMap implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java index 866fee07576..e5ec0e0afb3 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/ManagedSet.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,8 +16,6 @@ package org.springframework.beans.factory.support; -import java.util.Collection; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; @@ -32,7 +30,7 @@ import org.springframework.beans.Mergeable; * @author Rob Harrop * @since 21.01.2004 */ -public class ManagedSet extends LinkedHashSet implements Mergeable, BeanMetadataElement { +public class ManagedSet extends LinkedHashSet implements Mergeable, BeanMetadataElement { private Object source; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 8c3fd4a779a..21316df7e3b 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -21,7 +21,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.Enumeration; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; @@ -93,12 +92,6 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader */ public static final String CLASS_KEY = "(class)"; - /** - * Special key to distinguish owner.class=com.myapp.MyClass. - * Deprecated in favor of .(class)= - */ - private static final String DEPRECATED_CLASS_KEY = "class"; - /** * Special key to distinguish owner.(parent)=parentBeanName. */ @@ -295,7 +288,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader */ public int registerBeanDefinitions(ResourceBundle rb, String prefix) throws BeanDefinitionStoreException { // Simply create a map and call overloaded method. - Map map = new HashMap(); + Map map = new HashMap(); Enumeration keys = rb.getKeys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); @@ -356,8 +349,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader } int beanCount = 0; - for (Iterator it = map.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + for (Object key : map.keySet()) { if (!(key instanceof String)) { throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed"); } @@ -408,7 +400,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader * Map came from (for logging purposes) * @throws BeansException if the bean definition could not be parsed or registered */ - protected void registerBeanDefinition(String beanName, Map map, String prefix, String resourceDescription) + protected void registerBeanDefinition(String beanName, Map map, String prefix, String resourceDescription) throws BeansException { String className = null; @@ -420,12 +412,11 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader ConstructorArgumentValues cas = new ConstructorArgumentValues(); MutablePropertyValues pvs = new MutablePropertyValues(); - for (Iterator it = map.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry entry : map.entrySet()) { String key = StringUtils.trimWhitespace((String) entry.getKey()); if (key.startsWith(prefix + SEPARATOR)) { String property = key.substring(prefix.length() + SEPARATOR.length()); - if (isClassKey(property)) { + if (CLASS_KEY.equals(property)) { className = StringUtils.trimWhitespace((String) entry.getValue()); } else if (PARENT_KEY.equals(property)) { @@ -442,8 +433,8 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader else if (SINGLETON_KEY.equals(property)) { // Spring 1.2 style String val = StringUtils.trimWhitespace((String) entry.getValue()); - scope = ((val == null || TRUE_VALUE.equals(val) ? - GenericBeanDefinition.SCOPE_SINGLETON : GenericBeanDefinition.SCOPE_PROTOTYPE)); + scope = ((val == null || TRUE_VALUE.equals(val) ? GenericBeanDefinition.SCOPE_SINGLETON : + GenericBeanDefinition.SCOPE_PROTOTYPE)); } else if (LAZY_INIT_KEY.equals(property)) { String val = StringUtils.trimWhitespace((String) entry.getValue()); @@ -470,7 +461,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader Object val = new RuntimeBeanReference(ref); pvs.addPropertyValue(property, val); } - else{ + else { // It's a normal bean property. pvs.addPropertyValue(property, readValue(entry)); } @@ -506,23 +497,6 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader } } - /** - * Indicates whether the supplied property matches the class property of - * the bean definition. - */ - private boolean isClassKey(String property) { - if (CLASS_KEY.equals(property)) { - return true; - } - else if (DEPRECATED_CLASS_KEY.equals(property)) { - if (logger.isWarnEnabled()) { - logger.warn("Use of 'class' property in [" + getClass().getName() + "] is deprecated in favor of '(class)'"); - } - return true; - } - return false; - } - /** * Reads the value of the entry. Correctly interprets bean references for * values that are prefixed with an asterisk. diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java index 2dd36a8a676..4b9c0aecd29 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java @@ -17,11 +17,11 @@ package org.springframework.beans.factory.support; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.core.CollectionFactory; import org.springframework.core.SimpleAliasRegistry; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -37,7 +37,7 @@ import org.springframework.util.StringUtils; public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements BeanDefinitionRegistry { /** Map of bean definition objects, keyed by bean name */ - private final Map beanDefinitionMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map beanDefinitionMap = new ConcurrentHashMap(); public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) @@ -55,7 +55,7 @@ public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements } public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { - BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(beanName); + BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd == null) { throw new NoSuchBeanDefinitionException(beanName); } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java index 367eea0dc87..1f72ce98f58 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java @@ -66,11 +66,11 @@ import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; /** - * Stateful delegate class used to parse XML bean definitions. Intended for use - * by both the main parser and any extension + * Stateful delegate class used to parse XML bean definitions. + * Intended for use by both the main parser and any extension * {@link BeanDefinitionParser BeanDefinitionParsers} or * {@link BeanDefinitionDecorator BeanDefinitionDecorators}. - * + * * @author Rob Harrop * @author Juergen Hoeller * @author Rod Johnson @@ -86,8 +86,8 @@ public class BeanDefinitionParserDelegate { public static final String BEAN_NAME_DELIMITERS = ",; "; /** - * Value of a T/F attribute that represents true. Anything else represents - * false. Case seNsItive. + * Value of a T/F attribute that represents true. + * Anything else represents false. Case seNsItive. */ public static final String TRUE_VALUE = "true"; @@ -227,6 +227,7 @@ public class BeanDefinitionParserDelegate { public static final String DEFAULT_DESTROY_METHOD_ATTRIBUTE = "default-destroy-method"; + protected final Log logger = LogFactory.getLog(getClass()); private final XmlReaderContext readerContext; @@ -236,15 +237,14 @@ public class BeanDefinitionParserDelegate { private ParseState parseState = new ParseState(); /** - * Stores all used bean names so we can enforce uniqueness on a per file - * basis. + * Stores all used bean names so we can enforce uniqueness on a per file basis. */ private final Set usedNames = new HashSet(); /** - * Create a new BeanDefinitionParserDelegate associated with the supplied - * {@link XmlReaderContext}. + * Create a new BeanDefinitionParserDelegate associated with the + * supplied {@link XmlReaderContext}. */ public BeanDefinitionParserDelegate(XmlReaderContext readerContext) { Assert.notNull(readerContext, "XmlReaderContext must not be null"); @@ -258,10 +258,10 @@ public class BeanDefinitionParserDelegate { return this.readerContext; } + /** - * Invoke the - * {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull - * the source metadata from the supplied {@link Element}. + * Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull the + * source metadata from the supplied {@link Element}. */ protected Object extractSource(Element ele) { return this.readerContext.extractSource(ele); @@ -288,10 +288,10 @@ public class BeanDefinitionParserDelegate { this.readerContext.error(message, source, this.parseState.snapshot(), cause); } + /** * Initialize the default lazy-init, autowire, dependency check settings, * init-method, destroy-method and merge settings. - * * @see #getDefaults() */ public void initDefaults(Element root) { @@ -324,8 +324,8 @@ public class BeanDefinitionParserDelegate { } /** - * Return the default settings for bean definitions as indicated within the - * attributes of the top-level <beans/> element. + * Return the default settings for bean definitions as indicated within + * the attributes of the top-level <beans/> element. */ public BeanDefinitionDefaults getBeanDefinitionDefaults() { BeanDefinitionDefaults bdd = new BeanDefinitionDefaults(); @@ -348,10 +348,10 @@ public class BeanDefinitionParserDelegate { return candidatePattern == null ? null : StringUtils.commaDelimitedListToStringArray(candidatePattern); } + /** - * Parses the supplied <bean> element. May return - * null if there were errors during parse. Errors are - * reported to the + * Parses the supplied <bean> element. May return null + * if there were errors during parse. Errors are reported to the * {@link org.springframework.beans.factory.parsing.ProblemReporter}. */ public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) { @@ -359,9 +359,8 @@ public class BeanDefinitionParserDelegate { } /** - * Parses the supplied <bean> element. May return - * null if there were errors during parse. Errors are - * reported to the + * Parses the supplied <bean> element. May return null + * if there were errors during parse. Errors are reported to the * {@link org.springframework.beans.factory.parsing.ProblemReporter}. */ public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) { @@ -378,8 +377,8 @@ public class BeanDefinitionParserDelegate { if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = (String) aliases.remove(0); if (logger.isDebugEnabled()) { - logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases - + " as aliases"); + logger.debug("No XML 'id' specified - using '" + beanName + + "' as bean name and " + aliases + " as aliases"); } } @@ -392,8 +391,8 @@ public class BeanDefinitionParserDelegate { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { - beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, - this.readerContext.getRegistry(), true); + beanName = BeanDefinitionReaderUtils.generateBeanName( + beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); @@ -401,15 +400,15 @@ public class BeanDefinitionParserDelegate { // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); - if (beanClassName != null && beanName.startsWith(beanClassName) - && beanName.length() > beanClassName.length() - && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { + if (beanClassName != null && + beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && + !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isDebugEnabled()) { - logger.debug("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" - + beanName + "]"); + logger.debug("Neither XML 'id' nor 'name' specified - " + + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { @@ -425,8 +424,7 @@ public class BeanDefinitionParserDelegate { } /** - * Validate that the specified bean name and aliases have not been used - * already. + * Validate that the specified bean name and aliases have not been used already. */ protected void checkNameUniqueness(String beanName, List aliases, Element beanElement) { String foundName = null; @@ -446,11 +444,11 @@ public class BeanDefinitionParserDelegate { } /** - * Parse the bean definition itself, without regard to name or aliases. May - * return null if problems occured during the parse of the - * bean definition. + * Parse the bean definition itself, without regard to name or aliases. May return + * null if problems occured during the parse of the bean definition. */ - public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) { + public AbstractBeanDefinition parseBeanDefinitionElement( + Element ele, String beanName, BeanDefinition containingBean) { this.parseState.push(new BeanEntry(beanName)); @@ -467,7 +465,6 @@ public class BeanDefinitionParserDelegate { AbstractBeanDefinition bd = createBeanDefinition(className, parent); parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); - bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); parseMetaElements(ele, bd); @@ -500,14 +497,11 @@ public class BeanDefinitionParserDelegate { } /** - * Apply the attributes of the given bean element to the given bean - * definition. - * + * Apply the attributes of the given bean element to the given bean * definition. * @param ele bean declaration element * @param beanName bean name * @param containingBean containing bean definition - * @return a bean definition initialized according to the bean element - * attributes + * @return a bean definition initialized according to the bean element attributes */ public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName, BeanDefinition containingBean, AbstractBeanDefinition bd) { @@ -605,18 +599,16 @@ public class BeanDefinitionParserDelegate { /** * Create a bean definition for the given class name and parent name. - * * @param className the name of the bean class * @param parentName the name of the bean's parent bean * @return the newly created bean definition - * @throws ClassNotFoundException if bean class resolution was attempted but - * failed + * @throws ClassNotFoundException if bean class resolution was attempted but failed */ protected AbstractBeanDefinition createBeanDefinition(String className, String parentName) throws ClassNotFoundException { - return BeanDefinitionReaderUtils.createBeanDefinition(parentName, className, - this.readerContext.getBeanClassLoader()); + return BeanDefinitionReaderUtils.createBeanDefinition( + parentName, className, this.readerContext.getBeanClassLoader()); } public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) { @@ -772,8 +764,7 @@ public class BeanDefinitionParserDelegate { try { this.parseState.push(new ConstructorArgumentEntry(index)); Object value = parsePropertyValue(ele, bd, null); - ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder( - value); + ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value); if (StringUtils.hasLength(typeAttr)) { valueHolder.setType(typeAttr); } @@ -875,20 +866,21 @@ public class BeanDefinitionParserDelegate { } /** - * Get the value of a property element. May be a list etc. Also used for - * constructor arguments, "propertyName" being null in this case. + * Get the value of a property element. May be a list etc. + * Also used for constructor arguments, "propertyName" being null in this case. */ public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) { - String elementName = (propertyName != null) ? " element for property '" + propertyName + "'" - : " element"; + String elementName = (propertyName != null) ? + " element for property '" + propertyName + "'" : + " element"; // Should only have one child element: ref, value, list, etc. NodeList nl = ele.getChildNodes(); Element subElement = null; for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); - if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT) - && !DomUtils.nodeNameEquals(node, META_ELEMENT)) { + if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT) && + !DomUtils.nodeNameEquals(node, META_ELEMENT)) { // Child element is what we're looking for. if (subElement != null) { error(elementName + " must not contain more than one sub-element", ele); @@ -901,9 +893,10 @@ public class BeanDefinitionParserDelegate { boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE); boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE); - if ((hasRefAttribute && hasValueAttribute) || ((hasRefAttribute || hasValueAttribute) && subElement != null)) { - error(elementName - + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele); + if ((hasRefAttribute && hasValueAttribute) || + ((hasRefAttribute || hasValueAttribute) && subElement != null)) { + error(elementName + + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele); } if (hasRefAttribute) { @@ -937,7 +930,6 @@ public class BeanDefinitionParserDelegate { /** * Parse a value, ref or collection sub-element of a property or * constructor-arg element. - * * @param ele subelement of property element; we don't know which yet * @param defaultTypeClassName the default type (class name) for any * <value> tag that might be created @@ -1011,10 +1003,6 @@ public class BeanDefinitionParserDelegate { /** * Return a typed String value Object for the given 'idref' element. - * - * @param ele - * @param bd - * @return */ public Object parseIdRefElement(Element ele) { // A generic reference to any name of any bean. @@ -1038,10 +1026,6 @@ public class BeanDefinitionParserDelegate { /** * Return a typed String value Object for the given value element. - * - * @param ele element - * @param defaultTypeClassName type class name - * @return typed String value Object */ public Object parseValueElement(Element ele, String defaultTypeClassName) { // It's a literal value. @@ -1061,7 +1045,6 @@ public class BeanDefinitionParserDelegate { /** * Build a typed String value Object for the given raw value. - * * @see org.springframework.beans.factory.config.TypedStringValue */ protected Object buildTypedStringValue(String value, String targetTypeName, Element ele) @@ -1167,13 +1150,14 @@ public class BeanDefinitionParserDelegate { Object key = null; boolean hasKeyAttribute = entryEle.hasAttribute(KEY_ATTRIBUTE); boolean hasKeyRefAttribute = entryEle.hasAttribute(KEY_REF_ATTRIBUTE); - if ((hasKeyAttribute && hasKeyRefAttribute) || ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) { - error(" element is only allowed to contain either " - + "a 'key' attribute OR a 'key-ref' attribute OR a sub-element", entryEle); + if ((hasKeyAttribute && hasKeyRefAttribute) || + ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) { + error(" element is only allowed to contain either " + + "a 'key' attribute OR a 'key-ref' attribute OR a sub-element", entryEle); } if (hasKeyAttribute) { - key = buildTypedStringValueForMap(entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyTypeClassName, - entryEle); + key = buildTypedStringValueForMap( + entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyTypeClassName, entryEle); } else if (hasKeyRefAttribute) { String refName = entryEle.getAttribute(KEY_REF_ATTRIBUTE); @@ -1195,14 +1179,14 @@ public class BeanDefinitionParserDelegate { Object value = null; boolean hasValueAttribute = entryEle.hasAttribute(VALUE_ATTRIBUTE); boolean hasValueRefAttribute = entryEle.hasAttribute(VALUE_REF_ATTRIBUTE); - if ((hasValueAttribute && hasValueRefAttribute) || ((hasValueAttribute || hasValueRefAttribute)) - && valueEle != null) { - error(" element is only allowed to contain either " - + "'value' attribute OR 'value-ref' attribute OR sub-element", entryEle); + if ((hasValueAttribute && hasValueRefAttribute) || + ((hasValueAttribute || hasValueRefAttribute)) && valueEle != null) { + error(" element is only allowed to contain either " + + "'value' attribute OR 'value-ref' attribute OR sub-element", entryEle); } if (hasValueAttribute) { - value = buildTypedStringValueForMap(entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueTypeClassName, - entryEle); + value = buildTypedStringValueForMap( + entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueTypeClassName, entryEle); } else if (hasValueRefAttribute) { String refName = entryEle.getAttribute(VALUE_REF_ATTRIBUTE); @@ -1229,7 +1213,6 @@ public class BeanDefinitionParserDelegate { /** * Build a typed String value Object for the given raw value. - * * @see org.springframework.beans.factory.config.TypedStringValue */ protected final Object buildTypedStringValueForMap(String value, String defaultTypeClassName, Element entryEle) { @@ -1318,8 +1301,8 @@ public class BeanDefinitionParserDelegate { return decorateBeanDefinitionIfRequired(ele, definitionHolder, null); } - public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder, - BeanDefinition containingBd) { + public BeanDefinitionHolder decorateBeanDefinitionIfRequired( + Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) { BeanDefinitionHolder finalDefinition = definitionHolder; @@ -1341,8 +1324,8 @@ public class BeanDefinitionParserDelegate { return finalDefinition; } - private BeanDefinitionHolder decorateIfRequired(Node node, BeanDefinitionHolder originalDef, - BeanDefinition containingBd) { + private BeanDefinitionHolder decorateIfRequired( + Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) { String namespaceUri = node.getNamespaceURI(); if (!isDefaultNamespace(namespaceUri)) { @@ -1370,15 +1353,17 @@ public class BeanDefinitionParserDelegate { private BeanDefinitionHolder parseNestedCustomElement(Element ele, BeanDefinition containingBd) { BeanDefinition innerDefinition = parseCustomElement(ele, containingBd); if (innerDefinition == null) { - error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " - + "This tag cannot be used nested inside .", ele); + error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " + + "This tag cannot be used nested inside .", ele); return null; } - String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR - + ObjectUtils.getIdentityHexString(innerDefinition); + String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + + ObjectUtils.getIdentityHexString(innerDefinition); if (logger.isDebugEnabled()) { - logger.debug("Using generated bean name [" + id + "] for nested custom element '" + ele.getNodeName() + "'"); + logger.debug("Using generated bean name [" + id + + "] for nested custom element '" + ele.getNodeName() + "'"); } return new BeanDefinitionHolder(innerDefinition, id); } + } 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 e6653a66c97..bd3173760cc 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 @@ -155,10 +155,8 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver this.handlerMappings = new HashMap(mappings); } catch (IOException ex) { - IllegalStateException ise = new IllegalStateException( - "Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]"); - ise.initCause(ex); - throw ise; + throw new IllegalStateException( + "Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex); } } return this.handlerMappings; diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionParser.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionParser.java deleted file mode 100644 index b4dbe0a2901..00000000000 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionParser.java +++ /dev/null @@ -1,58 +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.xml; - -import org.w3c.dom.Document; - -import org.springframework.beans.factory.BeanDefinitionStoreException; -import org.springframework.beans.factory.support.BeanDefinitionReader; -import org.springframework.core.io.Resource; - -/** - * Strategy interface for parsing XML bean definitions. - * Used by XmlBeanDefinitionReader for actually parsing a DOM document. - * - *

Instantiated per document to parse: Implementations can hold - * state in instance variables during the execution of the - * registerBeanDefinitions method, for example global - * settings that are defined for all bean definitions in the document. - * - * @author Juergen Hoeller - * @since 18.12.2003 - * @deprecated as of Spring 2.0: superseded by BeanDefinitionDocumentReader - * @see BeanDefinitionDocumentReader - * @see XmlBeanDefinitionReader#setParserClass - */ -@Deprecated -public interface XmlBeanDefinitionParser { - - /** - * Parse bean definitions from the given DOM document, - * and register them with the given bean factory. - * @param reader the bean definition reader, containing the bean factory - * to work on and the bean class loader to use. Can also be used to load - * further bean definition files referenced by the given document. - * @param doc the DOM document - * @param resource descriptor of the original XML resource - * (useful for displaying parse errors) - * @return the number of bean definitions found - * @throws BeanDefinitionStoreException in case of parsing errors - */ - int registerBeanDefinitions(BeanDefinitionReader reader, Document doc, Resource resource) - throws BeanDefinitionStoreException; - -} diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java index de802a6784f..ecc7aed92dd 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Set; - import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; @@ -104,8 +103,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { private int validationMode = VALIDATION_AUTO; - private Class parserClass; - private Class documentReaderClass = DefaultBeanDefinitionDocumentReader.class; private ProblemReporter problemReporter = new FailFastProblemReporter(); @@ -124,8 +121,8 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { private final XmlValidationModeDetector validationModeDetector = new XmlValidationModeDetector(); - private final ThreadLocal resourcesCurrentlyBeingLoaded = - new NamedThreadLocal("XML bean definition resources currently being loaded"); + private final ThreadLocal> resourcesCurrentlyBeingLoaded = + new NamedThreadLocal>("XML bean definition resources currently being loaded"); /** @@ -153,16 +150,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { return this.namespaceAware; } - /** - * Set if the XML parser should validate the document and thus enforce a DTD. - * @deprecated as of Spring 2.0: superseded by "validationMode" - * @see #setValidationMode - */ - @Deprecated - public void setValidating(boolean validating) { - this.validationMode = (validating ? VALIDATION_AUTO : VALIDATION_NONE); - } - /** * Set the validation mode to use by name. Defaults to {@link #VALIDATION_AUTO}. */ @@ -270,21 +257,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { this.errorHandler = errorHandler; } - /** - * Set the XmlBeanDefinitionParser implementation to use, - * responsible for the actual parsing of XML bean definitions. - * @deprecated as of Spring 2.0: superseded by "documentReaderClass" - * @see #setDocumentReaderClass - * @see XmlBeanDefinitionParser - */ - @Deprecated - public void setParserClass(Class parserClass) { - if (this.parserClass == null || !XmlBeanDefinitionParser.class.isAssignableFrom(parserClass)) { - throw new IllegalArgumentException("'parserClass' must be an XmlBeanDefinitionParser"); - } - this.parserClass = parserClass; - } - /** * Specify the BeanDefinitionDocumentReader implementation to use, * responsible for the actual reading of the XML bean definition document. @@ -325,9 +297,9 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { logger.info("Loading XML bean definitions from " + encodedResource.getResource()); } - Set currentResources = (Set) this.resourcesCurrentlyBeingLoaded.get(); + Set currentResources = this.resourcesCurrentlyBeingLoaded.get(); if (currentResources == null) { - currentResources = new HashSet(4); + currentResources = new HashSet(4); this.resourcesCurrentlyBeingLoaded.set(currentResources); } if (!currentResources.add(encodedResource)) { @@ -497,12 +469,6 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { * @see BeanDefinitionDocumentReader#registerBeanDefinitions */ public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { - // Support old XmlBeanDefinitionParser SPI for backwards-compatibility. - if (this.parserClass != null) { - XmlBeanDefinitionParser parser = - (XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass); - return parser.registerBeanDefinitions(this, doc, resource); - } // Read document based on new BeanDefinitionDocumentReader SPI. BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); int countBefore = getRegistry().getBeanDefinitionCount(); @@ -513,11 +479,12 @@ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { /** * Create the {@link BeanDefinitionDocumentReader} to use for actually * reading bean definitions from an XML document. - *

Default implementation instantiates the specified "documentReaderClass". + *

The default implementation instantiates the specified "documentReaderClass". * @see #setDocumentReaderClass */ + @SuppressWarnings("unchecked") protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() { - return (BeanDefinitionDocumentReader) BeanUtils.instantiateClass(this.documentReaderClass); + return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass)); } /** diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/ClassArrayEditor.java b/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/ClassArrayEditor.java index 9d831ca53cf..ab8e93b48db 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/ClassArrayEditor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/ClassArrayEditor.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. @@ -84,14 +84,14 @@ public class ClassArrayEditor extends PropertyEditorSupport { private static String toCommaDelimitedString(Class[] classes) { - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < classes.length; ++i) { if (i > 0) { - buffer.append(","); + sb.append(","); } - buffer.append(ClassUtils.getQualifiedName(classes[i])); + sb.append(ClassUtils.getQualifiedName(classes[i])); } - return buffer.toString(); + return sb.toString(); } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/CustomDateEditor.java b/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/CustomDateEditor.java index d832686fb25..e5543b28d15 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/CustomDateEditor.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/CustomDateEditor.java @@ -107,10 +107,7 @@ public class CustomDateEditor extends PropertyEditorSupport { setValue(this.dateFormat.parse(text)); } catch (ParseException ex) { - IllegalArgumentException iae = - new IllegalArgumentException("Could not parse date: " + ex.getMessage()); - iae.initCause(ex); - throw iae; + throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex); } } } diff --git a/org.springframework.beans/src/test/java/org/springframework/beans/BeanUtilsTests.java b/org.springframework.beans/src/test/java/org/springframework/beans/BeanUtilsTests.java index 29b9a239b3d..1e4edf3c36e 100644 --- a/org.springframework.beans/src/test/java/org/springframework/beans/BeanUtilsTests.java +++ b/org.springframework.beans/src/test/java/org/springframework/beans/BeanUtilsTests.java @@ -169,7 +169,7 @@ public class BeanUtilsTests extends TestCase { } public void testResolveSimpleSignature() throws Exception { - Method desiredMethod = MethodSignatureBean.class.getMethod("doSomething", null); + Method desiredMethod = MethodSignatureBean.class.getMethod("doSomething"); assertSignatureEquals(desiredMethod, "doSomething"); assertSignatureEquals(desiredMethod, "doSomething()"); } @@ -205,7 +205,7 @@ public class BeanUtilsTests extends TestCase { public void testResolveOverloadedSignature() throws Exception { // test resolve with no args - Method desiredMethod = MethodSignatureBean.class.getMethod("overloaded", null); + Method desiredMethod = MethodSignatureBean.class.getMethod("overloaded"); assertSignatureEquals(desiredMethod, "overloaded()"); // resolve with single arg diff --git a/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperTests.java b/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperTests.java index e312113b88a..5d10c903924 100644 --- a/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperTests.java +++ b/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperTests.java @@ -35,7 +35,6 @@ import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; -import junit.framework.Assert; import junit.framework.TestCase; import org.apache.commons.logging.LogFactory; import org.hibernate.FlushMode; @@ -55,20 +54,6 @@ import org.springframework.util.StringUtils; */ public class BeanWrapperTests extends TestCase { - public void testSetWrappedInstanceOfSameClass() throws Exception { - TestBean tb = new TestBean(); - BeanWrapper bw = new BeanWrapperImpl(tb); - assertTrue(bw.isReadableProperty("age")); - tb.setAge(11); - - TestBean tb2 = new TestBean(); - bw.setWrappedInstance(tb2); - - bw.setPropertyValue("age", new Integer(14)); - assertTrue("2nd changed", tb2.getAge() == 14); - assertTrue("1 didn't change", tb.getAge() == 11); - } - public void testIsReadablePropertyNotReadable() { NoRead nr = new NoRead(); BeanWrapper bw = new BeanWrapperImpl(nr); @@ -165,17 +150,6 @@ public class BeanWrapperTests extends TestCase { assertEquals(String.class, bw.getPropertyType("map[key0]")); } - public void testSetWrappedInstanceOfDifferentClass() { - ThrowsException tex = new ThrowsException(); - BeanWrapper bw = new BeanWrapperImpl(tex); - - TestBean tb2 = new TestBean(); - bw.setWrappedInstance(tb2); - - bw.setPropertyValue("age", new Integer(14)); - assertTrue("2nd changed", tb2.getAge() == 14); - } - public void testGetterThrowsException() { GetterBean gb = new GetterBean(); BeanWrapper bw = new BeanWrapperImpl(gb); @@ -369,11 +343,11 @@ public class BeanWrapperTests extends TestCase { EnumTester et = new EnumTester(); BeanWrapper bw = new BeanWrapperImpl(et); - bw.setPropertyValue("flushMode", "NEVER"); - Assert.assertEquals(FlushMode.NEVER, et.getFlushMode()); + bw.setPropertyValue("flushMode", "MANUAL"); + assertEquals(FlushMode.MANUAL, et.getFlushMode()); bw.setPropertyValue("flushMode", " AUTO "); - Assert.assertEquals(FlushMode.AUTO, et.getFlushMode()); + assertEquals(FlushMode.AUTO, et.getFlushMode()); try { bw.setPropertyValue("flushMode", "EVER"); @@ -796,36 +770,6 @@ public class BeanWrapperTests extends TestCase { "Lewisham".equals(kbw.getPropertyValue("spouse.spouse.spouse.spouse.company"))); } - public void testNewWrappedInstancePropertyValuesGet() { - BeanWrapper bw = new BeanWrapperImpl(); - - TestBean t = new TestBean("Tony", 50); - bw.setWrappedInstance(t); - assertEquals("Bean wrapper returns wrong property value", - new Integer(t.getAge()), bw.getPropertyValue("age")); - - TestBean u = new TestBean("Udo", 30); - bw.setWrappedInstance(u); - assertEquals("Bean wrapper returns cached property value", - new Integer(u.getAge()), bw.getPropertyValue("age")); - } - - public void testNewWrappedInstanceNestedPropertyValuesGet() { - BeanWrapper bw = new BeanWrapperImpl(); - - TestBean t = new TestBean("Tony", 50); - t.setSpouse(new TestBean("Sue", 40)); - bw.setWrappedInstance(t); - assertEquals("Bean wrapper returns wrong nested property value", - new Integer(t.getSpouse().getAge()), bw.getPropertyValue("spouse.age")); - - TestBean u = new TestBean("Udo", 30); - u.setSpouse(new TestBean("Vera", 20)); - bw.setWrappedInstance(u); - assertEquals("Bean wrapper returns cached nested property value", - new Integer(u.getSpouse().getAge()), bw.getPropertyValue("spouse.age")); - } - public void testNullObject() { try { new BeanWrapperImpl((Object) null); @@ -1160,7 +1104,7 @@ public class BeanWrapperTests extends TestCase { BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("someProperty", "someValue"); assertEquals("someValue", bw.getPropertyValue("someProperty")); - Assert.assertEquals("someValue", bean.getSomeProperty()); + assertEquals("someValue", bean.getSomeProperty()); } public void testErrorMessageOfNestedProperty() { diff --git a/org.springframework.beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java b/org.springframework.beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java index 81ab7fe5ff4..d6f03943a8a 100644 --- a/org.springframework.beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java +++ b/org.springframework.beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.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,7 @@ package org.springframework.beans.factory; +import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; @@ -28,6 +29,8 @@ import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.core.io.ClassPathResource; @@ -59,14 +62,17 @@ public class ConcurrentBeanFactoryTests extends TestCase { private BeanFactory factory; - private Set set = Collections.synchronizedSet(new HashSet()); + private final Set set = Collections.synchronizedSet(new HashSet()); private Throwable ex = null; protected void setUp() throws Exception { XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("concurrent.xml", getClass())); - CustomDateEditor editor = new CustomDateEditor(df, false); - factory.registerCustomEditor(Date.class, editor); + factory.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { + public void registerCustomEditors(PropertyEditorRegistry registry) { + registry.registerCustomEditor(Date.class, new CustomDateEditor((DateFormat) df.clone(), false)); + } + }); this.factory = factory; } diff --git a/org.springframework.beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java b/org.springframework.beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java index df3faa10a56..c00c22de600 100644 --- a/org.springframework.beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java +++ b/org.springframework.beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java @@ -28,6 +28,8 @@ import junit.framework.TestCase; import org.springframework.beans.FatalBeanException; import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.TestBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; @@ -39,13 +41,16 @@ import org.springframework.beans.propertyeditors.CustomDateEditor; */ public class CustomEditorConfigurerTests extends TestCase { - public void testCustomEditorConfigurerWithRequiredTypeAsClassName() throws ParseException { + public void testCustomEditorConfigurerWithPropertyEditorRegistrar() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN); - editors.put(Date.class.getName(), new CustomDateEditor(df, true)); - cec.setCustomEditors(editors); + final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN); + cec.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] { + new PropertyEditorRegistrar() { + public void registerCustomEditors(PropertyEditorRegistry registry) { + registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true)); + } + }}); cec.postProcessBeanFactory(bf); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -61,45 +66,11 @@ public class CustomEditorConfigurerTests extends TestCase { assertEquals(df.parse("2.12.1975"), tb2.getSomeMap().get("myKey")); } - public void testCustomEditorConfigurerWithRequiredTypeAsClass() throws ParseException { + public void testCustomEditorConfigurerWithEditorClassName() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN); - editors.put(Date.class, new CustomDateEditor(df, true)); - cec.setCustomEditors(editors); - cec.postProcessBeanFactory(bf); - - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue("date", "2.12.1975"); - bf.registerBeanDefinition("tb", new RootBeanDefinition(TestBean.class, pvs)); - - TestBean tb = (TestBean) bf.getBean("tb"); - assertEquals(df.parse("2.12.1975"), tb.getDate()); - } - - public void testCustomEditorConfigurerWithEditorAsClassName() throws ParseException { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - editors.put(Date.class, MyDateEditor.class.getName()); - cec.setCustomEditors(editors); - cec.postProcessBeanFactory(bf); - - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.addPropertyValue("date", "2.12.1975"); - bf.registerBeanDefinition("tb", new RootBeanDefinition(TestBean.class, pvs)); - - TestBean tb = (TestBean) bf.getBean("tb"); - DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN); - assertEquals(df.parse("2.12.1975"), tb.getDate()); - } - - public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - editors.put(Date.class, MyDateEditor.class); + Map editors = new HashMap(); + editors.put(Date.class.getName(), MyDateEditor.class.getName()); cec.setCustomEditors(editors); cec.postProcessBeanFactory(bf); @@ -115,12 +86,8 @@ public class CustomEditorConfigurerTests extends TestCase { public void testCustomEditorConfigurerWithRequiredTypeArray() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - editors.put("java.lang.String[]", new PropertyEditorSupport() { - public void setAsText(String text) { - setValue(new String[] {"test"}); - } - }); + Map editors = new HashMap(); + editors.put("java.lang.String[]", MyTestEditor.class.getName()); cec.setCustomEditors(editors); cec.postProcessBeanFactory(bf); @@ -136,8 +103,8 @@ public class CustomEditorConfigurerTests extends TestCase { public void testCustomEditorConfigurerWithUnresolvableEditor() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - editors.put(Date.class, "MyNonExistingEditor"); + Map editors = new HashMap(); + editors.put(Date.class.getName(), "MyNonExistingEditor"); editors.put("MyNonExistingType", "MyNonExistingEditor"); cec.setCustomEditors(editors); try { @@ -152,8 +119,8 @@ public class CustomEditorConfigurerTests extends TestCase { public void testCustomEditorConfigurerWithIgnoredUnresolvableEditor() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); - Map editors = new HashMap(); - editors.put(Date.class, "MyNonExistingEditor"); + Map editors = new HashMap(); + editors.put(Date.class.getName(), "MyNonExistingEditor"); editors.put("MyNonExistingType", "MyNonExistingEditor"); cec.setCustomEditors(editors); cec.setIgnoreUnresolvableEditors(true); @@ -168,4 +135,12 @@ public class CustomEditorConfigurerTests extends TestCase { } } + + public static class MyTestEditor extends PropertyEditorSupport { + + public void setAsText(String text) { + setValue(new String[] {"test"}); + } + } + } diff --git a/org.springframework.context.support/context-support.iml b/org.springframework.context.support/context-support.iml index 3fb43deab8a..a2dfc62e5d9 100644 --- a/org.springframework.context.support/context-support.iml +++ b/org.springframework.context.support/context-support.iml @@ -1,169 +1,169 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java b/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java index 6ccda27ef7b..acdd77b11d2 100644 --- a/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java +++ b/org.springframework.context.support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java @@ -19,7 +19,6 @@ package org.springframework.mail.javamail; import java.io.File; import java.io.IOException; import java.io.InputStream; - import javax.activation.FileTypeMap; import javax.activation.MimetypesFileTypeMap; @@ -119,10 +118,8 @@ public class ConfigurableMimeFileTypeMap extends FileTypeMap implements Initiali this.fileTypeMap = createFileTypeMap(this.mappingLocation, this.mappings); } catch (IOException ex) { - IllegalStateException ise = new IllegalStateException( - "Could not load specified MIME type mapping file: " + this.mappingLocation); - ise.initCause(ex); - throw ise; + throw new IllegalStateException( + "Could not load specified MIME type mapping file: " + this.mappingLocation, ex); } } return this.fileTypeMap; diff --git a/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java b/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java index 08bf1b1833a..e4e73f303f2 100644 --- a/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java +++ b/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java @@ -95,13 +95,17 @@ public class SchedulerFactoryBean extends SchedulerAccessor public static final int DEFAULT_THREAD_COUNT = 10; - private static final ThreadLocal configTimeResourceLoaderHolder = new ThreadLocal(); + private static final ThreadLocal configTimeResourceLoaderHolder = + new ThreadLocal(); - private static final ThreadLocal configTimeTaskExecutorHolder = new ThreadLocal(); + private static final ThreadLocal configTimeTaskExecutorHolder = + new ThreadLocal(); - private static final ThreadLocal configTimeDataSourceHolder = new ThreadLocal(); + private static final ThreadLocal configTimeDataSourceHolder = + new ThreadLocal(); - private static final ThreadLocal configTimeNonTransactionalDataSourceHolder = new ThreadLocal(); + private static final ThreadLocal configTimeNonTransactionalDataSourceHolder = + new ThreadLocal(); /** * Return the ResourceLoader for the currently configured Quartz Scheduler, @@ -113,7 +117,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor * @see ResourceLoaderClassLoadHelper */ public static ResourceLoader getConfigTimeResourceLoader() { - return (ResourceLoader) configTimeResourceLoaderHolder.get(); + return configTimeResourceLoaderHolder.get(); } /** @@ -126,7 +130,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor * @see LocalTaskExecutorThreadPool */ public static TaskExecutor getConfigTimeTaskExecutor() { - return (TaskExecutor) configTimeTaskExecutorHolder.get(); + return configTimeTaskExecutorHolder.get(); } /** @@ -139,7 +143,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor * @see LocalDataSourceJobStore */ public static DataSource getConfigTimeDataSource() { - return (DataSource) configTimeDataSourceHolder.get(); + return configTimeDataSourceHolder.get(); } /** @@ -152,7 +156,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor * @see LocalDataSourceJobStore */ public static DataSource getConfigTimeNonTransactionalDataSource() { - return (DataSource) configTimeNonTransactionalDataSourceHolder.get(); + return configTimeNonTransactionalDataSourceHolder.get(); } diff --git a/org.springframework.context/context.iml b/org.springframework.context/context.iml index c6fe1fb5982..0cff2d9a162 100644 --- a/org.springframework.context/context.iml +++ b/org.springframework.context/context.iml @@ -1,193 +1,194 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.context/ivy.xml b/org.springframework.context/ivy.xml index 5217970acfd..323edfde39b 100644 --- a/org.springframework.context/ivy.xml +++ b/org.springframework.context/ivy.xml @@ -48,6 +48,7 @@ + diff --git a/org.springframework.context/src/main/java/org/springframework/context/ConfigurableApplicationContext.java b/org.springframework.context/src/main/java/org/springframework/context/ConfigurableApplicationContext.java index e5266d0bdf9..6854cd1aa8a 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/ConfigurableApplicationContext.java +++ b/org.springframework.context/src/main/java/org/springframework/context/ConfigurableApplicationContext.java @@ -52,6 +52,18 @@ public interface ConfigurableApplicationContext extends ApplicationContext, Life */ String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver"; + /** + * Name of the System properties bean in the factory. + * @see java.lang.System#getProperties() + */ + String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties"; + + /** + * Name of the System environment bean in the factory. + * @see java.lang.System#getenv() + */ + String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment"; + /** * Set the parent of this application context. diff --git a/org.springframework.context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java b/org.springframework.context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java index 4f0bb07569d..0590d0265f3 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java +++ b/org.springframework.context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java @@ -609,7 +609,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean "] does not carry a WebServiceClient annotation"); } service = (Service) BeanUtils.instantiateClass(ctor, - new Object[] {new URL(this.wsdlLocation), new QName(clientAnn.targetNamespace(), clientAnn.name())}); + new URL(this.wsdlLocation), new QName(clientAnn.targetNamespace(), clientAnn.name())); } catch (NoSuchMethodException ex) { throw new IllegalStateException("JAX-WS Service class [" + this.lookupType.getName() + diff --git a/org.springframework.context/src/main/java/org/springframework/context/config/ContextNamespaceHandler.java b/org.springframework.context/src/main/java/org/springframework/context/config/ContextNamespaceHandler.java index 9a07fd2dc4a..62f83a8f0d6 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/config/ContextNamespaceHandler.java +++ b/org.springframework.context/src/main/java/org/springframework/context/config/ContextNamespaceHandler.java @@ -16,14 +16,9 @@ package org.springframework.context.config; -import org.w3c.dom.Element; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.core.JdkVersion; -import org.springframework.util.ClassUtils; +import org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser; +import org.springframework.context.annotation.ComponentScanBeanDefinitionParser; /** * {@link org.springframework.beans.factory.xml.NamespaceHandler} @@ -38,36 +33,12 @@ public class ContextNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser()); registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser()); - registerJava5DependentParser("annotation-config", - "org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser"); - registerJava5DependentParser("component-scan", - "org.springframework.context.annotation.ComponentScanBeanDefinitionParser"); + registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser()); + registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser()); registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser()); registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser()); registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser()); } - private void registerJava5DependentParser(final String elementName, final String parserClassName) { - BeanDefinitionParser parser = null; - if (JdkVersion.isAtLeastJava15()) { - try { - Class parserClass = ClassUtils.forName(parserClassName, ContextNamespaceHandler.class.getClassLoader()); - parser = (BeanDefinitionParser) parserClass.newInstance(); - } - catch (Throwable ex) { - throw new IllegalStateException("Unable to create Java 1.5 dependent parser: " + parserClassName, ex); - } - } - else { - parser = new BeanDefinitionParser() { - public BeanDefinition parse(Element element, ParserContext parserContext) { - throw new IllegalStateException("Context namespace element '" + elementName + - "' and its parser class [" + parserClassName + "] are only available on JDK 1.5 and higher"); - } - }; - } - registerBeanDefinitionParser(elementName, parser); - } - } diff --git a/org.springframework.context/src/main/java/org/springframework/context/config/MBeanExportBeanDefinitionParser.java b/org.springframework.context/src/main/java/org/springframework/context/config/MBeanExportBeanDefinitionParser.java index a04d26aa4d7..779894122ce 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/config/MBeanExportBeanDefinitionParser.java +++ b/org.springframework.context/src/main/java/org/springframework/context/config/MBeanExportBeanDefinitionParser.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.core.JdkVersion; +import org.springframework.jmx.export.annotation.AnnotationMBeanExporter; import org.springframework.jmx.support.MBeanRegistrationSupport; import org.springframework.util.StringUtils; @@ -61,10 +61,7 @@ class MBeanExportBeanDefinitionParser extends AbstractBeanDefinitionParser { @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { - String beanClassName = (JdkVersion.isAtLeastJava15() ? - "org.springframework.jmx.export.annotation.AnnotationMBeanExporter" : - "org.springframework.jmx.export.MBeanExporter"); - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClassName); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AnnotationMBeanExporter.class); // Mark as infrastructure bean and attach source location. builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); @@ -94,7 +91,7 @@ class MBeanExportBeanDefinitionParser extends AbstractBeanDefinitionParser { else if (REGISTRATION_REPLACE_EXISTING.equals(registration)) { registrationBehavior = MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING; } - builder.addPropertyValue("registrationBehavior", new Integer(registrationBehavior)); + builder.addPropertyValue("registrationBehavior", registrationBehavior); return builder.getBeanDefinition(); } diff --git a/org.springframework.context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java b/org.springframework.context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java index 91af674736d..b60efbf1366 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java +++ b/org.springframework.context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.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,10 +18,10 @@ package org.springframework.context.event; import java.util.Collection; import java.util.LinkedHashSet; +import java.util.concurrent.CopyOnWriteArraySet; import org.springframework.beans.BeanUtils; import org.springframework.context.ApplicationListener; -import org.springframework.core.CollectionFactory; /** * Abstract implementation of the {@link ApplicationEventMulticaster} interface, @@ -46,7 +46,7 @@ import org.springframework.core.CollectionFactory; public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster { /** Collection of ApplicationListeners */ - private Collection applicationListeners = new LinkedHashSet(); + private Collection applicationListeners = new LinkedHashSet(); /** @@ -56,7 +56,8 @@ public abstract class AbstractApplicationEventMulticaster implements Application * without synchronization while still making listener updates thread-safe. */ public void setConcurrentUpdates(boolean concurrent) { - Collection newColl = (concurrent ? CollectionFactory.createCopyOnWriteSet() : new LinkedHashSet()); + Collection newColl = concurrent ? + new CopyOnWriteArraySet() : new LinkedHashSet(); // Add all previously registered listeners (usually none). newColl.addAll(this.applicationListeners); this.applicationListeners = newColl; @@ -70,6 +71,7 @@ public abstract class AbstractApplicationEventMulticaster implements Application * of the same listener, while a List class will allow for registering * the same listener multiple times. */ + @SuppressWarnings("unchecked") public void setCollectionClass(Class collectionClass) { if (collectionClass == null) { throw new IllegalArgumentException("'collectionClass' must not be null"); @@ -78,7 +80,8 @@ public abstract class AbstractApplicationEventMulticaster implements Application throw new IllegalArgumentException("'collectionClass' must implement [java.util.Collection]"); } // Create desired collection instance. - Collection newColl = (Collection) BeanUtils.instantiateClass(collectionClass); + Collection newColl = + (Collection) BeanUtils.instantiateClass(collectionClass); // Add all previously registered listeners (usually none). newColl.addAll(this.applicationListeners); this.applicationListeners = newColl; diff --git a/org.springframework.context/src/main/java/org/springframework/context/expression/AbstractBeanExpressionResolver.java b/org.springframework.context/src/main/java/org/springframework/context/expression/AbstractBeanExpressionResolver.java new file mode 100644 index 00000000000..6143b2520eb --- /dev/null +++ b/org.springframework.context/src/main/java/org/springframework/context/expression/AbstractBeanExpressionResolver.java @@ -0,0 +1,115 @@ +/* + * 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.context.expression; + +import org.springframework.beans.factory.config.BeanExpressionContext; +import org.springframework.beans.factory.config.BeanExpressionResolver; +import org.springframework.util.Assert; + +/** + * Abstract implementation of the {@link BeanExpressionResolver} interface. + * Handles the common mixing of expression parts with literal parts. + * + *

Subclasses need to implement the {@link #evaluateExpression} template + * method for actual expression evaluation. + * + * @author Juergen Hoeller + * @since 3.0 + * @see #setExpressionPrefix + * @see #setExpressionSuffix + */ +public abstract class AbstractBeanExpressionResolver implements BeanExpressionResolver { + + /** Default expression prefix: "#{" */ + public static final String DEFAULT_EXPRESSION_PREFIX = "#{"; + + /** Default expression suffix: "}" */ + public static final String DEFAULT_EXPRESSION_SUFFIX = "}"; + + + private String expressionPrefix = DEFAULT_EXPRESSION_PREFIX; + + private String expressionSuffix = DEFAULT_EXPRESSION_SUFFIX; + + + /** + * Set the prefix that an expression string starts with. + * The default is "#{". + * @see #DEFAULT_EXPRESSION_PREFIX + */ + public void setExpressionPrefix(String expressionPrefix) { + Assert.hasText(expressionPrefix, "Expression prefix must not be empty"); + this.expressionPrefix = expressionPrefix; + } + + /** + * Set the suffix that an expression string ends with. + * The default is "}". + * @see #DEFAULT_EXPRESSION_SUFFIX + */ + public void setExpressionSuffix(String expressionSuffix) { + Assert.hasText(expressionSuffix, "Expression suffix must not be empty"); + this.expressionSuffix = expressionSuffix; + } + + + public Object evaluate(String value, BeanExpressionContext evalContext) { + if (value == null) { + return null; + } + Object result = ""; + int prefixIndex = value.indexOf(this.expressionPrefix); + int endIndex = 0; + while (prefixIndex != -1) { + int exprStart = prefixIndex + this.expressionPrefix.length(); + int suffixIndex = value.indexOf(this.expressionSuffix, exprStart); + if (suffixIndex != -1) { + if (prefixIndex > 0) { + result = result + value.substring(endIndex, prefixIndex); + } + endIndex = suffixIndex + this.expressionSuffix.length(); + String expr = value.substring(exprStart, suffixIndex); + Object exprResult = evaluateExpression(expr, evalContext); + if (result != null && !"".equals(result)) { + result = result.toString() + exprResult.toString(); + } + else { + result = exprResult; + } + prefixIndex = value.indexOf(this.expressionPrefix, suffixIndex); + } + else { + prefixIndex = -1; + } + } + if (endIndex < value.length()) { + return result + value.substring(endIndex); + } + else { + return result; + } + } + + /** + * Evaluate the given expression. + * @param exprString the expression String to evaluate + * @param evalContext the context to evaluate the expression within + * @return the evaluation result + */ + protected abstract Object evaluateExpression(String exprString, BeanExpressionContext evalContext); + +} diff --git a/org.springframework.context/src/main/java/org/springframework/context/expression/BeanExpressionContextAccessor.java b/org.springframework.context/src/main/java/org/springframework/context/expression/BeanExpressionContextAccessor.java new file mode 100644 index 00000000000..73a8a906ab9 --- /dev/null +++ b/org.springframework.context/src/main/java/org/springframework/context/expression/BeanExpressionContextAccessor.java @@ -0,0 +1,53 @@ +/* + * 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.context.expression; + +import org.springframework.beans.factory.config.BeanExpressionContext; +import org.springframework.expression.AccessException; +import org.springframework.expression.EvaluationContext; +import org.springframework.expression.PropertyAccessor; + +/** + * EL property accessor that knows how to traverse the beans and contextual objects + * of a Spring {@link org.springframework.beans.factory.config.BeanExpressionContext}. + * + * @author Juergen Hoeller + * @since 3.0 + */ +public class BeanExpressionContextAccessor implements PropertyAccessor { + + public boolean canRead(EvaluationContext context, Object target, Object name) throws AccessException { + return (((BeanExpressionContext) target).containsObject(name.toString())); + } + + public Object read(EvaluationContext context, Object target, Object name) throws AccessException { + return ((BeanExpressionContext) target).getObject(name.toString()); + } + + public boolean canWrite(EvaluationContext context, Object target, Object name) throws AccessException { + return false; + } + + public void write(EvaluationContext context, Object target, Object name, Object newValue) throws AccessException { + throw new AccessException("Beans in a BeanFactory are read-only"); + } + + public Class[] getSpecificTargetClasses() { + return new Class[] {BeanExpressionContext.class}; + } + +} \ No newline at end of file diff --git a/org.springframework.context/src/main/java/org/springframework/context/expression/BeanFactoryAccessor.java b/org.springframework.context/src/main/java/org/springframework/context/expression/BeanFactoryAccessor.java new file mode 100644 index 00000000000..9fab7e9c368 --- /dev/null +++ b/org.springframework.context/src/main/java/org/springframework/context/expression/BeanFactoryAccessor.java @@ -0,0 +1,53 @@ +/* + * 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.context.expression; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.expression.AccessException; +import org.springframework.expression.EvaluationContext; +import org.springframework.expression.PropertyAccessor; + +/** + * EL property accessor that knows how to traverse the beans of a + * Spring {@link org.springframework.beans.factory.BeanFactory}. + * + * @author Juergen Hoeller + * @since 3.0 + */ +public class BeanFactoryAccessor implements PropertyAccessor { + + public boolean canRead(EvaluationContext context, Object target, Object name) throws AccessException { + return (((BeanFactory) target).containsBean(name.toString())); + } + + public Object read(EvaluationContext context, Object target, Object name) throws AccessException { + return ((BeanFactory) target).getBean(name.toString()); + } + + public boolean canWrite(EvaluationContext context, Object target, Object name) throws AccessException { + return false; + } + + public void write(EvaluationContext context, Object target, Object name, Object newValue) throws AccessException { + throw new AccessException("Beans in a BeanFactory are read-only"); + } + + public Class[] getSpecificTargetClasses() { + return new Class[] {BeanFactory.class}; + } + +} diff --git a/org.springframework.context/src/main/java/org/springframework/context/expression/MapAccessor.java b/org.springframework.context/src/main/java/org/springframework/context/expression/MapAccessor.java new file mode 100644 index 00000000000..6b54c418eb3 --- /dev/null +++ b/org.springframework.context/src/main/java/org/springframework/context/expression/MapAccessor.java @@ -0,0 +1,54 @@ +/* + * 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.context.expression; + +import java.util.Map; + +import org.springframework.expression.AccessException; +import org.springframework.expression.EvaluationContext; +import org.springframework.expression.PropertyAccessor; + +/** + * EL property accessor that knows how to traverse the keys + * of a standard {@link java.util.Map}. + * + * @author Juergen Hoeller + * @since 3.0 + */ +public class MapAccessor implements PropertyAccessor { + + public boolean canRead(EvaluationContext context, Object target, Object name) throws AccessException { + return (((Map) target).containsKey(name)); + } + + public Object read(EvaluationContext context, Object target, Object name) throws AccessException { + return ((Map) target).get(name); + } + + public boolean canWrite(EvaluationContext context, Object target, Object name) throws AccessException { + return true; + } + + public void write(EvaluationContext context, Object target, Object name, Object newValue) throws AccessException { + ((Map) target).put(name, newValue); + } + + public Class[] getSpecificTargetClasses() { + return new Class[] {Map.class}; + } + +} diff --git a/org.springframework.context/src/main/java/org/springframework/context/expression/StandardBeanExpressionResolver.java b/org.springframework.context/src/main/java/org/springframework/context/expression/StandardBeanExpressionResolver.java new file mode 100644 index 00000000000..2cb2d536744 --- /dev/null +++ b/org.springframework.context/src/main/java/org/springframework/context/expression/StandardBeanExpressionResolver.java @@ -0,0 +1,74 @@ +/* + * 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.context.expression; + +import org.springframework.beans.factory.BeanExpressionException; +import org.springframework.beans.factory.config.BeanExpressionContext; +import org.springframework.expression.Expression; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.SpelExpressionParser; +import org.springframework.expression.spel.standard.StandardEvaluationContext; +import org.springframework.util.Assert; + +/** + * Standard implementation of the {@link BeanExpressionResolver} interface, + * parsing and evaluating Spring EL using Spring's expression module. + * + * @author Juergen Hoeller + * @since 3.0 + * @see org.springframework.expression.ExpressionParser + * @see org.springframework.expression.spel.SpelExpressionParser + * @see org.springframework.expression.spel.standard.StandardEvaluationContext + */ +public class StandardBeanExpressionResolver extends AbstractBeanExpressionResolver { + + private ExpressionParser expressionParser = new SpelExpressionParser(); + + + /** + * Specify the EL parser to use for expression parsing. + *

Default is a {@link org.springframework.expression.spel.SpelExpressionParser}, + * compatible with standard Unified EL style expression syntax. + */ + public void setExpressionParser(ExpressionParser expressionParser) { + Assert.notNull(expressionParser, "ExpressionParser must not be null"); + this.expressionParser = expressionParser; + } + + + protected Object evaluateExpression(String exprString, BeanExpressionContext evalContext) { + try { + Expression expr = this.expressionParser.parseExpression(exprString); + StandardEvaluationContext ec = new StandardEvaluationContext(evalContext); + ec.addPropertyAccessor(new BeanExpressionContextAccessor()); + ec.addPropertyAccessor(new BeanFactoryAccessor()); + ec.addPropertyAccessor(new MapAccessor()); + return expr.getValue(ec); + } + catch (Exception ex) { + throw new BeanExpressionException("Expression parsing failed", ex); + } + } + + /** + * Template method for customizing the expression evaluation context. + *

The default implementation is empty. + */ + protected void customizeEvaluationContext(StandardEvaluationContext evalContext) { + } + +} diff --git a/org.springframework.context/src/main/java/org/springframework/context/expression/package.html b/org.springframework.context/src/main/java/org/springframework/context/expression/package.html new file mode 100644 index 00000000000..eaef03149cd --- /dev/null +++ b/org.springframework.context/src/main/java/org/springframework/context/expression/package.html @@ -0,0 +1,7 @@ + + + +Expression parsing support within a Spring application context. + + + 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 58bf66e7e3b..020a5235f79 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 @@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -30,10 +29,9 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeanUtils; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; @@ -61,7 +59,8 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.ContextStartedEvent; import org.springframework.context.event.ContextStoppedEvent; import org.springframework.context.event.SimpleApplicationEventMulticaster; -import org.springframework.core.JdkVersion; +import org.springframework.context.expression.StandardBeanExpressionResolver; +import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; @@ -71,7 +70,6 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; /** @@ -151,7 +149,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader private ApplicationContext parent; /** BeanFactoryPostProcessors to apply on refresh */ - private final List beanFactoryPostProcessors = new ArrayList(); + private final List beanFactoryPostProcessors = + new ArrayList(); /** Display name */ private String displayName; @@ -181,7 +180,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader private ApplicationEventMulticaster applicationEventMulticaster; /** Statically specified listeners */ - private List applicationListeners = new ArrayList(); + private List applicationListeners = new ArrayList(); /** @@ -324,9 +323,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader /** * Return the list of BeanFactoryPostProcessors that will get applied * to the internal BeanFactory. - * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor */ - public List getBeanFactoryPostProcessors() { + public List getBeanFactoryPostProcessors() { return this.beanFactoryPostProcessors; } @@ -336,9 +334,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader /** * Return the list of statically specified ApplicationListeners. - * @see org.springframework.context.ApplicationListener */ - public List getApplicationListeners() { + public List getApplicationListeners() { return this.applicationListeners; } @@ -439,10 +436,9 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader * @param beanFactory the BeanFactory to configure */ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { - // Tell the internal bean factory to use the context's class loader. + // Tell the internal bean factory to use the context's class loader etc. beanFactory.setBeanClassLoader(getClassLoader()); - - // Populate the bean factory with context-specific resource editors. + beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver()); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this)); // Configure the bean factory with context callbacks. @@ -460,22 +456,19 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Detect a LoadTimeWeaver and prepare for weaving, if found. - if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME) && JdkVersion.isAtLeastJava15()) { - // Register the (JDK 1.5 specific) LoadTimeWeaverAwareProcessor. - try { - Class ltwapClass = ClassUtils.forName( - "org.springframework.context.weaving.LoadTimeWeaverAwareProcessor", - AbstractApplicationContext.class.getClassLoader()); - BeanPostProcessor ltwap = (BeanPostProcessor) BeanUtils.instantiateClass(ltwapClass); - ((BeanFactoryAware) ltwap).setBeanFactory(beanFactory); - beanFactory.addBeanPostProcessor(ltwap); - } - catch (ClassNotFoundException ex) { - throw new IllegalStateException("Spring's LoadTimeWeaverAwareProcessor class is not available"); - } + if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { + beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } + + // Register default environment beans. + if (!beanFactory.containsBean(SYSTEM_PROPERTIES_BEAN_NAME)) { + beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, System.getProperties()); + } + if (!beanFactory.containsBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { + beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, System.getenv()); + } } /** @@ -495,8 +488,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader */ protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { // Invoke factory processors registered with the context instance. - for (Iterator it = getBeanFactoryPostProcessors().iterator(); it.hasNext();) { - BeanFactoryPostProcessor factoryProcessor = (BeanFactoryPostProcessor) it.next(); + for (BeanFactoryPostProcessor factoryProcessor : getBeanFactoryPostProcessors()) { factoryProcessor.postProcessBeanFactory(beanFactory); } @@ -507,18 +499,18 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. - List priorityOrderedPostProcessors = new ArrayList(); - List orderedPostProcessorNames = new ArrayList(); - List nonOrderedPostProcessorNames = new ArrayList(); - for (int i = 0; i < postProcessorNames.length; i++) { - if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) { - priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i])); + List priorityOrderedPostProcessors = new ArrayList(); + List orderedPostProcessorNames = new ArrayList(); + List nonOrderedPostProcessorNames = new ArrayList(); + for (String ppName : postProcessorNames) { + if (isTypeMatch(ppName, PriorityOrdered.class)) { + priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } - else if (isTypeMatch(postProcessorNames[i], Ordered.class)) { - orderedPostProcessorNames.add(postProcessorNames[i]); + else if (isTypeMatch(ppName, Ordered.class)) { + orderedPostProcessorNames.add(ppName); } else { - nonOrderedPostProcessorNames.add(postProcessorNames[i]); + nonOrderedPostProcessorNames.add(ppName); } } @@ -527,19 +519,17 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader invokeBeanFactoryPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, invoke the BeanFactoryPostProcessors that implement Ordered. - List orderedPostProcessors = new ArrayList(); - for (Iterator it = orderedPostProcessorNames.iterator(); it.hasNext();) { - String postProcessorName = (String) it.next(); - orderedPostProcessors.add(getBean(postProcessorName)); + List orderedPostProcessors = new ArrayList(); + for (String postProcessorName : orderedPostProcessorNames) { + orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class)); } Collections.sort(orderedPostProcessors, new OrderComparator()); invokeBeanFactoryPostProcessors(beanFactory, orderedPostProcessors); // Finally, invoke all other BeanFactoryPostProcessors. - List nonOrderedPostProcessors = new ArrayList(); - for (Iterator it = nonOrderedPostProcessorNames.iterator(); it.hasNext();) { - String postProcessorName = (String) it.next(); - nonOrderedPostProcessors.add(getBean(postProcessorName)); + List nonOrderedPostProcessors = new ArrayList(); + for (String postProcessorName : nonOrderedPostProcessorNames) { + nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(beanFactory, nonOrderedPostProcessors); } @@ -547,9 +537,10 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader /** * Invoke the given BeanFactoryPostProcessor beans. */ - private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) { - for (Iterator it = postProcessors.iterator(); it.hasNext();) { - BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor) it.next(); + private void invokeBeanFactoryPostProcessors( + ConfigurableListableBeanFactory beanFactory, List postProcessors) { + + for (BeanFactoryPostProcessor postProcessor : postProcessors) { postProcessor.postProcessBeanFactory(beanFactory); } } @@ -570,18 +561,18 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. - List priorityOrderedPostProcessors = new ArrayList(); - List orderedPostProcessorNames = new ArrayList(); - List nonOrderedPostProcessorNames = new ArrayList(); - for (int i = 0; i < postProcessorNames.length; i++) { - if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) { - priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i])); + List priorityOrderedPostProcessors = new ArrayList(); + List orderedPostProcessorNames = new ArrayList(); + List nonOrderedPostProcessorNames = new ArrayList(); + for (String ppName : postProcessorNames) { + if (isTypeMatch(ppName, PriorityOrdered.class)) { + priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanPostProcessor.class)); } - else if (isTypeMatch(postProcessorNames[i], Ordered.class)) { - orderedPostProcessorNames.add(postProcessorNames[i]); + else if (isTypeMatch(ppName, Ordered.class)) { + orderedPostProcessorNames.add(ppName); } else { - nonOrderedPostProcessorNames.add(postProcessorNames[i]); + nonOrderedPostProcessorNames.add(ppName); } } @@ -590,19 +581,17 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. - List orderedPostProcessors = new ArrayList(); - for (Iterator it = orderedPostProcessorNames.iterator(); it.hasNext();) { - String postProcessorName = (String) it.next(); - orderedPostProcessors.add(getBean(postProcessorName)); + List orderedPostProcessors = new ArrayList(); + for (String postProcessorName : orderedPostProcessorNames) { + orderedPostProcessors.add(getBean(postProcessorName, BeanPostProcessor.class)); } Collections.sort(orderedPostProcessors, new OrderComparator()); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Finally, register all other BeanPostProcessors. - List nonOrderedPostProcessors = new ArrayList(); - for (Iterator it = nonOrderedPostProcessorNames.iterator(); it.hasNext();) { - String postProcessorName = (String) it.next(); - nonOrderedPostProcessors.add(getBean(postProcessorName)); + List nonOrderedPostProcessors = new ArrayList(); + for (String postProcessorName : nonOrderedPostProcessorNames) { + nonOrderedPostProcessors.add(getBean(postProcessorName, BeanPostProcessor.class)); } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); } @@ -610,9 +599,10 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader /** * Register the given BeanPostProcessor beans. */ - private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) { - for (Iterator it = postProcessors.iterator(); it.hasNext();) { - BeanPostProcessor postProcessor = (BeanPostProcessor) it.next(); + private void registerBeanPostProcessors( + ConfigurableListableBeanFactory beanFactory, List postProcessors) { + + for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); } } @@ -624,7 +614,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { - this.messageSource = (MessageSource) beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); + this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; @@ -659,7 +649,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { - this.applicationEventMulticaster = (ApplicationEventMulticaster) + this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); @@ -693,14 +683,14 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader */ protected void registerListeners() { // Register statically specified listeners first. - for (Iterator it = getApplicationListeners().iterator(); it.hasNext();) { - addListener((ApplicationListener) it.next()); + for (ApplicationListener listener : getApplicationListeners()) { + addListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! - Collection listenerBeans = getBeansOfType(ApplicationListener.class, true, false).values(); - for (Iterator it = listenerBeans.iterator(); it.hasNext();) { - addListener((ApplicationListener) it.next()); + Collection lisBeans = getBeansOfType(ApplicationListener.class, true, false).values(); + for (ApplicationListener lisBean : lisBeans) { + addListener(lisBean); } } @@ -823,9 +813,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader logger.error("Exception thrown from ApplicationListener handling ContextClosedEvent", ex); } // Stop all Lifecycle beans, to avoid delays during individual destruction. - Map lifecycleBeans = getLifecycleBeans(); - for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { - String beanName = (String) it.next(); + Map lifecycleBeans = getLifecycleBeans(); + for (String beanName : new LinkedHashSet(lifecycleBeans.keySet())) { doStop(lifecycleBeans, beanName); } // Destroy all cached singletons in the context's BeanFactory. @@ -881,7 +870,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader return getBeanFactory().getBean(name); } - public Object getBean(String name, Class requiredType) throws BeansException { + public T getBean(String name, Class requiredType) throws BeansException { return getBeanFactory().getBean(name, requiredType); } @@ -938,11 +927,11 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader return getBeanFactory().getBeanNamesForType(type, includePrototypes, allowEagerInit); } - public Map getBeansOfType(Class type) throws BeansException { + public Map getBeansOfType(Class type) throws BeansException { return getBeanFactory().getBeansOfType(type); } - public Map getBeansOfType(Class type, boolean includePrototypes, boolean allowEagerInit) + public Map getBeansOfType(Class type, boolean includePrototypes, boolean allowEagerInit) throws BeansException { return getBeanFactory().getBeansOfType(type, includePrototypes, allowEagerInit); @@ -968,7 +957,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader */ protected BeanFactory getInternalParentBeanFactory() { return (getParent() instanceof ConfigurableApplicationContext) ? - ((ConfigurableApplicationContext) getParent()).getBeanFactory() : (BeanFactory) getParent(); + ((ConfigurableApplicationContext) getParent()).getBeanFactory() : getParent(); } @@ -1025,27 +1014,23 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader //--------------------------------------------------------------------- public void start() { - Map lifecycleBeans = getLifecycleBeans(); - for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { - String beanName = (String) it.next(); + Map lifecycleBeans = getLifecycleBeans(); + for (String beanName : new LinkedHashSet(lifecycleBeans.keySet())) { doStart(lifecycleBeans, beanName); } publishEvent(new ContextStartedEvent(this)); } public void stop() { - Map lifecycleBeans = getLifecycleBeans(); - for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { - String beanName = (String) it.next(); + Map lifecycleBeans = getLifecycleBeans(); + for (String beanName : new LinkedHashSet(lifecycleBeans.keySet())) { doStop(lifecycleBeans, beanName); } publishEvent(new ContextStoppedEvent(this)); } public boolean isRunning() { - Iterator it = getLifecycleBeans().values().iterator(); - while (it.hasNext()) { - Lifecycle lifecycle = (Lifecycle) it.next(); + for (Lifecycle lifecycle : getLifecycleBeans().values()) { if (!lifecycle.isRunning()) { return false; } @@ -1058,14 +1043,14 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader * Lifecycle interface in this context. * @return Map of Lifecycle beans with bean name as key */ - private Map getLifecycleBeans() { + private Map getLifecycleBeans() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); String[] beanNames = beanFactory.getSingletonNames(); - Map beans = new LinkedHashMap(); - for (int i = 0; i < beanNames.length; i++) { - Object bean = beanFactory.getSingleton(beanNames[i]); + Map beans = new LinkedHashMap(); + for (String beanName : beanNames) { + Object bean = beanFactory.getSingleton(beanName); if (bean instanceof Lifecycle) { - beans.put(beanNames[i], bean); + beans.put(beanName, (Lifecycle) bean); } } return beans; @@ -1081,8 +1066,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName); if (bean != null) { String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName); - for (int i = 0; i < dependenciesForBean.length; i++) { - doStart(lifecycleBeans, dependenciesForBean[i]); + for (String dependency : dependenciesForBean) { + doStart(lifecycleBeans, dependency); } if (!bean.isRunning()) { bean.start(); @@ -1101,8 +1086,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName); if (bean != null) { String[] dependentBeans = getBeanFactory().getDependentBeans(beanName); - for (int i = 0; i < dependentBeans.length; i++) { - doStop(lifecycleBeans, dependentBeans[i]); + for (String dependentBean : dependentBeans) { + doStop(lifecycleBeans, dependentBean); } if (bean.isRunning()) { bean.stop(); @@ -1156,7 +1141,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader */ @Override public String toString() { - StringBuffer sb = new StringBuffer(getId()); + StringBuilder sb = new StringBuilder(getId()); sb.append(": display name [").append(getDisplayName()); sb.append("]; startup date [").append(new Date(getStartupDate())); sb.append("]; "); diff --git a/org.springframework.context/src/main/java/org/springframework/context/support/DefaultMessageSourceResolvable.java b/org.springframework.context/src/main/java/org/springframework/context/support/DefaultMessageSourceResolvable.java index 2dc72efe395..dab86704430 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/support/DefaultMessageSourceResolvable.java +++ b/org.springframework.context/src/main/java/org/springframework/context/support/DefaultMessageSourceResolvable.java @@ -121,11 +121,11 @@ public class DefaultMessageSourceResolvable implements MessageSourceResolvable, * including codes, arguments, and default message. */ protected final String resolvableToString() { - StringBuffer buf = new StringBuffer(); - buf.append("codes [").append(StringUtils.arrayToDelimitedString(this.codes, ",")); - buf.append("]; arguments [" + StringUtils.arrayToDelimitedString(this.arguments, ",")); - buf.append("]; default message [").append(this.defaultMessage).append(']'); - return buf.toString(); + StringBuilder result = new StringBuilder(); + result.append("codes [").append(StringUtils.arrayToDelimitedString(this.codes, ",")); + result.append("]; arguments [" + StringUtils.arrayToDelimitedString(this.arguments, ",")); + result.append("]; default message [").append(this.defaultMessage).append(']'); + return result.toString(); } /** 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 9c6c72c9a05..9258ae646a8 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 @@ -405,7 +405,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); - StringBuffer temp = new StringBuffer(basename); + StringBuilder temp = new StringBuilder(basename); if (language.length() > 0) { temp.append('_').append(language); diff --git a/org.springframework.context/src/main/java/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.java b/org.springframework.context/src/main/java/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.java index aebfb201254..3ba61e45ee9 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.java +++ b/org.springframework.context/src/main/java/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.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,12 +64,23 @@ public class LoadTimeWeaverAwareProcessor implements BeanPostProcessor, BeanFact * LoadTimeWeaver will be auto-retrieved from the containing * {@link BeanFactory}, expecting a bean named * {@link ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME "loadTimeWeaver"}. - * @param loadTimeWeaver the specific LoadTimeWeaver that is to be used; can be null + * @param loadTimeWeaver the specific LoadTimeWeaver that is to be used */ public LoadTimeWeaverAwareProcessor(LoadTimeWeaver loadTimeWeaver) { this.loadTimeWeaver = loadTimeWeaver; } + /** + * Create a new LoadTimeWeaverAwareProcessor. + *

The LoadTimeWeaver will be auto-retrieved from + * the given {@link BeanFactory}, expecting a bean named + * {@link ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME "loadTimeWeaver"}. + * @param loadTimeWeaver the specific LoadTimeWeaver that is to be used + */ + public LoadTimeWeaverAwareProcessor(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; @@ -82,7 +93,7 @@ public class LoadTimeWeaverAwareProcessor implements BeanPostProcessor, BeanFact if (ltw == null) { Assert.state(this.beanFactory != null, "BeanFactory required if no LoadTimeWeaver explicitly specified"); - ltw = (LoadTimeWeaver) this.beanFactory.getBean( + ltw = this.beanFactory.getBean( ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, LoadTimeWeaver.class); } ((LoadTimeWeaverAware) bean).setLoadTimeWeaver(ltw); diff --git a/org.springframework.context/src/main/java/org/springframework/instrument/classloading/ShadowingClassLoader.java b/org.springframework.context/src/main/java/org/springframework/instrument/classloading/ShadowingClassLoader.java index 76e63b423e5..2a987628a51 100644 --- a/org.springframework.context/src/main/java/org/springframework/instrument/classloading/ShadowingClassLoader.java +++ b/org.springframework.context/src/main/java/org/springframework/instrument/classloading/ShadowingClassLoader.java @@ -66,8 +66,8 @@ public class ShadowingClassLoader extends DecoratingClassLoader { public ShadowingClassLoader(ClassLoader enclosingClassLoader) { Assert.notNull(enclosingClassLoader, "Enclosing ClassLoader must not be null"); this.enclosingClassLoader = enclosingClassLoader; - for (int i = 0; i < DEFAULT_EXCLUDED_PACKAGES.length; i++) { - excludePackage(DEFAULT_EXCLUDED_PACKAGES[i]); + for (String excludedPackage : DEFAULT_EXCLUDED_PACKAGES) { + excludePackage(excludedPackage); } } @@ -113,8 +113,8 @@ public class ShadowingClassLoader extends DecoratingClassLoader { * @return whether the specified class should be shadowed */ private boolean shouldShadow(String className) { - return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader") - && isEligibleForShadowing(className) && !isClassNameExcludedFromShadowing(className)); + return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader") && + isEligibleForShadowing(className)); } /** @@ -128,18 +128,6 @@ public class ShadowingClassLoader extends DecoratingClassLoader { return !isExcluded(className); } - /** - * Subclasses can override this method to specify whether or not a - * particular class should be excluded from shadowing. - * @param className the class name to test - * @return whether the specified class is excluded - * @deprecated in favor of {@link #isEligibleForShadowing} - */ - @Deprecated - protected boolean isClassNameExcludedFromShadowing(String className) { - return false; - } - private Class doLoadClass(String name) throws ClassNotFoundException { String internalName = StringUtils.replace(name, ".", "/") + ".class"; diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/access/ConnectorDelegate.java b/org.springframework.context/src/main/java/org/springframework/jmx/access/ConnectorDelegate.java index 1d2a66d30ac..f4df31dcbc7 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/access/ConnectorDelegate.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/access/ConnectorDelegate.java @@ -50,7 +50,7 @@ class ConnectorDelegate { * @param environment the JMX environment for the connector (may be null) * @param agentId the local JMX MBeanServer's agent id (may be null) */ - public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map environment, String agentId) + public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map environment, String agentId) throws MBeanServerNotFoundException { if (serviceUrl != null) { diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java b/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java index fb5239408e2..101419d233d 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanClientInterceptor.java @@ -23,7 +23,6 @@ import java.net.MalformedURLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; - import javax.management.Attribute; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; @@ -73,9 +72,6 @@ import org.springframework.util.ReflectionUtils; * {@link #setConnectOnStartup(boolean) connectOnStartup} property to "false", * you can defer this process until the first invocation against the proxy. * - *

Requires JMX 1.2's MBeanServerConnection feature. - * As a consequence, this class will not work on JMX 1.0. - * *

This functionality is usually used through {@link MBeanProxyFactoryBean}. * See the javadoc of that class for more information. * @@ -95,7 +91,7 @@ public class MBeanClientInterceptor private JMXServiceURL serviceUrl; - private Map environment; + private Map environment; private String agentId; @@ -117,11 +113,11 @@ public class MBeanClientInterceptor private MBeanServerInvocationHandler invocationHandler; - private Map allowedAttributes; + private Map allowedAttributes; - private Map allowedOperations; + private Map allowedOperations; - private final Map signatureCache = new HashMap(); + private final Map signatureCache = new HashMap(); private final Object preparationMonitor = new Object(); @@ -145,7 +141,7 @@ public class MBeanClientInterceptor * Specify the environment for the JMX connector. * @see javax.management.remote.JMXConnectorFactory#connect(javax.management.remote.JMXServiceURL, java.util.Map) */ - public void setEnvironment(Map environment) { + public void setEnvironment(Map environment) { this.environment = environment; } @@ -156,7 +152,7 @@ public class MBeanClientInterceptor * "environment[myKey]". This is particularly useful for * adding or overriding entries in child bean definitions. */ - public Map getEnvironment() { + public Map getEnvironment() { return this.environment; } @@ -288,17 +284,16 @@ public class MBeanClientInterceptor MBeanInfo info = this.serverToUse.getMBeanInfo(this.objectName); MBeanAttributeInfo[] attributeInfo = info.getAttributes(); - this.allowedAttributes = new HashMap(attributeInfo.length); - for (int x = 0; x < attributeInfo.length; x++) { - this.allowedAttributes.put(attributeInfo[x].getName(), attributeInfo[x]); + this.allowedAttributes = new HashMap(attributeInfo.length); + for (MBeanAttributeInfo infoEle : attributeInfo) { + this.allowedAttributes.put(infoEle.getName(), infoEle); } MBeanOperationInfo[] operationInfo = info.getOperations(); - this.allowedOperations = new HashMap(operationInfo.length); - for (int x = 0; x < operationInfo.length; x++) { - MBeanOperationInfo opInfo = operationInfo[x]; - Class[] paramTypes = JmxUtils.parameterInfoToTypes(opInfo.getSignature(), this.beanClassLoader); - this.allowedOperations.put(new MethodCacheKey(opInfo.getName(), paramTypes), opInfo); + this.allowedOperations = new HashMap(operationInfo.length); + for (MBeanOperationInfo infoEle : operationInfo) { + Class[] paramTypes = JmxUtils.parameterInfoToTypes(infoEle.getSignature(), this.beanClassLoader); + this.allowedOperations.put(new MethodCacheKey(infoEle.getName(), paramTypes), infoEle); } } catch (ClassNotFoundException ex) { @@ -467,7 +462,7 @@ public class MBeanClientInterceptor throws JMException, IOException { String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing); - MBeanAttributeInfo inf = (MBeanAttributeInfo) this.allowedAttributes.get(attributeName); + MBeanAttributeInfo inf = this.allowedAttributes.get(attributeName); // If no attribute is returned, we know that it is not defined in the // management interface. if (inf == null) { @@ -506,14 +501,14 @@ public class MBeanClientInterceptor */ private Object invokeOperation(Method method, Object[] args) throws JMException, IOException { MethodCacheKey key = new MethodCacheKey(method.getName(), method.getParameterTypes()); - MBeanOperationInfo info = (MBeanOperationInfo) this.allowedOperations.get(key); + MBeanOperationInfo info = this.allowedOperations.get(key); if (info == null) { throw new InvalidInvocationException("Operation '" + method.getName() + "' is not exposed on the management interface"); } String[] signature = null; synchronized (this.signatureCache) { - signature = (String[]) this.signatureCache.get(method); + signature = this.signatureCache.get(method); if (signature == null) { signature = JmxUtils.getMethodSignature(method); this.signatureCache.put(method, signature); diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanProxyFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanProxyFactoryBean.java index 206f3f11fa3..ad3e99f88e5 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanProxyFactoryBean.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/access/MBeanProxyFactoryBean.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,9 +39,6 @@ import org.springframework.util.ClassUtils; * interface that does not correspond to the management interface will lead * to an InvalidInvocationException. * - *

Requires JMX 1.2's MBeanServerConnection feature. - * As a consequence, this class will not work on JMX 1.0. - * * @author Rob Harrop * @author Juergen Hoeller * @since 1.2 diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/access/NotificationListenerRegistrar.java b/org.springframework.context/src/main/java/org/springframework/jmx/access/NotificationListenerRegistrar.java index ae7fbcf2e9f..9feb174f108 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/access/NotificationListenerRegistrar.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/access/NotificationListenerRegistrar.java @@ -40,9 +40,6 @@ import org.springframework.util.CollectionUtils; * with one or more MBeans in an {@link javax.management.MBeanServer} * (typically via a {@link javax.management.MBeanServerConnection}). * - *

Requires JMX 1.2's MBeanServerConnection feature. - * As a consequence, this class will not work on JMX 1.0. - * * @author Juergen Hoeller * @since 2.5.2 * @see #setServer @@ -59,7 +56,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder private JMXServiceURL serviceUrl; - private Map environment; + private Map environment; private String agentId; @@ -80,7 +77,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder * Specify the environment for the JMX connector. * @see javax.management.remote.JMXConnectorFactory#connect(javax.management.remote.JMXServiceURL, java.util.Map) */ - public void setEnvironment(Map environment) { + public void setEnvironment(Map environment) { this.environment = environment; } @@ -91,7 +88,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder * "environment[myKey]". This is particularly useful for * adding or overriding entries in child bean definitions. */ - public Map getEnvironment() { + public Map getEnvironment() { return this.environment; } @@ -138,9 +135,9 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder if (logger.isDebugEnabled()) { logger.debug("Registering NotificationListener for MBeans " + Arrays.asList(this.actualObjectNames)); } - for (int i = 0; i < this.actualObjectNames.length; i++) { - this.server.addNotificationListener(this.actualObjectNames[i], - getNotificationListener(), getNotificationFilter(), getHandback()); + for (ObjectName actualObjectName : this.actualObjectNames) { + this.server.addNotificationListener( + actualObjectName, getNotificationListener(), getNotificationFilter(), getHandback()); } } catch (IOException ex) { @@ -158,10 +155,10 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder public void destroy() { try { if (this.actualObjectNames != null) { - for (int i = 0; i < this.actualObjectNames.length; i++) { + for (ObjectName actualObjectName : this.actualObjectNames) { try { - this.server.removeNotificationListener(this.actualObjectNames[i], - getNotificationListener(), getNotificationFilter(), getHandback()); + this.server.removeNotificationListener( + actualObjectName, getNotificationListener(), getNotificationFilter(), getHandback()); } catch (Exception ex) { if (logger.isDebugEnabled()) { diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/export/MBeanExporter.java b/org.springframework.context/src/main/java/org/springframework/jmx/export/MBeanExporter.java index b411430bcb4..101b690f748 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/export/MBeanExporter.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/export/MBeanExporter.java @@ -20,12 +20,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; - import javax.management.DynamicMBean; import javax.management.JMException; import javax.management.MBeanException; @@ -86,10 +84,8 @@ import org.springframework.util.ObjectUtils; * allowing application code to be notified of MBean registration and * unregistration events. * - *

This exporter is compatible with JMX 1.0 or higher for its basic - * functionality. However, for adapting AOP proxies where the target - * bean is a native MBean, JMX 1.2 is required. As of Spring 2.5, - * this class also autodetects and exports JDK 1.6 MXBeans. + *

This exporter is compatible with JMX 1.2 on Java 5 and above. + * As of Spring 2.5, it also autodetects and exports Java 6 MXBeans. * * @author Rob Harrop * @author Juergen Hoeller @@ -145,7 +141,7 @@ public class MBeanExporter extends MBeanRegistrationSupport private static final Constants constants = new Constants(MBeanExporter.class); /** The beans to be exposed as JMX managed resources, with JMX names as keys */ - private Map beans; + private Map beans; /** The autodetect mode to use for this MBeanExporter */ private Integer autodetectMode; @@ -160,7 +156,7 @@ public class MBeanExporter extends MBeanRegistrationSupport private boolean exposeManagedResourceClassLoader = true; /** A set of bean names that should be excluded from autodetection */ - private Set excludedBeans; + private Set excludedBeans; /** The MBeanExporterListeners registered with this exporter. */ private MBeanExporterListener[] listeners; @@ -169,7 +165,8 @@ public class MBeanExporter extends MBeanRegistrationSupport private NotificationListenerBean[] notificationListeners; /** Map of actually registered NotificationListeners */ - private final Map registeredNotificationListeners = new LinkedHashMap(); + private final Map registeredNotificationListeners = + new LinkedHashMap(); /** Stores the MBeanInfoAssembler to use for this exporter */ private MBeanInfoAssembler assembler = new SimpleReflectiveMBeanInfoAssembler(); @@ -201,7 +198,7 @@ public class MBeanExporter extends MBeanRegistrationSupport * @see org.springframework.jmx.export.naming.KeyNamingStrategy * @see javax.management.ObjectName#ObjectName(String) */ - public void setBeans(Map beans) { + public void setBeans(Map beans) { this.beans = beans; } @@ -216,7 +213,7 @@ public class MBeanExporter extends MBeanRegistrationSupport * @see #isMBean */ public void setAutodetect(boolean autodetect) { - this.autodetectMode = new Integer(autodetect ? AUTODETECT_ALL : AUTODETECT_NONE); + this.autodetectMode = (autodetect ? AUTODETECT_ALL : AUTODETECT_NONE); } /** @@ -233,7 +230,7 @@ public class MBeanExporter extends MBeanRegistrationSupport if (!constants.getValues(CONSTANT_PREFIX_AUTODETECT).contains(new Integer(autodetectMode))) { throw new IllegalArgumentException("Only values of autodetect constants allowed"); } - this.autodetectMode = new Integer(autodetectMode); + this.autodetectMode = autodetectMode; } /** @@ -302,7 +299,7 @@ public class MBeanExporter extends MBeanRegistrationSupport * Set the list of names for beans that should be excluded from autodetection. */ public void setExcludedBeans(String[] excludedBeans) { - this.excludedBeans = (excludedBeans != null ? new HashSet(Arrays.asList(excludedBeans)) : null); + this.excludedBeans = (excludedBeans != null ? new HashSet(Arrays.asList(excludedBeans)) : null); } /** @@ -354,34 +351,25 @@ public class MBeanExporter extends MBeanRegistrationSupport * advanced options such as registering * {@link javax.management.NotificationFilter NotificationFilters} and * handback objects see {@link #setNotificationListeners(NotificationListenerBean[])}. - * @throws IllegalArgumentException if the supplied listeners {@link Map} is null. */ - public void setNotificationListenerMappings(Map listeners) { + public void setNotificationListenerMappings(Map listeners) { Assert.notNull(listeners, "'listeners' must not be null"); - List notificationListeners = new ArrayList(listeners.size()); - - for (Iterator iterator = listeners.entrySet().iterator(); iterator.hasNext();) { - Map.Entry entry = (Map.Entry) iterator.next(); + List notificationListeners = + new ArrayList(listeners.size()); + for (Map.Entry entry : listeners.entrySet()) { // Get the listener from the map value. - Object value = entry.getValue(); - if (!(value instanceof NotificationListener)) { - throw new IllegalArgumentException( - "Map entry value [" + value + "] is not a NotificationListener"); - } - NotificationListenerBean bean = new NotificationListenerBean((NotificationListener) value); - + NotificationListenerBean bean = new NotificationListenerBean(entry.getValue()); // Get the ObjectName from the map key. Object key = entry.getKey(); if (key != null && !WILDCARD.equals(key)) { // This listener is mapped to a specific ObjectName. bean.setMappedObjectName(entry.getKey()); } - notificationListeners.add(bean); } - this.notificationListeners = (NotificationListenerBean[]) + this.notificationListeners = notificationListeners.toArray(new NotificationListenerBean[notificationListeners.size()]); } @@ -507,15 +495,15 @@ public class MBeanExporter extends MBeanRegistrationSupport protected void registerBeans() { // The beans property may be null, for example if we are relying solely on autodetection. if (this.beans == null) { - this.beans = new HashMap(); + this.beans = new HashMap(); // Use AUTODETECT_ALL as default in no beans specified explicitly. if (this.autodetectMode == null) { - this.autodetectMode = new Integer(AUTODETECT_ALL); + this.autodetectMode = AUTODETECT_ALL; } } // Perform autodetection, if desired. - int mode = (this.autodetectMode != null ? this.autodetectMode.intValue() : AUTODETECT_NONE); + int mode = (this.autodetectMode != null ? this.autodetectMode : AUTODETECT_NONE); if (mode != AUTODETECT_NONE) { if (this.beanFactory == null) { throw new MBeanExportException("Cannot autodetect MBeans if not running in a BeanFactory"); @@ -533,12 +521,8 @@ public class MBeanExporter extends MBeanRegistrationSupport } if (!this.beans.isEmpty()) { - for (Iterator it = this.beans.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - Assert.notNull(entry.getKey(), "Beans key must not be null"); - String beanKey = entry.getKey().toString(); - Object value = entry.getValue(); - registerBeanNameOrInstance(value, beanKey); + for (Map.Entry entry : this.beans.entrySet()) { + registerBeanNameOrInstance(entry.getValue(), entry.getKey()); } } } @@ -607,11 +591,11 @@ public class MBeanExporter extends MBeanRegistrationSupport else { // Plain bean instance -> register it directly. if (this.beanFactory != null) { - Map beansOfSameType = this.beanFactory.getBeansOfType(mapValue.getClass(), false, false); - for (Iterator iterator = beansOfSameType.entrySet().iterator(); iterator.hasNext();) { - Map.Entry entry = (Map.Entry) iterator.next(); + Map beansOfSameType = + this.beanFactory.getBeansOfType(mapValue.getClass(), false, false); + for (Map.Entry entry : beansOfSameType.entrySet()) { if (entry.getValue() == mapValue) { - String beanName = (String) entry.getKey(); + String beanName = entry.getKey(); ObjectName objectName = registerBeanInstance(mapValue, beanKey); replaceNotificationListenerBeanNameKeysIfNecessary(beanName, objectName); return objectName; @@ -636,8 +620,8 @@ public class MBeanExporter extends MBeanRegistrationSupport */ private void replaceNotificationListenerBeanNameKeysIfNecessary(String beanName, ObjectName objectName) { if (this.notificationListeners != null) { - for (int i = 0; i < this.notificationListeners.length; i++) { - this.notificationListeners[i].replaceObjectName(beanName, objectName); + for (NotificationListenerBean notificationListener : this.notificationListeners) { + notificationListener.replaceObjectName(beanName, objectName); } } } @@ -889,15 +873,14 @@ public class MBeanExporter extends MBeanRegistrationSupport */ private void autodetect(AutodetectCallback callback) { String[] beanNames = this.beanFactory.getBeanNamesForType(Object.class, true, this.allowEagerInit); - for (int i = 0; i < beanNames.length; i++) { - String beanName = beanNames[i]; + for (String beanName : beanNames) { if (!isExcluded(beanName)) { Class beanClass = this.beanFactory.getType(beanName); if (beanClass != null && callback.include(beanClass, beanName)) { boolean lazyInit = isBeanDefinitionLazyInit(this.beanFactory, beanName); Object beanInstance = (!lazyInit ? this.beanFactory.getBean(beanName) : null); - if (!this.beans.containsValue(beanName) && - (beanInstance == null || !CollectionUtils.containsInstance(this.beans.values(), beanInstance))) { + if (!this.beans.containsValue(beanName) && (beanInstance == null || + !CollectionUtils.containsInstance(this.beans.values(), beanInstance))) { // Not already registered for JMX exposure. this.beans.put(beanName, (beanInstance != null ? beanInstance : beanName)); if (logger.isInfoEnabled()) { @@ -945,8 +928,7 @@ public class MBeanExporter extends MBeanRegistrationSupport */ private void registerNotificationListeners() throws MBeanExportException { if (this.notificationListeners != null) { - for (int i = 0; i < this.notificationListeners.length; i++) { - NotificationListenerBean bean = this.notificationListeners[i]; + for (NotificationListenerBean bean : this.notificationListeners) { try { ObjectName[] mappedObjectNames = bean.getResolvedObjectNames(); if (mappedObjectNames == null) { @@ -954,9 +936,9 @@ public class MBeanExporter extends MBeanRegistrationSupport mappedObjectNames = getRegisteredObjectNames(); } if (this.registeredNotificationListeners.put(bean, mappedObjectNames) == null) { - for (int j = 0; j < mappedObjectNames.length; j++) { - this.server.addNotificationListener(mappedObjectNames[j], - bean.getNotificationListener(), bean.getNotificationFilter(), bean.getHandback()); + for (ObjectName mappedObjectName : mappedObjectNames) { + this.server.addNotificationListener(mappedObjectName, bean.getNotificationListener(), + bean.getNotificationFilter(), bean.getHandback()); } } } @@ -972,14 +954,13 @@ public class MBeanExporter extends MBeanRegistrationSupport * from the {@link MBeanServer}. */ private void unregisterNotificationListeners() { - for (Iterator it = this.registeredNotificationListeners.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - NotificationListenerBean bean = (NotificationListenerBean) entry.getKey(); - ObjectName[] mappedObjectNames = (ObjectName[]) entry.getValue(); - for (int j = 0; j < mappedObjectNames.length; j++) { + for (Map.Entry entry : this.registeredNotificationListeners.entrySet()) { + NotificationListenerBean bean = entry.getKey(); + ObjectName[] mappedObjectNames = entry.getValue(); + for (ObjectName mappedObjectName : mappedObjectNames) { try { - this.server.removeNotificationListener(mappedObjectNames[j], - bean.getNotificationListener(), bean.getNotificationFilter(), bean.getHandback()); + this.server.removeNotificationListener(mappedObjectName, bean.getNotificationListener(), + bean.getNotificationFilter(), bean.getHandback()); } catch (Exception ex) { if (logger.isDebugEnabled()) { @@ -1028,8 +1009,8 @@ public class MBeanExporter extends MBeanRegistrationSupport */ private void notifyListenersOfRegistration(ObjectName objectName) { if (this.listeners != null) { - for (int i = 0; i < this.listeners.length; i++) { - this.listeners[i].mbeanRegistered(objectName); + for (MBeanExporterListener listener : this.listeners) { + listener.mbeanRegistered(objectName); } } } @@ -1040,8 +1021,8 @@ public class MBeanExporter extends MBeanRegistrationSupport */ private void notifyListenersOfUnregistration(ObjectName objectName) { if (this.listeners != null) { - for (int i = 0; i < this.listeners.length; i++) { - this.listeners[i].mbeanUnregistered(objectName); + for (MBeanExporterListener listener : this.listeners) { + listener.mbeanUnregistered(objectName); } } } diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java index 8d1b3b710bd..114e00a893f 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.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,7 +20,6 @@ import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; - import javax.management.Descriptor; import javax.management.JMException; import javax.management.MBeanOperationInfo; @@ -31,7 +30,6 @@ import javax.management.modelmbean.ModelMBeanOperationInfo; import org.springframework.aop.framework.AopProxyUtils; import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeanUtils; -import org.springframework.core.JdkVersion; import org.springframework.jmx.support.JmxUtils; /** @@ -252,10 +250,10 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean @Override protected ModelMBeanAttributeInfo[] getAttributeInfo(Object managedBean, String beanKey) throws JMException { PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(getClassToExpose(managedBean)); - List infos = new ArrayList(); + List infos = new ArrayList(); - for (int i = 0; i < props.length; i++) { - Method getter = props[i].getReadMethod(); + for (PropertyDescriptor prop : props) { + Method getter = prop.getReadMethod(); if (getter != null && getter.getDeclaringClass() == Object.class) { continue; } @@ -263,15 +261,15 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean getter = null; } - Method setter = props[i].getWriteMethod(); + Method setter = prop.getWriteMethod(); if (setter != null && !includeWriteAttribute(setter, beanKey)) { setter = null; } if (getter != null || setter != null) { // If both getter and setter are null, then this does not need exposing. - String attrName = JmxUtils.getAttributeName(props[i], isUseStrictCasing()); - String description = getAttributeDescription(props[i], beanKey); + String attrName = JmxUtils.getAttributeName(prop, isUseStrictCasing()); + String description = getAttributeDescription(prop, beanKey); ModelMBeanAttributeInfo info = new ModelMBeanAttributeInfo(attrName, description, getter, setter); Descriptor desc = info.getDescriptor(); @@ -288,7 +286,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean } } - return (ModelMBeanAttributeInfo[]) infos.toArray(new ModelMBeanAttributeInfo[infos.size()]); + return infos.toArray(new ModelMBeanAttributeInfo[infos.size()]); } /** @@ -306,11 +304,10 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean @Override protected ModelMBeanOperationInfo[] getOperationInfo(Object managedBean, String beanKey) { Method[] methods = getClassToExpose(managedBean).getMethods(); - List infos = new ArrayList(); + List infos = new ArrayList(); - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; - if (JdkVersion.isAtLeastJava15() && method.isSynthetic()) { + for (Method method : methods) { + if (method.isSynthetic()) { continue; } if (method.getDeclaringClass().equals(Object.class)) { @@ -355,7 +352,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean } } - return (ModelMBeanOperationInfo[]) infos.toArray(new ModelMBeanOperationInfo[infos.size()]); + return infos.toArray(new ModelMBeanOperationInfo[infos.size()]); } /** diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/support/JmxUtils.java b/org.springframework.context/src/main/java/org/springframework/jmx/support/JmxUtils.java index 75530f2706f..2bc3a663a51 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/support/JmxUtils.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/support/JmxUtils.java @@ -21,7 +21,6 @@ import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.List; - import javax.management.DynamicMBean; import javax.management.MBeanParameterInfo; import javax.management.MBeanServer; @@ -33,7 +32,6 @@ import javax.management.ObjectName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.core.JdkVersion; import org.springframework.jmx.MBeanServerNotFoundException; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -114,7 +112,7 @@ public abstract class JmxUtils { server = (MBeanServer) servers.get(0); } - if (server == null && agentId == null && JdkVersion.isAtLeastJava15()) { + if (server == null && agentId == null) { // Attempt to load the PlatformMBeanServer. try { server = ManagementFactory.getPlatformMBeanServer(); @@ -221,7 +219,7 @@ public abstract class JmxUtils { public static ObjectName appendIdentityToObjectName(ObjectName objectName, Object managedResource) throws MalformedObjectNameException { - Hashtable keyProperties = objectName.getKeyPropertyList(); + Hashtable keyProperties = objectName.getKeyPropertyList(); keyProperties.put(IDENTITY_OBJECT_NAME_KEY, ObjectUtils.getIdentityHexString(managedResource)); return ObjectNameManager.getInstance(objectName.getDomain(), keyProperties); } @@ -282,8 +280,7 @@ public abstract class JmxUtils { } String mbeanInterfaceName = clazz.getName() + MBEAN_SUFFIX; Class[] implementedInterfaces = clazz.getInterfaces(); - for (int x = 0; x < implementedInterfaces.length; x++) { - Class iface = implementedInterfaces[x]; + for (Class iface : implementedInterfaces) { if (iface.getName().equals(mbeanInterfaceName)) { return iface; } @@ -303,13 +300,12 @@ public abstract class JmxUtils { return null; } Class[] implementedInterfaces = clazz.getInterfaces(); - for (int x = 0; x < implementedInterfaces.length; x++) { - Class iface = implementedInterfaces[x]; + for (Class iface : implementedInterfaces) { boolean isMxBean = iface.getName().endsWith(MXBEAN_SUFFIX); if (mxBeanAnnotationAvailable) { Boolean checkResult = MXBeanChecker.hasMXBeanAnnotation(iface); if (checkResult != null) { - isMxBean = checkResult.booleanValue(); + isMxBean = checkResult; } } if (isMxBean) { @@ -325,14 +321,9 @@ public abstract class JmxUtils { */ private static class MXBeanChecker { - public static Boolean hasMXBeanAnnotation(Class iface) { - MXBean mxBean = (MXBean) iface.getAnnotation(MXBean.class); - if (mxBean != null) { - return Boolean.valueOf(mxBean.value()); - } - else { - return null; - } + public static Boolean hasMXBeanAnnotation(Class iface) { + MXBean mxBean = iface.getAnnotation(MXBean.class); + return (mxBean != null ? mxBean.value() : null); } } diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/support/ObjectNameManager.java b/org.springframework.context/src/main/java/org/springframework/jmx/support/ObjectNameManager.java index cd149f60355..16a339f4d02 100644 --- a/org.springframework.context/src/main/java/org/springframework/jmx/support/ObjectNameManager.java +++ b/org.springframework.context/src/main/java/org/springframework/jmx/support/ObjectNameManager.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,18 +17,12 @@ package org.springframework.jmx.support; import java.util.Hashtable; - import javax.management.MalformedObjectNameException; import javax.management.ObjectName; -import org.springframework.util.ClassUtils; - /** * Helper class for the creation of {@link javax.management.ObjectName} instances. * - *

ObjectName instances will be cached on JMX 1.2, - * whereas they will be recreated for each request on JMX 1.0. - * * @author Rob Harrop * @author Juergen Hoeller * @since 1.2 @@ -36,11 +30,6 @@ import org.springframework.util.ClassUtils; */ public class ObjectNameManager { - // Determine whether the JMX 1.2 ObjectName.getInstance method is available. - private static final boolean getInstanceAvailable = - ClassUtils.hasMethod(ObjectName.class, "getInstance", new Class[] {String.class}); - - /** * Retrieve the ObjectName instance corresponding to the supplied name. * @param objectName the ObjectName in ObjectName or @@ -70,12 +59,7 @@ public class ObjectNameManager { * @see ObjectName#getInstance(String) */ public static ObjectName getInstance(String objectName) throws MalformedObjectNameException { - if (getInstanceAvailable) { - return ObjectName.getInstance(objectName); - } - else { - return new ObjectName(objectName); - } + return ObjectName.getInstance(objectName); } /** @@ -92,12 +76,7 @@ public class ObjectNameManager { public static ObjectName getInstance(String domainName, String key, String value) throws MalformedObjectNameException { - if (getInstanceAvailable) { - return ObjectName.getInstance(domainName, key, value); - } - else { - return new ObjectName(domainName, key, value); - } + return ObjectName.getInstance(domainName, key, value); } /** @@ -110,15 +89,10 @@ public class ObjectNameManager { * @see ObjectName#ObjectName(String, java.util.Hashtable) * @see ObjectName#getInstance(String, java.util.Hashtable) */ - public static ObjectName getInstance(String domainName, Hashtable properties) + public static ObjectName getInstance(String domainName, Hashtable properties) throws MalformedObjectNameException { - if (getInstanceAvailable) { - return ObjectName.getInstance(domainName, properties); - } - else { - return new ObjectName(domainName, properties); - } + return ObjectName.getInstance(domainName, properties); } } diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/support/WebLogicJndiMBeanServerFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/jmx/support/WebLogicJndiMBeanServerFactoryBean.java deleted file mode 100644 index 56833fc3ec3..00000000000 --- a/org.springframework.context/src/main/java/org/springframework/jmx/support/WebLogicJndiMBeanServerFactoryBean.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2002-2007 the original author 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.jmx.support; - -import java.lang.reflect.InvocationTargetException; - -import javax.management.MBeanServer; -import javax.naming.NamingException; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.jmx.MBeanServerNotFoundException; -import org.springframework.jndi.JndiLocatorSupport; - -/** - * FactoryBean that obtains a specified WebLogic {@link javax.management.MBeanServer} - * reference through a WebLogic MBeanHome obtained via a JNDI lookup. - * By default, the server's local MBeanHome will be obtained. - * - *

Exposes the MBeanServer for bean references. - * This FactoryBean is a direct alternative to {@link MBeanServerFactoryBean}, - * which uses standard JMX 1.2 API to access the platform's MBeanServer. - * - *

Note: There is also a more general {@link WebLogicMBeanServerFactoryBean} - * for accessing any specified WebLogic MBeanServer, - * potentially a remote one. - * - *

NOTE: This class is only intended for use with WebLogic 8.1. - * On WebLogic 9.x, simply obtain the MBeanServer directly from the JNDI location - * "java:comp/env/jmx/runtime", for example through the following configuration: - * - *

- * <bean class="org.springframework.jndi.JndiObjectFactoryBean">
- *   <property name="jndiName" value="java:comp/env/jmx/runtime"/>
- * </bean>
- * - * @author Rob Harrop - * @author Juergen Hoeller - * @since 1.2.6 - * @see weblogic.management.MBeanHome#LOCAL_JNDI_NAME - * @see weblogic.management.MBeanHome#getMBeanServer() - * @see javax.management.MBeanServer - * @see MBeanServerFactoryBean - * @see WebLogicMBeanServerFactoryBean - */ -public class WebLogicJndiMBeanServerFactoryBean extends JndiLocatorSupport - implements FactoryBean, InitializingBean { - - private static final String WEBLOGIC_MBEAN_HOME_CLASS = "weblogic.management.MBeanHome"; - - private static final String LOCAL_JNDI_NAME_FIELD = "LOCAL_JNDI_NAME"; - - private static final String GET_MBEAN_SERVER_METHOD = "getMBeanServer"; - - - private String mbeanHomeName; - - private MBeanServer mbeanServer; - - - /** - * Specify the JNDI name of the WebLogic MBeanHome object to use - * for creating the JMX MBeanServer reference. - *

Default is MBeanHome.LOCAL_JNDI_NAME - * @see weblogic.management.MBeanHome#LOCAL_JNDI_NAME - */ - public void setMbeanHomeName(String mbeanHomeName) { - this.mbeanHomeName = mbeanHomeName; - } - - - public void afterPropertiesSet() throws MBeanServerNotFoundException { - try { - String jndiName = this.mbeanHomeName; - if (jndiName == null) { - /* - * jndiName = MBeanHome.LOCAL_JNDI_NAME; - */ - Class mbeanHomeClass = getClass().getClassLoader().loadClass(WEBLOGIC_MBEAN_HOME_CLASS); - jndiName = (String) mbeanHomeClass.getField(LOCAL_JNDI_NAME_FIELD).get(null); - } - Object mbeanHome = lookup(jndiName); - - /* - * this.mbeanServer = mbeanHome.getMBeanServer(); - */ - this.mbeanServer = (MBeanServer) - mbeanHome.getClass().getMethod(GET_MBEAN_SERVER_METHOD, null).invoke(mbeanHome, null); - } - catch (NamingException ex) { - throw new MBeanServerNotFoundException("Could not find WebLogic's MBeanHome object in JNDI", ex); - } - catch (ClassNotFoundException ex) { - throw new MBeanServerNotFoundException("Could not find WebLogic's MBeanHome class", ex); - } - catch (InvocationTargetException ex) { - throw new MBeanServerNotFoundException( - "WebLogic's MBeanHome.getMBeanServer method failed", ex.getTargetException()); - } - catch (Exception ex) { - throw new MBeanServerNotFoundException( - "Could not access WebLogic's MBeanHome/getMBeanServer method", ex); - } - } - - - public Object getObject() { - return this.mbeanServer; - } - - public Class getObjectType() { - return (this.mbeanServer != null ? this.mbeanServer.getClass() : MBeanServer.class); - } - - public boolean isSingleton() { - return true; - } - -} diff --git a/org.springframework.context/src/main/java/org/springframework/jmx/support/WebLogicMBeanServerFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/jmx/support/WebLogicMBeanServerFactoryBean.java deleted file mode 100644 index f610456130c..00000000000 --- a/org.springframework.context/src/main/java/org/springframework/jmx/support/WebLogicMBeanServerFactoryBean.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2002-2007 the original author 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.jmx.support; - -import java.lang.reflect.InvocationTargetException; - -import javax.management.MBeanServer; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.jmx.MBeanServerNotFoundException; - -/** - * FactoryBean that obtains a specified WebLogic {@link javax.management.MBeanServer} - * reference through WebLogic's proprietary Helper / - * MBeanHome API, which is available on WebLogic 6.1 and higher. - * - *

Exposes the MBeanServer for bean references. - * This FactoryBean is a direct alternative to {@link MBeanServerFactoryBean}, - * which uses standard JMX 1.2 API to access the platform's MBeanServer. - * - *

Note: There is also a {@link WebLogicJndiMBeanServerFactoryBean} for - * accessing the WebLogic MBeanServer instance through a WebLogic - * MBeanHome obtained via a JNDI lookup, typical a local one. - * - *

NOTE: This class is only intended for use with WebLogic up to 8.1. - * On WebLogic 9.x, simply obtain the MBeanServer directly from the JNDI location - * "java:comp/env/jmx/runtime", for example through the following configuration: - * - *

- * <bean class="org.springframework.jndi.JndiObjectFactoryBean">
- *   <property name="jndiName" value="java:comp/env/jmx/runtime"/>
- * </bean>
- * - * @author Rob Harrop - * @author Juergen Hoeller - * @since 1.2 - * @see weblogic.management.Helper#getMBeanHome(String, String, String, String) - * @see weblogic.management.MBeanHome#getMBeanServer() - * @see javax.management.MBeanServer - * @see MBeanServerFactoryBean - * @see WebLogicJndiMBeanServerFactoryBean - */ -public class WebLogicMBeanServerFactoryBean implements FactoryBean, InitializingBean { - - private static final String WEBLOGIC_JMX_HELPER_CLASS = "weblogic.management.Helper"; - - private static final String GET_MBEAN_HOME_METHOD = "getMBeanHome"; - - private static final String GET_MBEAN_SERVER_METHOD = "getMBeanServer"; - - - private String username = "weblogic"; - - private String password = "weblogic"; - - private String serverUrl = "t3://localhost:7001"; - - private String serverName = "server"; - - private MBeanServer mbeanServer; - - - /** - * Set the username to use for retrieving the WebLogic MBeanServer. - * Default is "weblogic". - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * Set the password to use for retrieving the WebLogic MBeanServer. - * Default is "weblogic". - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * Set the server URL to use for retrieving the WebLogic MBeanServer. - * Default is "t3://localhost:7001". - */ - public void setServerUrl(String serverUrl) { - this.serverUrl = serverUrl; - } - - /** - * Set the server name to use for retrieving the WebLogic MBeanServer. - * Default is "server". - */ - public void setServerName(String serverName) { - this.serverName = serverName; - } - - - public void afterPropertiesSet() throws MBeanServerNotFoundException { - try { - /* - * MBeanHome mbeanHome = Helper.getMBeanHome(this.username, this.password, this.serverUrl, this.serverName); - */ - Class helperClass = getClass().getClassLoader().loadClass(WEBLOGIC_JMX_HELPER_CLASS); - Class[] argTypes = new Class[] {String.class, String.class, String.class, String.class}; - Object[] args = new Object[] {this.username, this.password, this.serverUrl, this.serverName}; - Object mbeanHome = helperClass.getMethod(GET_MBEAN_HOME_METHOD, argTypes).invoke(null, args); - - /* - * this.mbeanServer = mbeanHome.getMBeanServer(); - */ - this.mbeanServer = (MBeanServer) - mbeanHome.getClass().getMethod(GET_MBEAN_SERVER_METHOD, null).invoke(mbeanHome, null); - } - catch (ClassNotFoundException ex) { - throw new MBeanServerNotFoundException("Could not find WebLogic's JMX Helper class", ex); - } - catch (InvocationTargetException ex) { - throw new MBeanServerNotFoundException( - "WebLogic's JMX Helper.getMBeanHome/getMBeanServer method failed", ex.getTargetException()); - } - catch (Exception ex) { - throw new MBeanServerNotFoundException( - "Could not access WebLogic's JMX Helper.getMBeanHome/getMBeanServer method", ex); - } - } - - - public Object getObject() { - return this.mbeanServer; - } - - public Class getObjectType() { - return (this.mbeanServer != null ? this.mbeanServer.getClass() : MBeanServer.class); - } - - public boolean isSingleton() { - return true; - } - -} diff --git a/org.springframework.context/src/main/java/org/springframework/scheduling/timer/TimerFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/scheduling/timer/TimerFactoryBean.java index 213cf201985..6e73a34ddcc 100644 --- a/org.springframework.context/src/main/java/org/springframework/scheduling/timer/TimerFactoryBean.java +++ b/org.springframework.context/src/main/java/org/springframework/scheduling/timer/TimerFactoryBean.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. @@ -25,7 +25,6 @@ import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; -import org.springframework.core.JdkVersion; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -114,11 +113,7 @@ public class TimerFactoryBean implements FactoryBean, BeanNameAware, Initializin * @see java.util.Timer#Timer(boolean) */ protected Timer createTimer(String name, boolean daemon) { - Timer timer = createTimer(daemon); - if (timer != null) { - return timer; - } - if (StringUtils.hasText(name) && JdkVersion.isAtLeastJava15()) { + if (StringUtils.hasText(name)) { return new Timer(name, daemon); } else { @@ -126,16 +121,6 @@ public class TimerFactoryBean implements FactoryBean, BeanNameAware, Initializin } } - /** - * Create a new Timer instance. Called by afterPropertiesSet. - * Can be overridden in subclasses to provide custom Timer subclasses. - * @deprecated as of Spring 2.0.1, in favor of {@link #createTimer(String, boolean)} - */ - @Deprecated - protected Timer createTimer(boolean daemon) { - return null; - } - /** * Register the specified {@link ScheduledTimerTask ScheduledTimerTasks} * on the given {@link Timer}. @@ -143,8 +128,7 @@ public class TimerFactoryBean implements FactoryBean, BeanNameAware, Initializin * @param timer the Timer to register the tasks on. */ protected void registerTasks(ScheduledTimerTask[] tasks, Timer timer) { - for (int i = 0; i < tasks.length; i++) { - ScheduledTimerTask task = tasks[i]; + for (ScheduledTimerTask task : tasks) { if (task.isOneTimeTask()) { timer.schedule(task.getTimerTask(), task.getDelay()); } diff --git a/org.springframework.context/src/main/java/org/springframework/ui/ExtendedModelMap.java b/org.springframework.context/src/main/java/org/springframework/ui/ExtendedModelMap.java index dadb9bc5226..dc43645bc1d 100644 --- a/org.springframework.context/src/main/java/org/springframework/ui/ExtendedModelMap.java +++ b/org.springframework.context/src/main/java/org/springframework/ui/ExtendedModelMap.java @@ -59,8 +59,8 @@ public class ExtendedModelMap extends ModelMap implements Model { return this; } - @SuppressWarnings("unchecked") public Map asMap() { return this; } + } diff --git a/org.springframework.context/src/main/java/org/springframework/ui/ModelMap.java b/org.springframework.context/src/main/java/org/springframework/ui/ModelMap.java index 665dc56fb2f..b1e4919ea57 100644 --- a/org.springframework.context/src/main/java/org/springframework/ui/ModelMap.java +++ b/org.springframework.context/src/main/java/org/springframework/ui/ModelMap.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.util.Assert; * @see org.springframework.web.servlet.ModelAndView * @see org.springframework.web.portlet.ModelAndView */ -public class ModelMap extends LinkedHashMap { +public class ModelMap extends LinkedHashMap { /** * Construct a new, empty ModelMap. @@ -127,8 +127,7 @@ public class ModelMap extends LinkedHashMap { */ public ModelMap mergeAttributes(Map attributes) { if (attributes != null) { - for (Iterator it = attributes.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + for (String key : attributes.keySet()) { if (!containsKey(key)) { put(key, attributes.get(key)); } diff --git a/org.springframework.context/src/main/java/org/springframework/validation/AbstractErrors.java b/org.springframework.context/src/main/java/org/springframework/validation/AbstractErrors.java index f2ea296b948..0fdd75a4309 100644 --- a/org.springframework.context/src/main/java/org/springframework/validation/AbstractErrors.java +++ b/org.springframework.context/src/main/java/org/springframework/validation/AbstractErrors.java @@ -212,7 +212,7 @@ public abstract class AbstractErrors implements Errors, Serializable { @Override public String toString() { - StringBuffer sb = new StringBuffer(getClass().getName()); + StringBuilder sb = new StringBuilder(getClass().getName()); sb.append(": ").append(getErrorCount()).append(" errors"); Iterator it = getAllErrors().iterator(); while (it.hasNext()) { diff --git a/org.springframework.context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java b/org.springframework.context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java index 29b953d6a8c..4f6e20e318b 100644 --- a/org.springframework.context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java +++ b/org.springframework.context/src/main/java/org/springframework/validation/support/BindingAwareModelMap.java @@ -17,7 +17,6 @@ package org.springframework.validation.support; import java.util.Map; -import java.util.Set; import org.springframework.ui.ExtendedModelMap; import org.springframework.validation.BindingResult; @@ -32,19 +31,19 @@ import org.springframework.validation.BindingResult; * * @author Juergen Hoeller * @since 2.5.6 - * @see + * @see org.springframework.validation.BindingResult */ public class BindingAwareModelMap extends ExtendedModelMap { @Override - public Object put(Object key, Object value) { + public Object put(String key, Object value) { removeBindingResultIfNecessary(key, value); return super.put(key, value); } @Override - public void putAll(Map map) { - for (Map.Entry entry : (Set) map.entrySet()) { + public void putAll(Map map) { + for (Map.Entry entry : map.entrySet()) { removeBindingResultIfNecessary(entry.getKey(), entry.getValue()); } super.putAll(map); diff --git a/org.springframework.context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java b/org.springframework.context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java new file mode 100644 index 00000000000..38e82eeaa33 --- /dev/null +++ b/org.springframework.context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java @@ -0,0 +1,79 @@ +/* + * 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.context.expression; + +import junit.framework.TestCase; + +import org.springframework.beans.TestBean; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.config.Scope; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.support.GenericApplicationContext; + +/** + * @author Juergen Hoeller + */ +public class ApplicationContextExpressionTests extends TestCase { + + public void testGenericApplicationContext() { + GenericApplicationContext ac = new GenericApplicationContext(); + ac.getBeanFactory().registerScope("myScope", new Scope() { + public Object get(String name, ObjectFactory objectFactory) { + return objectFactory.getObject(); + } + public Object remove(String name) { + return null; + } + public void registerDestructionCallback(String name, Runnable callback) { + } + public Object resolveContextualObject(String key) { + if (key.equals("mySpecialAttr")) { + return "42"; + } + else { + return null; + } + } + public String getConversationId() { + return null; + } + }); + GenericBeanDefinition bd1 = new GenericBeanDefinition(); + bd1.setBeanClass(TestBean.class); + bd1.getPropertyValues().addPropertyValue("name", "myName"); + ac.registerBeanDefinition("tb1", bd1); + GenericBeanDefinition bd2 = new GenericBeanDefinition(); + bd2.setBeanClass(TestBean.class); + bd2.setScope("myScope"); + bd2.getPropertyValues().addPropertyValue("name", "XXX#{tb1.name}YYY#{mySpecialAttr}ZZZ"); + bd2.getPropertyValues().addPropertyValue("age", "#{mySpecialAttr}"); + bd2.getPropertyValues().addPropertyValue("country", "#{systemProperties.country}"); + ac.registerBeanDefinition("tb2", bd2); + System.getProperties().put("country", "UK"); + try { + ac.refresh(); + TestBean tb2 = (TestBean) ac.getBean("tb2"); + assertEquals("XXXmyNameYYY42ZZZ", tb2.getName()); + assertEquals(42, tb2.getAge()); + assertEquals("UK", tb2.getCountry()); + } + finally { + System.getProperties().remove("country"); + } + } + +} diff --git a/org.springframework.context/template.mf b/org.springframework.context/template.mf index 84cd12aeae2..eea9f11080e 100644 --- a/org.springframework.context/template.mf +++ b/org.springframework.context/template.mf @@ -27,6 +27,7 @@ Import-Template: org.springframework.aop.*;version="[3.0.0, 3.0.1)", org.springframework.beans.*;version="[3.0.0, 3.0.1)", org.springframework.core.*;version="[3.0.0, 3.0.1)", + org.springframework.expression.*;version="[3.0.0, 3.0.1)", org.springframework.instrument.*;version="[3.0.0, 3.0.1)";resolution:=optional, org.springframework.metadata.*;version="[3.0.0, 3.0.1)", org.springframework.util.*;version="[3.0.0, 3.0.1)" diff --git a/org.springframework.core/core.iml b/org.springframework.core/core.iml index 025bf332ece..3ef4ae71475 100644 --- a/org.springframework.core/core.iml +++ b/org.springframework.core/core.iml @@ -1,118 +1,118 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.core/src/main/java/org/springframework/core/CollectionFactory.java b/org.springframework.core/src/main/java/org/springframework/core/CollectionFactory.java index 81bf16879ab..201a5bfd3e1 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/CollectionFactory.java +++ b/org.springframework.core/src/main/java/org/springframework/core/CollectionFactory.java @@ -50,10 +50,7 @@ import org.springframework.util.ClassUtils; * *

The goal of this class is to avoid runtime dependencies on JDK 1.5+ and * Commons Collections 3.x, simply using the best collection implementation - * that is available at runtime. As of Spring 2.5, JDK 1.4 is required, - * so former adapter methods for JDK 1.3/1.4 always return the JDK 1.4 - * collections now. The adapter methods are still kept for supporting - * Spring-based applications/frameworks which were built to support JDK 1.3. + * that is available at runtime. * * @author Juergen Hoeller * @author Arjen Poutsma @@ -167,7 +164,7 @@ public abstract class CollectionFactory { /** * Create a concurrent Map if possible: This implementation always * creates a {@link java.util.concurrent.ConcurrentHashMap}, since Spring 3.0 - * required JDK 1.5 anyway. + * requires JDK 1.5 anyway. * @param initialCapacity the initial capacity of the Map * @return the new Map instance * @deprecated as of Spring 3.0, for usage on JDK 1.5 or higher @@ -180,7 +177,7 @@ public abstract class CollectionFactory { /** * Create a concurrent Map with a dedicated {@link ConcurrentMap} interface: * This implementation always creates a {@link java.util.concurrent.ConcurrentHashMap}, - * since Spring 3.0 required JDK 1.5 anyway. + * since Spring 3.0 requires JDK 1.5 anyway. * @param initialCapacity the initial capacity of the Map * @return the new ConcurrentMap instance * @deprecated as of Spring 3.0, for usage on JDK 1.5 or higher diff --git a/org.springframework.core/src/main/java/org/springframework/core/Constants.java b/org.springframework.core/src/main/java/org/springframework/core/Constants.java index e0fb6d1310c..a405a605783 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/Constants.java +++ b/org.springframework.core/src/main/java/org/springframework/core/Constants.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. @@ -329,7 +329,7 @@ public class Constants { * @see #toCodeForProperty */ public String propertyToConstantNamePrefix(String propertyName) { - StringBuffer parsedPrefix = new StringBuffer(); + StringBuilder parsedPrefix = new StringBuilder(); for(int i = 0; i < propertyName.length(); i++) { char c = propertyName.charAt(i); if (Character.isUpperCase(c)) { diff --git a/org.springframework.core/src/main/java/org/springframework/core/ControlFlowFactory.java b/org.springframework.core/src/main/java/org/springframework/core/ControlFlowFactory.java index 9a17275600a..6430ff7fb29 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/ControlFlowFactory.java +++ b/org.springframework.core/src/main/java/org/springframework/core/ControlFlowFactory.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. @@ -105,7 +105,7 @@ public abstract class ControlFlowFactory { @Override public String toString() { - StringBuffer sb = new StringBuffer("Jdk14ControlFlow: "); + StringBuilder sb = new StringBuilder("Jdk14ControlFlow: "); for (int i = 0; i < this.stack.length; i++) { if (i > 0) { sb.append("\n\t@"); diff --git a/org.springframework.core/src/main/java/org/springframework/core/Conventions.java b/org.springframework.core/src/main/java/org/springframework/core/Conventions.java index dde279eaf67..b3eb8c99292 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/Conventions.java +++ b/org.springframework.core/src/main/java/org/springframework/core/Conventions.java @@ -115,11 +115,10 @@ public abstract class Conventions { pluralize = true; } else if (Collection.class.isAssignableFrom(parameter.getParameterType())) { - if (JdkVersion.isAtLeastJava15()) { - valueClass = GenericCollectionTypeResolver.getCollectionParameterType(parameter); - } + valueClass = GenericCollectionTypeResolver.getCollectionParameterType(parameter); if (valueClass == null) { - throw new IllegalArgumentException("Cannot generate variable name for non-typed Collection parameter type"); + throw new IllegalArgumentException( + "Cannot generate variable name for non-typed Collection parameter type"); } pluralize = true; } @@ -182,9 +181,7 @@ public abstract class Conventions { pluralize = true; } else if (Collection.class.isAssignableFrom(resolvedType)) { - if (JdkVersion.isAtLeastJava15()) { - valueClass = GenericCollectionTypeResolver.getCollectionReturnType(method); - } + valueClass = GenericCollectionTypeResolver.getCollectionReturnType(method); if (valueClass == null) { if (!(value instanceof Collection)) { throw new IllegalArgumentException( diff --git a/org.springframework.core/src/main/java/org/springframework/core/JdkVersion.java b/org.springframework.core/src/main/java/org/springframework/core/JdkVersion.java index a8b067625fc..7b8d4ecad75 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/JdkVersion.java +++ b/org.springframework.core/src/main/java/org/springframework/core/JdkVersion.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. @@ -68,12 +68,9 @@ public abstract class JdkVersion { else if (javaVersion.indexOf("1.6.") != -1) { majorJavaVersion = JAVA_16; } - else if (javaVersion.indexOf("1.5.") != -1) { - majorJavaVersion = JAVA_15; - } else { - // else leave 1.4 as default (it's either 1.4 or unknown) - majorJavaVersion = JAVA_14; + // else leave 1.5 as default (it's either 1.5 or unknown) + majorJavaVersion = JAVA_15; } } @@ -105,12 +102,14 @@ public abstract class JdkVersion { /** * Convenience method to determine if the current JVM is at least Java 1.4. * @return true if the current JVM is at least Java 1.4 + * @deprecated as of Spring 3.0 which requires Java 1.5+ * @see #getMajorJavaVersion() * @see #JAVA_14 * @see #JAVA_15 * @see #JAVA_16 * @see #JAVA_17 */ + @Deprecated public static boolean isAtLeastJava14() { return true; } @@ -119,13 +118,15 @@ public abstract class JdkVersion { * Convenience method to determine if the current JVM is at least * Java 1.5 (Java 5). * @return true if the current JVM is at least Java 1.5 + * @deprecated as of Spring 3.0 which requires Java 1.5+ * @see #getMajorJavaVersion() * @see #JAVA_15 * @see #JAVA_16 * @see #JAVA_17 */ + @Deprecated public static boolean isAtLeastJava15() { - return getMajorJavaVersion() >= JAVA_15; + return true; } /** diff --git a/org.springframework.core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java b/org.springframework.core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java index 0305f4c75e4..11f4aeda6ef 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java +++ b/org.springframework.core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java @@ -20,10 +20,12 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; +import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -54,13 +56,13 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD private static Log logger = LogFactory.getLog(LocalVariableTableParameterNameDiscoverer.class); - private final Map parameterNamesCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map parameterNamesCache = new ConcurrentHashMap(); - private final Map classReaderCache = new HashMap(); + private final Map classReaderCache = new HashMap(); public String[] getParameterNames(Method method) { - String[] paramNames = (String[]) this.parameterNamesCache.get(method); + String[] paramNames = this.parameterNamesCache.get(method); if (paramNames == null) { try { paramNames = visitMethod(method).getParameterNames(); @@ -82,7 +84,7 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD } public String[] getParameterNames(Constructor ctor) { - String[] paramNames = (String[]) this.parameterNamesCache.get(ctor); + String[] paramNames = this.parameterNamesCache.get(ctor); if (paramNames == null) { try { paramNames = visitConstructor(ctor).getParameterNames(); 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 7a9ea3beb9d..c3633786853 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 @@ -16,14 +16,13 @@ package org.springframework.core; +import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; /** * Helper class that encapsulates the specification of a method parameter, i.e. @@ -34,10 +33,6 @@ import org.springframework.util.ReflectionUtils; * {@link org.springframework.beans.BeanWrapperImpl} and * {@link org.springframework.beans.factory.support.AbstractBeanFactory}. * - *

Note that this class does not depend on JDK 1.5 API artifacts, in order - * to remain compatible with JDK 1.4. Concrete generic type resolution - * via JDK 1.5 API happens in {@link GenericCollectionTypeResolver} only. - * * @author Juergen Hoeller * @author Rob Harrop * @since 2.0 @@ -45,13 +40,6 @@ import org.springframework.util.ReflectionUtils; */ public class MethodParameter { - private static final Method methodParameterAnnotationsMethod = - ClassUtils.getMethodIfAvailable(Method.class, "getParameterAnnotations", new Class[0]); - - private static final Method constructorParameterAnnotationsMethod = - ClassUtils.getMethodIfAvailable(Constructor.class, "getParameterAnnotations", new Class[0]); - - private Method method; private Constructor constructor; @@ -60,7 +48,7 @@ public class MethodParameter { private Class parameterType; - private Object[] parameterAnnotations; + private Annotation[] parameterAnnotations; private ParameterNameDiscoverer parameterNameDiscoverer; @@ -69,7 +57,7 @@ public class MethodParameter { private int nestingLevel = 1; /** Map from Integer level to Integer type index */ - private Map typeIndexesPerLevel; + private Map typeIndexesPerLevel; Map typeVariableMap; @@ -188,22 +176,13 @@ public class MethodParameter { /** * Return the annotations associated with the method/constructor parameter. - * @return the parameter annotations, or null if there is - * no annotation support (on JDK < 1.5). The return value is an Object array - * instead of an Annotation array simply for compatibility with older JDKs; - * feel free to cast it to Annotation[] on JDK 1.5 or higher. */ - public Object[] getParameterAnnotations() { - if (this.parameterAnnotations != null) { - return this.parameterAnnotations; + public Annotation[] getParameterAnnotations() { + if (this.parameterAnnotations == null) { + Annotation[][] annotationArray = (this.method != null) ? + this.method.getParameterAnnotations() : this.constructor.getParameterAnnotations(); + this.parameterAnnotations = annotationArray[this.parameterIndex]; } - if (methodParameterAnnotationsMethod == null) { - return null; - } - Object[][] annotationArray = (this.method != null ? - ((Object[][]) ReflectionUtils.invokeMethod(methodParameterAnnotationsMethod, this.method)) : - ((Object[][]) ReflectionUtils.invokeMethod(constructorParameterAnnotationsMethod, this.constructor))); - this.parameterAnnotations = annotationArray[this.parameterIndex]; return this.parameterAnnotations; } @@ -250,7 +229,7 @@ public class MethodParameter { * @see #getNestingLevel() */ public void decreaseNestingLevel() { - getTypeIndexesPerLevel().remove(new Integer(this.nestingLevel)); + getTypeIndexesPerLevel().remove(this.nestingLevel); this.nestingLevel--; } @@ -270,7 +249,7 @@ public class MethodParameter { * @see #getNestingLevel() */ public void setTypeIndexForCurrentLevel(int typeIndex) { - getTypeIndexesPerLevel().put(new Integer(this.nestingLevel), new Integer(typeIndex)); + getTypeIndexesPerLevel().put(this.nestingLevel, typeIndex); } /** @@ -290,15 +269,15 @@ public class MethodParameter { * if none specified (indicating the default type index) */ public Integer getTypeIndexForLevel(int nestingLevel) { - return (Integer) getTypeIndexesPerLevel().get(new Integer(nestingLevel)); + return getTypeIndexesPerLevel().get(nestingLevel); } /** * Obtain the (lazily constructed) type-indexes-per-level Map. */ - private Map getTypeIndexesPerLevel() { + private Map getTypeIndexesPerLevel() { if (this.typeIndexesPerLevel == null) { - this.typeIndexesPerLevel = new HashMap(4); + this.typeIndexesPerLevel = new HashMap(4); } return this.typeIndexesPerLevel; } diff --git a/org.springframework.core/src/main/java/org/springframework/core/NestedExceptionUtils.java b/org.springframework.core/src/main/java/org/springframework/core/NestedExceptionUtils.java index ed796acac6b..8b66390f469 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/NestedExceptionUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/core/NestedExceptionUtils.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. @@ -40,12 +40,12 @@ public abstract class NestedExceptionUtils { */ public static String buildMessage(String message, Throwable cause) { if (cause != null) { - StringBuffer buf = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (message != null) { - buf.append(message).append("; "); + sb.append(message).append("; "); } - buf.append("nested exception is ").append(cause); - return buf.toString(); + sb.append("nested exception is ").append(cause); + return sb.toString(); } else { return message; diff --git a/org.springframework.core/src/main/java/org/springframework/core/OrderComparator.java b/org.springframework.core/src/main/java/org/springframework/core/OrderComparator.java index 338d262d0f0..c5266948cd9 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/OrderComparator.java +++ b/org.springframework.core/src/main/java/org/springframework/core/OrderComparator.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 java.util.Comparator; * @see java.util.Collections#sort(java.util.List, java.util.Comparator) * @see java.util.Arrays#sort(Object[], java.util.Comparator) */ -public class OrderComparator implements Comparator { +public class OrderComparator implements Comparator { public int compare(Object o1, Object o2) { boolean p1 = (o1 instanceof PriorityOrdered); diff --git a/org.springframework.core/src/main/java/org/springframework/core/SimpleAliasRegistry.java b/org.springframework.core/src/main/java/org/springframework/core/SimpleAliasRegistry.java index 9abb79e1292..5f3e974ae3e 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/SimpleAliasRegistry.java +++ b/org.springframework.core/src/main/java/org/springframework/core/SimpleAliasRegistry.java @@ -18,9 +18,9 @@ package org.springframework.core; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -38,7 +38,7 @@ import org.springframework.util.StringValueResolver; public class SimpleAliasRegistry implements AliasRegistry { /** Map from alias to canonical name */ - private final Map aliasMap = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map aliasMap = new ConcurrentHashMap(); public void registerAlias(String name, String alias) { @@ -49,7 +49,7 @@ public class SimpleAliasRegistry implements AliasRegistry { } else { if (!allowAliasOverriding()) { - String registeredName = (String) this.aliasMap.get(alias); + String registeredName = this.aliasMap.get(alias); if (registeredName != null && !registeredName.equals(name)) { throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" + name + "': It is already registered for name '" + registeredName + "'."); @@ -68,7 +68,7 @@ public class SimpleAliasRegistry implements AliasRegistry { } public void removeAlias(String alias) { - String name = (String) this.aliasMap.remove(alias); + String name = this.aliasMap.remove(alias); if (name == null) { throw new IllegalStateException("No alias '" + alias + "' registered"); } @@ -79,11 +79,10 @@ public class SimpleAliasRegistry implements AliasRegistry { } public String[] getAliases(String name) { - List aliases = new ArrayList(); + List aliases = new ArrayList(); synchronized (this.aliasMap) { - for (Iterator it = this.aliasMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String registeredName = (String) entry.getValue(); + for (Map.Entry entry : this.aliasMap.entrySet()) { + String registeredName = entry.getValue(); if (registeredName.equals(name)) { aliases.add(entry.getKey()); } @@ -102,18 +101,18 @@ public class SimpleAliasRegistry implements AliasRegistry { public void resolveAliases(StringValueResolver valueResolver) { Assert.notNull(valueResolver, "StringValueResolver must not be null"); synchronized (this.aliasMap) { - Map aliasCopy = new HashMap(this.aliasMap); - for (Iterator it = aliasCopy.keySet().iterator(); it.hasNext();) { - String alias = (String) it.next(); - String registeredName = (String) aliasCopy.get(alias); + Map aliasCopy = new HashMap(this.aliasMap); + for (String alias : aliasCopy.keySet()) { + String registeredName = aliasCopy.get(alias); String resolvedAlias = valueResolver.resolveStringValue(alias); String resolvedName = valueResolver.resolveStringValue(registeredName); if (!resolvedAlias.equals(alias)) { - String existingName = (String) this.aliasMap.get(resolvedAlias); + String existingName = this.aliasMap.get(resolvedAlias); if (existingName != null && !existingName.equals(resolvedName)) { - throw new IllegalStateException("Cannot register resolved alias '" + - resolvedAlias + "' (original: '" + alias + "') for name '" + resolvedName + - "': It is already registered for name '" + registeredName + "'."); + throw new IllegalStateException( + "Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias + + "') for name '" + resolvedName + "': It is already registered for name '" + + registeredName + "'."); } this.aliasMap.put(resolvedAlias, resolvedName); this.aliasMap.remove(alias); @@ -135,7 +134,7 @@ public class SimpleAliasRegistry implements AliasRegistry { // Handle aliasing. String resolvedName = null; do { - resolvedName = (String) this.aliasMap.get(canonicalName); + resolvedName = this.aliasMap.get(canonicalName); if (resolvedName != null) { canonicalName = resolvedName; } diff --git a/org.springframework.core/src/main/java/org/springframework/core/style/DefaultToStringStyler.java b/org.springframework.core/src/main/java/org/springframework/core/style/DefaultToStringStyler.java index 3eab22b408a..8d628d6646b 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/style/DefaultToStringStyler.java +++ b/org.springframework.core/src/main/java/org/springframework/core/style/DefaultToStringStyler.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. @@ -52,7 +52,7 @@ public class DefaultToStringStyler implements ToStringStyler { } - public void styleStart(StringBuffer buffer, Object obj) { + public void styleStart(StringBuilder buffer, Object obj) { if (!obj.getClass().isArray()) { buffer.append('[').append(ClassUtils.getShortName(obj.getClass())); styleIdentityHashCode(buffer, obj); @@ -65,33 +65,33 @@ public class DefaultToStringStyler implements ToStringStyler { } } - private void styleIdentityHashCode(StringBuffer buffer, Object obj) { + private void styleIdentityHashCode(StringBuilder buffer, Object obj) { buffer.append('@'); buffer.append(ObjectUtils.getIdentityHexString(obj)); } - public void styleEnd(StringBuffer buffer, Object o) { + public void styleEnd(StringBuilder buffer, Object o) { buffer.append(']'); } - public void styleField(StringBuffer buffer, String fieldName, Object value) { + public void styleField(StringBuilder buffer, String fieldName, Object value) { styleFieldStart(buffer, fieldName); styleValue(buffer, value); styleFieldEnd(buffer, fieldName); } - protected void styleFieldStart(StringBuffer buffer, String fieldName) { + protected void styleFieldStart(StringBuilder buffer, String fieldName) { buffer.append(' ').append(fieldName).append(" = "); } - protected void styleFieldEnd(StringBuffer buffer, String fieldName) { + protected void styleFieldEnd(StringBuilder buffer, String fieldName) { } - public void styleValue(StringBuffer buffer, Object value) { + public void styleValue(StringBuilder buffer, Object value) { buffer.append(this.valueStyler.style(value)); } - public void styleFieldSeparator(StringBuffer buffer) { + public void styleFieldSeparator(StringBuilder buffer) { buffer.append(','); } diff --git a/org.springframework.core/src/main/java/org/springframework/core/style/DefaultValueStyler.java b/org.springframework.core/src/main/java/org/springframework/core/style/DefaultValueStyler.java index 0a5d3addde7..75962f17346 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/style/DefaultValueStyler.java +++ b/org.springframework.core/src/main/java/org/springframework/core/style/DefaultValueStyler.java @@ -80,20 +80,20 @@ public class DefaultValueStyler implements ValueStyler { } private String style(Map value) { - StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); - buffer.append(MAP + "["); + StringBuilder result = new StringBuilder(value.size() * 8 + 16); + result.append(MAP + "["); for (Iterator it = value.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); - buffer.append(style(entry)); + result.append(style(entry)); if (it.hasNext()) { - buffer.append(',').append(' '); + result.append(',').append(' '); } } if (value.isEmpty()) { - buffer.append(EMPTY); + result.append(EMPTY); } - buffer.append("]"); - return buffer.toString(); + result.append("]"); + return result.toString(); } private String style(Map.Entry value) { @@ -101,19 +101,19 @@ public class DefaultValueStyler implements ValueStyler { } private String style(Collection value) { - StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); - buffer.append(getCollectionTypeString(value)).append('['); + StringBuilder result = new StringBuilder(value.size() * 8 + 16); + result.append(getCollectionTypeString(value)).append('['); for (Iterator i = value.iterator(); i.hasNext();) { - buffer.append(style(i.next())); + result.append(style(i.next())); if (i.hasNext()) { - buffer.append(',').append(' '); + result.append(',').append(' '); } } if (value.isEmpty()) { - buffer.append(EMPTY); + result.append(EMPTY); } - buffer.append("]"); - return buffer.toString(); + result.append("]"); + return result.toString(); } private String getCollectionTypeString(Collection value) { @@ -129,20 +129,20 @@ public class DefaultValueStyler implements ValueStyler { } private String styleArray(Object[] array) { - StringBuffer buffer = new StringBuffer(array.length * 8 + 16); - buffer.append(ARRAY + "<" + ClassUtils.getShortName(array.getClass().getComponentType()) + ">["); + StringBuilder result = new StringBuilder(array.length * 8 + 16); + result.append(ARRAY + "<" + ClassUtils.getShortName(array.getClass().getComponentType()) + ">["); for (int i = 0; i < array.length - 1; i++) { - buffer.append(style(array[i])); - buffer.append(',').append(' '); + result.append(style(array[i])); + result.append(',').append(' '); } if (array.length > 0) { - buffer.append(style(array[array.length - 1])); + result.append(style(array[array.length - 1])); } else { - buffer.append(EMPTY); + result.append(EMPTY); } - buffer.append("]"); - return buffer.toString(); + result.append("]"); + return result.toString(); } } diff --git a/org.springframework.core/src/main/java/org/springframework/core/style/ToStringCreator.java b/org.springframework.core/src/main/java/org/springframework/core/style/ToStringCreator.java index 57a07305138..a4da17231c4 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/style/ToStringCreator.java +++ b/org.springframework.core/src/main/java/org/springframework/core/style/ToStringCreator.java @@ -36,7 +36,7 @@ public class ToStringCreator { new DefaultToStringStyler(StylerUtils.DEFAULT_VALUE_STYLER); - private StringBuffer buffer = new StringBuffer(512); + private StringBuilder buffer = new StringBuilder(512); private ToStringStyler styler; diff --git a/org.springframework.core/src/main/java/org/springframework/core/style/ToStringStyler.java b/org.springframework.core/src/main/java/org/springframework/core/style/ToStringStyler.java index 461832938dd..5c81982c49a 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/style/ToStringStyler.java +++ b/org.springframework.core/src/main/java/org/springframework/core/style/ToStringStyler.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. @@ -31,14 +31,14 @@ public interface ToStringStyler { * @param buffer the buffer to print to * @param obj the object to style */ - void styleStart(StringBuffer buffer, Object obj); + void styleStart(StringBuilder buffer, Object obj); /** * Style a toString()'ed object after it's fields are styled. * @param buffer the buffer to print to * @param obj the object to style */ - void styleEnd(StringBuffer buffer, Object obj); + void styleEnd(StringBuilder buffer, Object obj); /** * Style a field value as a string. @@ -46,19 +46,19 @@ public interface ToStringStyler { * @param fieldName the he name of the field * @param value the field value */ - void styleField(StringBuffer buffer, String fieldName, Object value); + void styleField(StringBuilder buffer, String fieldName, Object value); /** * Style the given value. * @param buffer the buffer to print to * @param value the field value */ - void styleValue(StringBuffer buffer, Object value); + void styleValue(StringBuilder buffer, Object value); /** * Style the field separator. * @param buffer buffer to print to */ - void styleFieldSeparator(StringBuffer buffer); + void styleFieldSeparator(StringBuilder buffer); } diff --git a/org.springframework.core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java index 685c4709d20..491725be188 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.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.task; import java.io.Serializable; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; import org.springframework.util.ConcurrencyThrottleSupport; import org.springframework.util.CustomizableThreadCreator; @@ -44,15 +43,6 @@ import org.springframework.util.CustomizableThreadCreator; */ public class SimpleAsyncTaskExecutor extends CustomizableThreadCreator implements AsyncTaskExecutor, Serializable { - /** - * Default thread name prefix: "SimpleAsyncTaskExecutor-". - * @deprecated as of Spring 2.0.3, since the default thread name prefix - * is now taken from the concrete class (could be a subclass) - */ - @Deprecated - public static final String DEFAULT_THREAD_NAME_PREFIX = - ClassUtils.getShortName(SimpleAsyncTaskExecutor.class) + "-"; - /** * Permit any number of concurrent invocations: that is, don't throttle concurrency. */ diff --git a/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java b/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java index 41c7f3ac54f..ee359eb32d2 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/ClassUtils.java @@ -71,13 +71,13 @@ public abstract class ClassUtils { * Map with primitive wrapper type as key and corresponding primitive * type as value, for example: Integer.class -> int.class. */ - private static final Map primitiveWrapperTypeMap = new HashMap(8); + private static final Map primitiveWrapperTypeMap = new HashMap(8); /** * Map with primitive type name as key and corresponding primitive * type as value, for example: "int" -> "int.class". */ - private static final Map primitiveTypeNameMap = new HashMap(16); + private static final Map primitiveTypeNameMap = new HashMap(16); static { @@ -90,14 +90,13 @@ public abstract class ClassUtils { primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); - Set primitiveTypeNames = new HashSet(16); - primitiveTypeNames.addAll(primitiveWrapperTypeMap.values()); - primitiveTypeNames.addAll(Arrays.asList(new Class[] { + Set primitiveTypes = new HashSet(16); + primitiveTypes.addAll(primitiveWrapperTypeMap.values()); + primitiveTypes.addAll(Arrays.asList( boolean[].class, byte[].class, char[].class, double[].class, - float[].class, int[].class, long[].class, short[].class})); - for (Iterator it = primitiveTypeNames.iterator(); it.hasNext();) { - Class primitiveClass = (Class) it.next(); - primitiveTypeNameMap.put(primitiveClass.getName(), primitiveClass); + float[].class, int[].class, long[].class, short[].class)); + for (Class primitiveType : primitiveTypes) { + primitiveTypeNameMap.put(primitiveType.getName(), primitiveType); } } @@ -230,15 +229,11 @@ public abstract class ClassUtils { return forName(className, classLoader); } catch (ClassNotFoundException ex) { - IllegalArgumentException iae = new IllegalArgumentException("Cannot find class [" + className + "]"); - iae.initCause(ex); - throw iae; + throw new IllegalArgumentException("Cannot find class [" + className + "]", ex); } catch (LinkageError ex) { - IllegalArgumentException iae = new IllegalArgumentException( - "Error loading class [" + className + "]: problem with class file or dependent class."); - iae.initCause(ex); - throw iae; + throw new IllegalArgumentException( + "Error loading class [" + className + "]: problem with class file or dependent class.", ex); } } @@ -258,7 +253,7 @@ public abstract class ClassUtils { // SHOULD sit in a package, so a length check is worthwhile. if (name != null && name.length() <= 8) { // Could be a primitive - likely. - result = (Class) primitiveTypeNameMap.get(name); + result = primitiveTypeNameMap.get(name); } return result; } @@ -315,7 +310,7 @@ public abstract class ClassUtils { * @return the user-defined class */ public static Class getUserClass(Class clazz) { - return (clazz != null && clazz.getName().indexOf(CGLIB_CLASS_SEPARATOR) != -1 ? + return (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR) ? clazz.getSuperclass() : clazz); } @@ -436,13 +431,13 @@ public abstract class ClassUtils { * @return a qualified name for the array class */ private static String getQualifiedNameForArray(Class clazz) { - StringBuffer buffer = new StringBuffer(); + StringBuilder result = new StringBuilder(); while (clazz.isArray()) { clazz = clazz.getComponentType(); - buffer.append(ClassUtils.ARRAY_SUFFIX); + result.append(ClassUtils.ARRAY_SUFFIX); } - buffer.insert(0, clazz.getName()); - return buffer.toString(); + result.insert(0, clazz.getName()); + return result.toString(); } /** @@ -469,16 +464,16 @@ public abstract class ClassUtils { } Class clazz = value.getClass(); if (Proxy.isProxyClass(clazz)) { - StringBuffer buf = new StringBuffer(clazz.getName()); - buf.append(" implementing "); + StringBuilder result = new StringBuilder(clazz.getName()); + result.append(" implementing "); Class[] ifcs = clazz.getInterfaces(); for (int i = 0; i < ifcs.length; i++) { - buf.append(ifcs[i].getName()); + result.append(ifcs[i].getName()); if (i < ifcs.length - 1) { - buf.append(','); + result.append(','); } } - return buf.toString(); + return result.toString(); } else if (clazz.isArray()) { return getQualifiedNameForArray(clazz); @@ -566,15 +561,14 @@ public abstract class ClassUtils { Assert.notNull(methodName, "Method name must not be null"); int count = 0; Method[] declaredMethods = clazz.getDeclaredMethods(); - for (int i = 0; i < declaredMethods.length; i++) { - Method method = declaredMethods[i]; + for (Method method : declaredMethods) { if (methodName.equals(method.getName())) { count++; } } Class[] ifcs = clazz.getInterfaces(); - for (int i = 0; i < ifcs.length; i++) { - count += getMethodCountForName(ifcs[i], methodName); + for (Class ifc : ifcs) { + count += getMethodCountForName(ifc, methodName); } if (clazz.getSuperclass() != null) { count += getMethodCountForName(clazz.getSuperclass(), methodName); @@ -593,15 +587,14 @@ public abstract class ClassUtils { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(methodName, "Method name must not be null"); Method[] declaredMethods = clazz.getDeclaredMethods(); - for (int i = 0; i < declaredMethods.length; i++) { - Method method = declaredMethods[i]; + for (Method method : declaredMethods) { if (method.getName().equals(methodName)) { return true; } } Class[] ifcs = clazz.getInterfaces(); - for (int i = 0; i < ifcs.length; i++) { - if (hasAtLeastOneMethodWithName(ifcs[i], methodName)) { + for (Class ifc : ifcs) { + if (hasAtLeastOneMethodWithName(ifc, methodName)) { return true; } } @@ -657,6 +650,7 @@ public abstract class ClassUtils { } } catch (NoSuchMethodException ex) { + return null; } return null; } @@ -832,7 +826,7 @@ public abstract class ClassUtils { if (CollectionUtils.isEmpty(classes)) { return "[]"; } - StringBuffer sb = new StringBuffer("["); + StringBuilder sb = new StringBuilder("["); for (Iterator it = classes.iterator(); it.hasNext(); ) { Class clazz = (Class) it.next(); sb.append(clazz.getName()); @@ -881,18 +875,17 @@ public abstract class ClassUtils { if (clazz.isInterface()) { return new Class[] {clazz}; } - List interfaces = new ArrayList(); + List interfaces = new ArrayList(); while (clazz != null) { - for (int i = 0; i < clazz.getInterfaces().length; i++) { - Class ifc = clazz.getInterfaces()[i]; - if (!interfaces.contains(ifc) && - (classLoader == null || isVisible(ifc, classLoader))) { + Class[] ifcs = clazz.getInterfaces(); + for (Class ifc : ifcs) { + if (!interfaces.contains(ifc) && (classLoader == null || isVisible(ifc, classLoader))) { interfaces.add(ifc); } } clazz = clazz.getSuperclass(); } - return (Class[]) interfaces.toArray(new Class[interfaces.size()]); + return interfaces.toArray(new Class[interfaces.size()]); } /** @@ -913,7 +906,7 @@ public abstract class ClassUtils { * @param clazz the class to analyse for interfaces * @return all interfaces that the given object implements as Set */ - public static Set getAllInterfacesForClassAsSet(Class clazz) { + public static Set getAllInterfacesForClassAsSet(Class clazz) { return getAllInterfacesForClassAsSet(clazz, null); } @@ -926,12 +919,12 @@ public abstract class ClassUtils { * (may be null when accepting all declared interfaces) * @return all interfaces that the given object implements as Set */ - public static Set getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) { + public static Set getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) { Assert.notNull(clazz, "Class must not be null"); if (clazz.isInterface()) { return Collections.singleton(clazz); } - Set interfaces = new LinkedHashSet(); + Set interfaces = new LinkedHashSet(); while (clazz != null) { for (int i = 0; i < clazz.getInterfaces().length; i++) { Class ifc = clazz.getInterfaces()[i]; diff --git a/org.springframework.core/src/main/java/org/springframework/util/CommonsLogWriter.java b/org.springframework.core/src/main/java/org/springframework/util/CommonsLogWriter.java index dc1308d4901..361170aac4d 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/CommonsLogWriter.java +++ b/org.springframework.core/src/main/java/org/springframework/util/CommonsLogWriter.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. @@ -30,7 +30,7 @@ public class CommonsLogWriter extends Writer { private final Log logger; - private final StringBuffer buffer = new StringBuffer(); + private final StringBuilder buffer = new StringBuilder(); /** @@ -49,7 +49,7 @@ public class CommonsLogWriter extends Writer { this.buffer.setLength(0); } else { - this.buffer.append((char) ch); + this.buffer.append(ch); } } @@ -62,7 +62,7 @@ public class CommonsLogWriter extends Writer { this.buffer.setLength(0); } else { - this.buffer.append((char) ch); + this.buffer.append(ch); } } } diff --git a/org.springframework.core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java b/org.springframework.core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java index bedb9bb1e82..5739948d348 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java +++ b/org.springframework.core/src/main/java/org/springframework/util/DefaultPropertiesPersister.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. @@ -133,7 +133,7 @@ public class DefaultPropertiesPersister implements PropertiesPersister { } protected String unescape(String str) { - StringBuffer outBuffer = new StringBuffer(str.length()); + StringBuilder result = new StringBuilder(str.length()); for (int index = 0; index < str.length();) { char c = str.charAt(index++); if (c == '\\') { @@ -151,9 +151,9 @@ public class DefaultPropertiesPersister implements PropertiesPersister { c = '\f'; } } - outBuffer.append(c); + result.append(c); } - return outBuffer.toString(); + return result.toString(); } @@ -191,39 +191,39 @@ public class DefaultPropertiesPersister implements PropertiesPersister { protected String escape(String str, boolean isKey) { int len = str.length(); - StringBuffer outBuffer = new StringBuffer(len * 2); + StringBuilder result = new StringBuilder(len * 2); for (int index = 0; index < len; index++) { char c = str.charAt(index); switch (c) { case ' ': if (index == 0 || isKey) { - outBuffer.append('\\'); + result.append('\\'); } - outBuffer.append(' '); + result.append(' '); break; case '\\': - outBuffer.append("\\\\"); + result.append("\\\\"); break; case '\t': - outBuffer.append("\\t"); + result.append("\\t"); break; case '\n': - outBuffer.append("\\n"); + result.append("\\n"); break; case '\r': - outBuffer.append("\\r"); + result.append("\\r"); break; case '\f': - outBuffer.append("\\f"); + result.append("\\f"); break; default: if ("=: \t\r\n\f#!".indexOf(c) != -1) { - outBuffer.append('\\'); + result.append('\\'); } - outBuffer.append(c); + result.append(c); } } - return outBuffer.toString(); + return result.toString(); } diff --git a/org.springframework.core/src/main/java/org/springframework/util/NumberUtils.java b/org.springframework.core/src/main/java/org/springframework/util/NumberUtils.java index 7dbeed7beff..30a2baae3e7 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/NumberUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/NumberUtils.java @@ -33,10 +33,6 @@ import java.text.ParseException; */ public abstract class NumberUtils { - private static final boolean decimalFormatSupportsBigDecimal = - ClassUtils.hasMethod(DecimalFormat.class, "setParseBigDecimal", new Class[] {boolean.class}); - - /** * Convert the given number into an instance of the given target class. * @param number the number to convert @@ -200,8 +196,7 @@ public abstract class NumberUtils { boolean resetBigDecimal = false; if (numberFormat instanceof DecimalFormat) { decimalFormat = (DecimalFormat) numberFormat; - if (BigDecimal.class.equals(targetClass) && decimalFormatSupportsBigDecimal && - !decimalFormat.isParseBigDecimal()) { + if (BigDecimal.class.equals(targetClass) && !decimalFormat.isParseBigDecimal()) { decimalFormat.setParseBigDecimal(true); resetBigDecimal = true; } @@ -211,10 +206,7 @@ public abstract class NumberUtils { return convertNumberToTargetClass(number, targetClass); } catch (ParseException ex) { - IllegalArgumentException iae = - new IllegalArgumentException("Could not parse number: " + ex.getMessage()); - iae.initCause(ex); - throw iae; + throw new IllegalArgumentException("Could not parse number: " + ex.getMessage()); } finally { if (resetBigDecimal) { diff --git a/org.springframework.core/src/main/java/org/springframework/util/ObjectUtils.java b/org.springframework.core/src/main/java/org/springframework/util/ObjectUtils.java index 3237160df45..f56cc9e0bed 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/ObjectUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/ObjectUtils.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. @@ -70,10 +70,12 @@ public abstract class ObjectUtils { return true; } if (declaredExceptions != null) { - for (int i = 0; i < declaredExceptions.length; i++) { + int i = 0; + while (i < declaredExceptions.length) { if (declaredExceptions[i].isAssignableFrom(ex.getClass())) { return true; } + i++; } } return false; @@ -100,8 +102,8 @@ public abstract class ObjectUtils { if (array == null) { return false; } - for (int i = 0; i < array.length; i++) { - if (nullSafeEquals(array[i], element)) { + for (Object arrayEle : array) { + if (nullSafeEquals(arrayEle, element)) { return true; } } @@ -565,18 +567,18 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(String.valueOf(array[i])); + sb.append(String.valueOf(array[i])); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -596,19 +598,19 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -628,18 +630,18 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -659,18 +661,18 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append("'").append(array[i]).append("'"); + sb.append("'").append(array[i]).append("'"); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -690,19 +692,19 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -722,19 +724,19 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -754,18 +756,18 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -785,18 +787,18 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } /** @@ -816,18 +818,18 @@ public abstract class ObjectUtils { if (length == 0) { return EMPTY_ARRAY; } - StringBuffer buffer = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { - buffer.append(ARRAY_START); + sb.append(ARRAY_START); } else { - buffer.append(ARRAY_ELEMENT_SEPARATOR); + sb.append(ARRAY_ELEMENT_SEPARATOR); } - buffer.append(array[i]); + sb.append(array[i]); } - buffer.append(ARRAY_END); - return buffer.toString(); + sb.append(ARRAY_END); + return sb.toString(); } } diff --git a/org.springframework.core/src/main/java/org/springframework/util/ReflectionUtils.java b/org.springframework.core/src/main/java/org/springframework/util/ReflectionUtils.java index 694cb70242a..6ede41ffd82 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/ReflectionUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/ReflectionUtils.java @@ -319,10 +319,7 @@ public abstract class ReflectionUtils { * @param ex the unexpected exception */ private static void handleUnexpectedException(Throwable ex) { - // Needs to avoid the chained constructor for JDK 1.4 compatibility. - IllegalStateException isex = new IllegalStateException("Unexpected exception thrown"); - isex.initCause(ex); - throw isex; + throw new IllegalStateException("Unexpected exception thrown", ex); } /** @@ -337,8 +334,7 @@ public abstract class ReflectionUtils { public static boolean declaresException(Method method, Class exceptionType) { Assert.notNull(method, "Method must not be null"); Class[] declaredExceptions = method.getExceptionTypes(); - for (int i = 0; i < declaredExceptions.length; i++) { - Class declaredException = declaredExceptions[i]; + for (Class declaredException : declaredExceptions) { if (declaredException.isAssignableFrom(exceptionType)) { return true; } diff --git a/org.springframework.core/src/main/java/org/springframework/util/StopWatch.java b/org.springframework.core/src/main/java/org/springframework/util/StopWatch.java index d8afa1afb4d..3fd8b191466 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/StopWatch.java +++ b/org.springframework.core/src/main/java/org/springframework/util/StopWatch.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-20078the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -203,7 +203,7 @@ public class StopWatch { * For custom reporting, call getTaskInfo() and use the task info directly. */ public String prettyPrint() { - StringBuffer sb = new StringBuffer(shortSummary()); + StringBuilder sb = new StringBuilder(shortSummary()); sb.append('\n'); if (!this.keepTaskList) { sb.append("No task info kept"); @@ -234,7 +234,7 @@ public class StopWatch { */ @Override public String toString() { - StringBuffer sb = new StringBuffer(shortSummary()); + StringBuilder sb = new StringBuilder(shortSummary()); if (this.keepTaskList) { TaskInfo[] tasks = getTaskInfo(); for (int i = 0; i < tasks.length; i++) { diff --git a/org.springframework.core/src/main/java/org/springframework/util/StringUtils.java b/org.springframework.core/src/main/java/org/springframework/util/StringUtils.java index d3c9e0ab346..47208f6dda6 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/StringUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/StringUtils.java @@ -38,7 +38,7 @@ import java.util.TreeSet; * for a more comprehensive suite of String utilities. * *

This class delivers some simple functionality that should really - * be provided by the core Java String and {@link StringBuffer} + * be provided by the core Java String and {@link StringBuilder} * classes, such as the ability to {@link #replace} all occurrences of a given * substring in a target string. It also provides easy-to-use methods to convert * between delimited strings, such as CSV strings, and collections and arrays. @@ -180,14 +180,14 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuffer buf = new StringBuffer(str); - while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) { - buf.deleteCharAt(0); + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { + sb.deleteCharAt(0); } - while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) { - buf.deleteCharAt(buf.length() - 1); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { + sb.deleteCharAt(sb.length() - 1); } - return buf.toString(); + return sb.toString(); } /** @@ -201,17 +201,17 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuffer buf = new StringBuffer(str); + StringBuilder sb = new StringBuilder(str); int index = 0; - while (buf.length() > index) { - if (Character.isWhitespace(buf.charAt(index))) { - buf.deleteCharAt(index); + while (sb.length() > index) { + if (Character.isWhitespace(sb.charAt(index))) { + sb.deleteCharAt(index); } else { index++; } } - return buf.toString(); + return sb.toString(); } /** @@ -224,11 +224,11 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuffer buf = new StringBuffer(str); - while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) { - buf.deleteCharAt(0); + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { + sb.deleteCharAt(0); } - return buf.toString(); + return sb.toString(); } /** @@ -241,11 +241,11 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuffer buf = new StringBuffer(str); - while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) { - buf.deleteCharAt(buf.length() - 1); + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { + sb.deleteCharAt(sb.length() - 1); } - return buf.toString(); + return sb.toString(); } /** @@ -258,11 +258,11 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuffer buf = new StringBuffer(str); - while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { - buf.deleteCharAt(0); + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) { + sb.deleteCharAt(0); } - return buf.toString(); + return sb.toString(); } /** @@ -275,11 +275,11 @@ public abstract class StringUtils { if (!hasLength(str)) { return str; } - StringBuffer buf = new StringBuffer(str); - while (buf.length() > 0 && buf.charAt(buf.length() - 1) == trailingCharacter) { - buf.deleteCharAt(buf.length() - 1); + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { + sb.deleteCharAt(sb.length() - 1); } - return buf.toString(); + return sb.toString(); } @@ -331,7 +331,7 @@ public abstract class StringUtils { /** * Test whether the given string matches the given substring * at the given index. - * @param str the original string (or StringBuffer) + * @param str the original string (or StringBuilder) * @param index the index in the original string to start matching against * @param substring the substring to match at the given index */ @@ -374,21 +374,20 @@ public abstract class StringUtils { if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { return inString; } - StringBuffer sbuf = new StringBuffer(); - // output StringBuffer we'll build up + StringBuilder sb = new StringBuilder(); int pos = 0; // our position in the old string int index = inString.indexOf(oldPattern); // the index of an occurrence we've found, or -1 int patLen = oldPattern.length(); while (index >= 0) { - sbuf.append(inString.substring(pos, index)); - sbuf.append(newPattern); + sb.append(inString.substring(pos, index)); + sb.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } - sbuf.append(inString.substring(pos)); + sb.append(inString.substring(pos)); // remember to append any characters to the right of a match - return sbuf.toString(); + return sb.toString(); } /** @@ -412,14 +411,14 @@ public abstract class StringUtils { if (!hasLength(inString) || !hasLength(charsToDelete)) { return inString; } - StringBuffer out = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); if (charsToDelete.indexOf(c) == -1) { - out.append(c); + sb.append(c); } } - return out.toString(); + return sb.toString(); } @@ -493,15 +492,15 @@ public abstract class StringUtils { if (str == null || str.length() == 0) { return str; } - StringBuffer buf = new StringBuffer(str.length()); + StringBuilder sb = new StringBuilder(str.length()); if (capitalize) { - buf.append(Character.toUpperCase(str.charAt(0))); + sb.append(Character.toUpperCase(str.charAt(0))); } else { - buf.append(Character.toLowerCase(str.charAt(0))); + sb.append(Character.toLowerCase(str.charAt(0))); } - buf.append(str.substring(1)); - return buf.toString(); + sb.append(str.substring(1)); + return sb.toString(); } /** diff --git a/org.springframework.core/src/main/java/org/springframework/util/SystemPropertyUtils.java b/org.springframework.core/src/main/java/org/springframework/util/SystemPropertyUtils.java index ab61950e966..61c2c90f10a 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/SystemPropertyUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/SystemPropertyUtils.java @@ -46,13 +46,13 @@ public abstract class SystemPropertyUtils { * @see #PLACEHOLDER_SUFFIX */ public static String resolvePlaceholders(String text) { - StringBuffer buf = new StringBuffer(text); + StringBuilder result = new StringBuilder(text); - int startIndex = buf.indexOf(PLACEHOLDER_PREFIX); + int startIndex = result.indexOf(PLACEHOLDER_PREFIX); while (startIndex != -1) { - int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length()); + int endIndex = result.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length()); if (endIndex != -1) { - String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); + String placeholder = result.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length(); try { String propVal = System.getProperty(placeholder); @@ -61,7 +61,7 @@ public abstract class SystemPropertyUtils { propVal = System.getenv(placeholder); } if (propVal != null) { - buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); + result.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); nextIndex = startIndex + propVal.length(); } else { @@ -73,14 +73,14 @@ public abstract class SystemPropertyUtils { System.err.println("Could not resolve placeholder '" + placeholder + "' in [" + text + "] as system property: " + ex); } - startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex); + startIndex = result.indexOf(PLACEHOLDER_PREFIX, nextIndex); } else { startIndex = -1; } } - return buf.toString(); + return result.toString(); } } diff --git a/org.springframework.core/src/main/java/org/springframework/util/xml/DomUtils.java b/org.springframework.core/src/main/java/org/springframework/util/xml/DomUtils.java index 9e62e252717..2bd5ca6fb0c 100644 --- a/org.springframework.core/src/main/java/org/springframework/util/xml/DomUtils.java +++ b/org.springframework.core/src/main/java/org/springframework/util/xml/DomUtils.java @@ -128,15 +128,15 @@ public abstract class DomUtils { */ public static String getTextValue(Element valueEle) { Assert.notNull(valueEle, "Element must not be null"); - StringBuffer value = new StringBuffer(); + StringBuilder sb = new StringBuilder(); NodeList nl = valueEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) { - value.append(item.getNodeValue()); + sb.append(item.getNodeValue()); } } - return value.toString(); + return sb.toString(); } /** diff --git a/org.springframework.expression/expression.iml b/org.springframework.expression/expression.iml index a6fc0ed6c6c..bebf8a103c6 100644 --- a/org.springframework.expression/expression.iml +++ b/org.springframework.expression/expression.iml @@ -1,48 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java b/org.springframework.expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java index 6efc351f66c..bd6ee7825df 100644 --- a/org.springframework.expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java +++ b/org.springframework.expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2004-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.expression.spel; import junit.framework.TestCase; @@ -27,14 +28,13 @@ import org.springframework.expression.spel.ast.PropertyOrFieldReference; * * @author Andy Clement */ -@SuppressWarnings("unused") public class PerformanceTests extends TestCase { public static final int ITERATIONS = 1000; public static final boolean report = true; private static SpelExpressionParser parser = new SpelExpressionParser(); - private static EvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();; + private static EvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); public void testPerformanceOfSimpleAccess() throws Exception { long starttime = 0; diff --git a/org.springframework.expression/src/test/java/org/springframework/expression/spel/SpelUtilitiesTests.java b/org.springframework.expression/src/test/java/org/springframework/expression/spel/SpelUtilitiesTests.java index aea8f9d4e50..35507fcdec7 100644 --- a/org.springframework.expression/src/test/java/org/springframework/expression/spel/SpelUtilitiesTests.java +++ b/org.springframework.expression/src/test/java/org/springframework/expression/spel/SpelUtilitiesTests.java @@ -37,7 +37,7 @@ public class SpelUtilitiesTests extends TestCase { "OperatorPlus value=+ children=#2", " CompoundExpression value=EXPRESSION", " IntLiteral value=1", " CompoundExpression value=EXPRESSION", " IntLiteral value=2", "===> Expression '1 + 2' - AST end" }; - checkExpected(theAst, expectedLines); + //checkExpected(theAst, expectedLines); } private static void checkExpected(String theData, String[] expectedLines) { diff --git a/org.springframework.instrument/instrument.iml b/org.springframework.instrument/instrument.iml index 550885dbc35..ef0c9607f1a 100644 --- a/org.springframework.instrument/instrument.iml +++ b/org.springframework.instrument/instrument.iml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.jdbc/jdbc.iml b/org.springframework.jdbc/jdbc.iml index 21a83b71c8d..386618b518f 100644 --- a/org.springframework.jdbc/jdbc.iml +++ b/org.springframework.jdbc/jdbc.iml @@ -1,92 +1,92 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java index 8b57be61cfc..2e8ef41a57f 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/DriverManagerDataSource.java @@ -147,10 +147,7 @@ public class DriverManagerDataSource extends AbstractDriverBasedDataSource { Class.forName(driverClassNameToUse, true, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException ex) { - IllegalStateException ise = - new IllegalStateException("Could not load JDBC driver class [" + driverClassNameToUse + "]"); - ise.initCause(ex); - throw ise; + throw new IllegalStateException("Could not load JDBC driver class [" + driverClassNameToUse + "]", ex); } if (logger.isInfoEnabled()) { logger.info("Loaded JDBC driver: " + driverClassNameToUse); diff --git a/org.springframework.jms/jms.iml b/org.springframework.jms/jms.iml index 467dbcf71e9..51d0f6cfbad 100644 --- a/org.springframework.jms/jms.iml +++ b/org.springframework.jms/jms.iml @@ -1,92 +1,92 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/AbstractPoolingServerSessionFactory.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/AbstractPoolingServerSessionFactory.java deleted file mode 100644 index d2ac49c0919..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/AbstractPoolingServerSessionFactory.java +++ /dev/null @@ -1,179 +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.jms.listener.serversession; - -import javax.jms.JMSException; -import javax.jms.ServerSession; -import javax.jms.Session; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.core.task.TaskExecutor; -import org.springframework.jms.support.JmsUtils; -import org.springframework.scheduling.timer.TimerTaskExecutor; - -/** - * Abstract base class for ServerSessionFactory implementations - * that pool ServerSessionFactory instances. - * - *

Provides a factory method that creates a poolable ServerSession - * (to be added as new instance to a pool), a callback method invoked - * when a ServerSession finished an execution of its listener (to return - * an instance to the pool), and a method to destroy a ServerSession instance - * (after removing an instance from the pool). - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - * @see org.springframework.jms.listener.serversession.CommonsPoolServerSessionFactory - */ -public abstract class AbstractPoolingServerSessionFactory implements ServerSessionFactory { - - protected final Log logger = LogFactory.getLog(getClass()); - - private TaskExecutor taskExecutor; - - private int maxSize; - - - /** - * Specify the TaskExecutor to use for executing ServerSessions - * (and consequently, the underlying MessageListener). - *

Default is a {@link org.springframework.scheduling.timer.TimerTaskExecutor} - * for each pooled ServerSession, using one Thread per pooled JMS Session. - * Alternatives are a shared TimerTaskExecutor, sharing a single Thread - * for the execution of all ServerSessions, or a TaskExecutor - * implementation backed by a thread pool. - */ - public void setTaskExecutor(TaskExecutor taskExecutor) { - this.taskExecutor = taskExecutor; - } - - /** - * Return the TaskExecutor to use for executing ServerSessions. - */ - protected TaskExecutor getTaskExecutor() { - return this.taskExecutor; - } - - /** - * Set the maximum size of the pool. - */ - public void setMaxSize(int maxSize) { - this.maxSize = maxSize; - } - - /** - * Return the maximum size of the pool. - */ - public int getMaxSize() { - return this.maxSize; - } - - - /** - * Create a new poolable ServerSession. - * To be called when a new instance should be added to the pool. - * @param sessionManager the listener session manager to create the - * poolable ServerSession for - * @return the new poolable ServerSession - * @throws JMSException if creation failed - */ - protected final ServerSession createServerSession(ListenerSessionManager sessionManager) throws JMSException { - return new PoolableServerSession(sessionManager); - } - - /** - * Destroy the given poolable ServerSession. - * To be called when an instance got removed from the pool. - * @param serverSession the poolable ServerSession to destroy - */ - protected final void destroyServerSession(ServerSession serverSession) { - if (serverSession != null) { - ((PoolableServerSession) serverSession).close(); - } - } - - - /** - * Template method called by a ServerSession if it finished - * execution of its listener and is ready to go back into the pool. - *

Subclasses should implement the actual returning of the instance - * to the pool. - * @param serverSession the ServerSession that finished its execution - * @param sessionManager the session manager that the ServerSession belongs to - */ - protected abstract void serverSessionFinished( - ServerSession serverSession, ListenerSessionManager sessionManager); - - - /** - * ServerSession implementation designed to be pooled. - * Creates a new JMS Session on instantiation, reuses it - * for all executions, and closes it on close. - *

Creates a TimerTaskExecutor (using a single Thread) per - * ServerSession, unless given a specific TaskExecutor to use. - */ - private class PoolableServerSession implements ServerSession { - - private final ListenerSessionManager sessionManager; - - private final Session session; - - private TaskExecutor taskExecutor; - - private TimerTaskExecutor internalExecutor; - - public PoolableServerSession(final ListenerSessionManager sessionManager) throws JMSException { - this.sessionManager = sessionManager; - this.session = sessionManager.createListenerSession(); - this.taskExecutor = getTaskExecutor(); - if (this.taskExecutor == null) { - this.internalExecutor = new TimerTaskExecutor(); - this.internalExecutor.afterPropertiesSet(); - this.taskExecutor = this.internalExecutor; - } - } - - public Session getSession() { - return this.session; - } - - public void start() { - this.taskExecutor.execute(new Runnable() { - public void run() { - try { - sessionManager.executeListenerSession(session); - } - finally { - serverSessionFinished(PoolableServerSession.this, sessionManager); - } - } - }); - } - - public void close() { - if (this.internalExecutor != null) { - this.internalExecutor.destroy(); - } - JmsUtils.closeSession(this.session); - } - } - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/CommonsPoolServerSessionFactory.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/CommonsPoolServerSessionFactory.java deleted file mode 100644 index f10dc356da2..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/CommonsPoolServerSessionFactory.java +++ /dev/null @@ -1,274 +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.jms.listener.serversession; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.jms.JMSException; -import javax.jms.ServerSession; - -import org.apache.commons.pool.ObjectPool; -import org.apache.commons.pool.PoolableObjectFactory; -import org.apache.commons.pool.impl.GenericObjectPool; - -/** - * {@link ServerSessionFactory} implementation that holds JMS - * ServerSessions in a configurable Jakarta Commons Pool. - * - *

By default, an instance of GenericObjectPool is created. - * Subclasses may change the type of ObjectPool used by - * overriding the createObjectPool method. - * - *

Provides many configuration properties mirroring those of the Commons Pool - * GenericObjectPool class; these properties are passed to the - * GenericObjectPool during construction. If creating a subclass of this - * class to change the ObjectPool implementation type, pass in the values - * of configuration properties that are relevant to your chosen implementation. - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - * @see GenericObjectPool - * @see #createObjectPool - * @see #setMaxSize - * @see #setMaxIdle - * @see #setMinIdle - * @see #setMaxWait - */ -public class CommonsPoolServerSessionFactory extends AbstractPoolingServerSessionFactory { - - private int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE; - - private int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE; - - private long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT; - - private long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; - - private long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; - - private final Map serverSessionPools = Collections.synchronizedMap(new HashMap(1)); - - - /** - * Create a CommonsPoolServerSessionFactory with default settings. - * Default maximum size of the pool is 8. - * @see #setMaxSize - * @see GenericObjectPool#setMaxActive - */ - public CommonsPoolServerSessionFactory() { - setMaxSize(GenericObjectPool.DEFAULT_MAX_ACTIVE); - } - - - /** - * Set the maximum number of idle ServerSessions in the pool. - * Default is 8. - * @see GenericObjectPool#setMaxIdle - */ - public void setMaxIdle(int maxIdle) { - this.maxIdle = maxIdle; - } - - /** - * Return the maximum number of idle ServerSessions in the pool. - */ - public int getMaxIdle() { - return this.maxIdle; - } - - /** - * Set the minimum number of idle ServerSessions in the pool. - * Default is 0. - * @see GenericObjectPool#setMinIdle - */ - public void setMinIdle(int minIdle) { - this.minIdle = minIdle; - } - - /** - * Return the minimum number of idle ServerSessions in the pool. - */ - public int getMinIdle() { - return this.minIdle; - } - - /** - * Set the maximum waiting time for fetching an ServerSession from the pool. - * Default is -1, waiting forever. - * @see GenericObjectPool#setMaxWait - */ - public void setMaxWait(long maxWait) { - this.maxWait = maxWait; - } - - /** - * Return the maximum waiting time for fetching a ServerSession from the pool. - */ - public long getMaxWait() { - return this.maxWait; - } - - /** - * Set the time between eviction runs that check idle ServerSessions - * whether they have been idle for too long or have become invalid. - * Default is -1, not performing any eviction. - * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis - */ - public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { - this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; - } - - /** - * Return the time between eviction runs that check idle ServerSessions. - */ - public long getTimeBetweenEvictionRunsMillis() { - return this.timeBetweenEvictionRunsMillis; - } - - /** - * Set the minimum time that an idle ServerSession can sit in the pool - * before it becomes subject to eviction. Default is 1800000 (30 minutes). - *

Note that eviction runs need to be performed to take this - * setting into effect. - * @see #setTimeBetweenEvictionRunsMillis - * @see GenericObjectPool#setMinEvictableIdleTimeMillis - */ - public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { - this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; - } - - /** - * Return the minimum time that an idle ServerSession can sit in the pool. - */ - public long getMinEvictableIdleTimeMillis() { - return this.minEvictableIdleTimeMillis; - } - - - /** - * Returns a ServerSession from the pool, creating a new pool for the given - * session manager if necessary. - * @see #createObjectPool - */ - public ServerSession getServerSession(ListenerSessionManager sessionManager) throws JMSException { - ObjectPool pool = null; - synchronized (this.serverSessionPools) { - pool = (ObjectPool) this.serverSessionPools.get(sessionManager); - if (pool == null) { - if (logger.isInfoEnabled()) { - logger.info("Creating Commons ServerSession pool for: " + sessionManager); - } - pool = createObjectPool(sessionManager); - this.serverSessionPools.put(sessionManager, pool); - } - } - try { - return (ServerSession) pool.borrowObject(); - } - catch (Exception ex) { - JMSException jmsEx = new JMSException("Failed to borrow ServerSession from pool"); - jmsEx.setLinkedException(ex); - throw jmsEx; - } - } - - /** - * Subclasses can override this if they want to return a specific Commons pool. - * They should apply any configuration properties to the pool here. - *

Default is a GenericObjectPool instance with the given pool size. - * @param sessionManager the session manager to use for - * creating and executing new listener sessions - * @return an empty Commons ObjectPool. - * @see org.apache.commons.pool.impl.GenericObjectPool - * @see #setMaxSize - */ - protected ObjectPool createObjectPool(ListenerSessionManager sessionManager) { - GenericObjectPool pool = new GenericObjectPool(createPoolableObjectFactory(sessionManager)); - pool.setMaxActive(getMaxSize()); - pool.setMaxIdle(getMaxIdle()); - pool.setMinIdle(getMinIdle()); - pool.setMaxWait(getMaxWait()); - pool.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis()); - pool.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis()); - return pool; - } - - /** - * Create a Commons PoolableObjectFactory adapter for the given session manager. - * Calls createServerSession and destroyServerSession - * as defined by the AbstractPoolingServerSessionFactory class. - * @param sessionManager the session manager to use for - * creating and executing new listener sessions - * @return the Commons PoolableObjectFactory - * @see #createServerSession - * @see #destroyServerSession - */ - protected PoolableObjectFactory createPoolableObjectFactory(final ListenerSessionManager sessionManager) { - return new PoolableObjectFactory() { - public Object makeObject() throws JMSException { - return createServerSession(sessionManager); - } - public void destroyObject(Object obj) { - destroyServerSession((ServerSession) obj); - } - public boolean validateObject(Object obj) { - return true; - } - public void activateObject(Object obj) { - } - public void passivateObject(Object obj) { - } - }; - } - - /** - * Returns the given ServerSession, which just finished an execution - * of its listener, back to the pool. - */ - protected void serverSessionFinished(ServerSession serverSession, ListenerSessionManager sessionManager) { - ObjectPool pool = (ObjectPool) this.serverSessionPools.get(sessionManager); - if (pool == null) { - throw new IllegalStateException("No pool found for session manager [" + sessionManager + "]"); - } - try { - pool.returnObject(serverSession); - } - catch (Exception ex) { - logger.error("Failed to return ServerSession to pool", ex); - } - } - - /** - * Closes and removes the pool for the given session manager. - */ - public void close(ListenerSessionManager sessionManager) { - ObjectPool pool = (ObjectPool) this.serverSessionPools.remove(sessionManager); - if (pool != null) { - try { - pool.close(); - } - catch (Exception ex) { - logger.error("Failed to close ServerSession pool", ex); - } - } - } - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ListenerSessionManager.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ListenerSessionManager.java deleted file mode 100644 index fd39e14e50c..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ListenerSessionManager.java +++ /dev/null @@ -1,58 +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.jms.listener.serversession; - -import javax.jms.JMSException; -import javax.jms.Session; - -/** - * SPI interface for creating and executing JMS Sessions, - * pre-populated with a specific MessageListener. - * Implemented by ServerSessionMessageListenerContainer, - * accessed by ServerSessionFactory implementations. - * - *

Effectively, an instance that implements this interface - * represents a message listener container for a specific - * listener and destination. - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - * @see ServerSessionFactory - * @see ServerSessionMessageListenerContainer - */ -public interface ListenerSessionManager { - - /** - * Create a new JMS Session, pre-populated with this manager's - * MessageListener. - * @return the new JMS Session - * @throws JMSException if Session creation failed - * @see javax.jms.Session#setMessageListener(javax.jms.MessageListener) - */ - Session createListenerSession() throws JMSException; - - /** - * Execute the given JMS Session, triggering its MessageListener - * with pre-loaded messages. - * @param session the JMS Session to invoke - * @see javax.jms.Session#run() - */ - void executeListenerSession(Session session); - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionFactory.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionFactory.java deleted file mode 100644 index 65f0698ad8b..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionFactory.java +++ /dev/null @@ -1,63 +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.jms.listener.serversession; - -import javax.jms.JMSException; -import javax.jms.ServerSession; - -import org.springframework.jms.listener.serversession.ListenerSessionManager; - -/** - * SPI interface to be implemented by components that manage - * JMS ServerSessions. Usually, but not necessarily, an implementation - * of this interface will hold a pool of ServerSessions. - * - *

The passed-in ListenerSessionManager has to be used for creating - * and executing JMS Sessions. This session manager is responsible for - * registering a MessageListener with all Sessions that it creates. - * Consequently, the ServerSessionFactory implementation has to - * concentrate on the actual lifecycle (e.g. pooling) of JMS Sessions, - * but is not concerned about Session creation or execution. - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - * @see org.springframework.jms.listener.serversession.ListenerSessionManager - * @see org.springframework.jms.listener.serversession.ServerSessionMessageListenerContainer - */ -public interface ServerSessionFactory { - - /** - * Retrieve a JMS ServerSession for the given session manager. - * @param sessionManager the session manager to use for - * creating and executing new listener sessions - * (implicitly indicating the target listener to invoke) - * @return the JMS ServerSession - * @throws JMSException if retrieval failed - */ - ServerSession getServerSession(ListenerSessionManager sessionManager) throws JMSException; - - /** - * Close all ServerSessions for the given session manager. - * @param sessionManager the session manager used for - * creating and executing new listener sessions - * (implicitly indicating the target listener) - */ - void close(ListenerSessionManager sessionManager); - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionMessageListenerContainer.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionMessageListenerContainer.java deleted file mode 100644 index fc12215bf5e..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionMessageListenerContainer.java +++ /dev/null @@ -1,256 +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.jms.listener.serversession; - -import javax.jms.Connection; -import javax.jms.ConnectionConsumer; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.ServerSession; -import javax.jms.ServerSessionPool; -import javax.jms.Session; -import javax.jms.Topic; - -import org.springframework.jms.listener.AbstractMessageListenerContainer; -import org.springframework.jms.support.JmsUtils; - -/** - * Message listener container that builds on the {@link javax.jms.ServerSessionPool} - * SPI, creating JMS ServerSession instances through a pluggable - * {@link ServerSessionFactory}. - * - *

NOTE: This class requires a JMS 1.1+ provider, because it builds on the - * domain-independent API. Use the {@link ServerSessionMessageListenerContainer102} - * subclass for a JMS 1.0.2 provider, e.g. when running on a J2EE 1.3 server. - * - *

The default ServerSessionFactory is a {@link SimpleServerSessionFactory}, - * which will create a new ServerSession for each listener execution. - * Consider specifying a {@link CommonsPoolServerSessionFactory} to reuse JMS - * Sessions and/or to limit the number of concurrent ServerSession executions. - * - *

See the {@link AbstractMessageListenerContainer} javadoc for details - * on acknowledge modes and other configuration options. - * - *

This is an 'advanced' (special-purpose) message listener container. - * For a simpler message listener container, in particular when using - * a JMS provider without ServerSessionPool support, consider using - * {@link org.springframework.jms.listener.SimpleMessageListenerContainer}. - * For a general one-stop shop that is nevertheless very flexible, consider - * {@link org.springframework.jms.listener.DefaultMessageListenerContainer}. - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - * @see org.springframework.jms.listener.SimpleMessageListenerContainer - * @see org.springframework.jms.listener.endpoint.JmsMessageEndpointManager - */ -public class ServerSessionMessageListenerContainer extends AbstractMessageListenerContainer - implements ListenerSessionManager { - - private ServerSessionFactory serverSessionFactory = new SimpleServerSessionFactory(); - - private int maxMessagesPerTask = 1; - - private ConnectionConsumer consumer; - - - /** - * Set the Spring ServerSessionFactory to use. - *

Default is a plain SimpleServerSessionFactory. - * Consider using a CommonsPoolServerSessionFactory to reuse JMS Sessions - * and/or to limit the number of concurrent ServerSession executions. - * @see SimpleServerSessionFactory - * @see CommonsPoolServerSessionFactory - */ - public void setServerSessionFactory(ServerSessionFactory serverSessionFactory) { - this.serverSessionFactory = - (serverSessionFactory != null ? serverSessionFactory : new SimpleServerSessionFactory()); - } - - /** - * Return the Spring ServerSessionFactory to use. - */ - protected ServerSessionFactory getServerSessionFactory() { - return this.serverSessionFactory; - } - - /** - * Set the maximum number of messages to load into a JMS Session. - * Default is 1. - *

See the corresponding JMS createConnectionConsumer - * argument for details. - * @see javax.jms.Connection#createConnectionConsumer - */ - public void setMaxMessagesPerTask(int maxMessagesPerTask) { - this.maxMessagesPerTask = maxMessagesPerTask; - } - - /** - * Return the maximum number of messages to load into a JMS Session. - */ - protected int getMaxMessagesPerTask() { - return this.maxMessagesPerTask; - } - - - //------------------------------------------------------------------------- - // Implementation of AbstractMessageListenerContainer's template methods - //------------------------------------------------------------------------- - - /** - * Always use a shared JMS Connection. - */ - protected final boolean sharedConnectionEnabled() { - return true; - } - - /** - * Creates a JMS ServerSessionPool for the specified listener and registers - * it with a JMS ConnectionConsumer for the specified destination. - * @see #createServerSessionPool - * @see #createConsumer - */ - protected void doInitialize() throws JMSException { - establishSharedConnection(); - - Connection con = getSharedConnection(); - Destination destination = getDestination(); - if (destination == null) { - Session session = createSession(con); - try { - destination = resolveDestinationName(session, getDestinationName()); - } - finally { - JmsUtils.closeSession(session); - } - } - ServerSessionPool pool = createServerSessionPool(); - this.consumer = createConsumer(con, destination, pool); - } - - /** - * Create a JMS ServerSessionPool for the specified message listener, - * via this container's ServerSessionFactory. - *

This message listener container implements the ListenerSessionManager - * interface, hence can be passed to the ServerSessionFactory itself. - * @return the ServerSessionPool - * @throws JMSException if creation of the ServerSessionPool failed - * @see #setServerSessionFactory - * @see ServerSessionFactory#getServerSession(ListenerSessionManager) - */ - protected ServerSessionPool createServerSessionPool() throws JMSException { - return new ServerSessionPool() { - public ServerSession getServerSession() throws JMSException { - logger.debug("JMS ConnectionConsumer requests ServerSession"); - return getServerSessionFactory().getServerSession(ServerSessionMessageListenerContainer.this); - } - }; - } - - /** - * Return the JMS ConnectionConsumer used by this message listener container. - * Available after initialization. - */ - protected final ConnectionConsumer getConsumer() { - return this.consumer; - } - - /** - * Close the JMS ServerSessionPool for the specified message listener, - * via this container's ServerSessionFactory, and subsequently also - * this container's JMS ConnectionConsumer. - *

This message listener container implements the ListenerSessionManager - * interface, hence can be passed to the ServerSessionFactory itself. - * @see #setServerSessionFactory - * @see ServerSessionFactory#getServerSession(ListenerSessionManager) - */ - protected void doShutdown() throws JMSException { - logger.debug("Closing ServerSessionFactory"); - getServerSessionFactory().close(this); - logger.debug("Closing JMS ConnectionConsumer"); - this.consumer.close(); - } - - - //------------------------------------------------------------------------- - // Implementation of the ListenerSessionManager interface - //------------------------------------------------------------------------- - - /** - * Create a JMS Session with the specified listener registered. - * Listener execution is delegated to the executeListener method. - *

Default implementation simply calls setMessageListener - * on a newly created JMS Session, according to the JMS specification's - * ServerSessionPool section. - * @return the JMS Session - * @throws JMSException if thrown by JMS API methods - * @see #executeListener - */ - public Session createListenerSession() throws JMSException { - final Session session = createSession(getSharedConnection()); - - session.setMessageListener(new MessageListener() { - public void onMessage(Message message) { - executeListener(session, message); - } - }); - - return session; - } - - /** - * Execute the given JMS Session, triggering invocation - * of its listener. - *

Default implementation simply calls run() - * on the JMS Session, according to the JMS specification's - * ServerSessionPool section. - * @param session the JMS Session to execute - */ - public void executeListenerSession(Session session) { - session.run(); - } - - - //------------------------------------------------------------------------- - // JMS 1.1 factory methods, potentially overridden for JMS 1.0.2 - //------------------------------------------------------------------------- - - /** - * Create a JMS ConnectionConsumer for the given Connection. - *

This implementation uses JMS 1.1 API. - * @param con the JMS Connection to create a Session for - * @param destination the JMS Destination to listen to - * @param pool the ServerSessionpool to use - * @return the new JMS Session - * @throws JMSException if thrown by JMS API methods - */ - protected ConnectionConsumer createConsumer(Connection con, Destination destination, ServerSessionPool pool) - throws JMSException { - - if (isSubscriptionDurable() && destination instanceof Topic) { - return con.createDurableConnectionConsumer( - (Topic) destination, getDurableSubscriptionName(), getMessageSelector(), pool, getMaxMessagesPerTask()); - } - else { - return con.createConnectionConsumer(destination, getMessageSelector(), pool, getMaxMessagesPerTask()); - } - } - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionMessageListenerContainer102.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionMessageListenerContainer102.java deleted file mode 100644 index fa4d80216e2..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/ServerSessionMessageListenerContainer102.java +++ /dev/null @@ -1,101 +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.jms.listener.serversession; - -import javax.jms.Connection; -import javax.jms.ConnectionConsumer; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueConnectionFactory; -import javax.jms.ServerSessionPool; -import javax.jms.Session; -import javax.jms.Topic; -import javax.jms.TopicConnection; -import javax.jms.TopicConnectionFactory; - -/** - * A subclass of {@link ServerSessionMessageListenerContainer} for the JMS 1.0.2 specification, - * not relying on JMS 1.1 methods like ServerSessionMessageListenerContainer itself. - * - *

This class can be used for JMS 1.0.2 providers, offering the same facility as - * ServerSessionMessageListenerContainer does for JMS 1.1 providers. - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - */ -public class ServerSessionMessageListenerContainer102 extends ServerSessionMessageListenerContainer { - - /** - * This implementation overrides the superclass method to use JMS 1.0.2 API. - */ - protected Connection createConnection() throws JMSException { - if (isPubSubDomain()) { - return ((TopicConnectionFactory) getConnectionFactory()).createTopicConnection(); - } - else { - return ((QueueConnectionFactory) getConnectionFactory()).createQueueConnection(); - } - } - - /** - * This implementation overrides the superclass method to use JMS 1.0.2 API. - */ - protected ConnectionConsumer createConsumer(Connection con, Destination destination, ServerSessionPool pool) - throws JMSException { - - if (isPubSubDomain()) { - if (isSubscriptionDurable()) { - return ((TopicConnection) con).createDurableConnectionConsumer( - (Topic) destination, getDurableSubscriptionName(), getMessageSelector(), pool, getMaxMessagesPerTask()); - } - else { - return ((TopicConnection) con).createConnectionConsumer( - (Topic) destination, getMessageSelector(), pool, getMaxMessagesPerTask()); - } - } - else { - return ((QueueConnection) con).createConnectionConsumer( - (Queue) destination, getMessageSelector(), pool, getMaxMessagesPerTask()); - } - } - - /** - * This implementation overrides the superclass method to use JMS 1.0.2 API. - */ - protected Session createSession(Connection con) throws JMSException { - if (isPubSubDomain()) { - return ((TopicConnection) con).createTopicSession(isSessionTransacted(), getSessionAcknowledgeMode()); - } - else { - return ((QueueConnection) con).createQueueSession(isSessionTransacted(), getSessionAcknowledgeMode()); - } - } - - /** - * This implementation overrides the superclass method to avoid using - * JMS 1.1's Session getAcknowledgeMode() method. - * The best we can do here is to check the setting on the listener container. - */ - protected boolean isClientAcknowledge(Session session) throws JMSException { - return (getSessionAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE); - } - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/SimpleServerSessionFactory.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/SimpleServerSessionFactory.java deleted file mode 100644 index 0f7b8ec2218..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/SimpleServerSessionFactory.java +++ /dev/null @@ -1,138 +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.jms.listener.serversession; - -import javax.jms.JMSException; -import javax.jms.ServerSession; -import javax.jms.Session; - -import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.core.task.TaskExecutor; -import org.springframework.jms.support.JmsUtils; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; - -/** - * The simplest possible implementation of the ServerSessionFactory SPI: - * creating a new ServerSession with a new JMS Session every time. - * This is the default used by ServerSessionMessageListenerContainer. - * - *

The execution of a ServerSession (and its MessageListener) gets delegated - * to a TaskExecutor. By default, a SimpleAsyncTaskExecutor will be used, - * creating a new Thread for every execution attempt. Alternatives are a - * TimerTaskExecutor, sharing a single Thread for the execution of all - * ServerSessions, or a TaskExecutor implementation backed by a thread pool. - * - *

To reuse JMS Sessions and/or to limit the number of concurrent - * ServerSession executions, consider using a pooling ServerSessionFactory: - * for example, CommonsPoolServerSessionFactory. - * - * @author Juergen Hoeller - * @since 2.0 - * @deprecated as of Spring 2.5, in favor of DefaultMessageListenerContainer - * and JmsMessageEndpointManager. To be removed in Spring 3.0. - * @see org.springframework.core.task.TaskExecutor - * @see org.springframework.core.task.SimpleAsyncTaskExecutor - * @see org.springframework.scheduling.timer.TimerTaskExecutor - * @see CommonsPoolServerSessionFactory - * @see ServerSessionMessageListenerContainer - */ -public class SimpleServerSessionFactory implements ServerSessionFactory { - - /** - * Default thread name prefix: "SimpleServerSessionFactory-". - */ - public static final String DEFAULT_THREAD_NAME_PREFIX = - ClassUtils.getShortName(SimpleServerSessionFactory.class) + "-"; - - - private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(DEFAULT_THREAD_NAME_PREFIX); - - - /** - * Specify the TaskExecutor to use for executing ServerSessions - * (and consequently, the underlying MessageListener). - *

Default is a SimpleAsyncTaskExecutor, creating a new Thread for - * every execution attempt. Alternatives are a TimerTaskExecutor, - * sharing a single Thread for the execution of all ServerSessions, - * or a TaskExecutor implementation backed by a thread pool. - * @see org.springframework.core.task.SimpleAsyncTaskExecutor - * @see org.springframework.scheduling.timer.TimerTaskExecutor - */ - public void setTaskExecutor(TaskExecutor taskExecutor) { - Assert.notNull(taskExecutor, "taskExecutor is required"); - this.taskExecutor = taskExecutor; - } - - /** - * Return the TaskExecutor to use for executing ServerSessions. - */ - protected TaskExecutor getTaskExecutor() { - return taskExecutor; - } - - - /** - * Creates a new SimpleServerSession with a new JMS Session - * for every call. - */ - public ServerSession getServerSession(ListenerSessionManager sessionManager) throws JMSException { - return new SimpleServerSession(sessionManager); - } - - /** - * This implementation is empty, as there is no state held for - * each ListenerSessionManager. - */ - public void close(ListenerSessionManager sessionManager) { - } - - - /** - * ServerSession implementation that simply creates a new - * JMS Session and executes it via the specified TaskExecutor. - */ - private class SimpleServerSession implements ServerSession { - - private final ListenerSessionManager sessionManager; - - private final Session session; - - public SimpleServerSession(ListenerSessionManager sessionManager) throws JMSException { - this.sessionManager = sessionManager; - this.session = sessionManager.createListenerSession(); - } - - public Session getSession() { - return session; - } - - public void start() { - getTaskExecutor().execute(new Runnable() { - public void run() { - try { - sessionManager.executeListenerSession(session); - } - finally { - JmsUtils.closeSession(session); - } - } - }); - } - } - -} diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/package.html b/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/package.html deleted file mode 100644 index 31c2c4be21c..00000000000 --- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/serversession/package.html +++ /dev/null @@ -1,8 +0,0 @@ - - - -This package contains the ServerSessionMessageListenerContainer implementation, -based on the standard JMS ServerSessionPool API. - - - diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/support/destination/JndiDestinationResolver.java b/org.springframework.jms/src/main/java/org/springframework/jms/support/destination/JndiDestinationResolver.java index 0696c596d11..e7ce546f6d3 100644 --- a/org.springframework.jms/src/main/java/org/springframework/jms/support/destination/JndiDestinationResolver.java +++ b/org.springframework.jms/src/main/java/org/springframework/jms/support/destination/JndiDestinationResolver.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,7 +17,7 @@ package org.springframework.jms.support.destination; import java.util.Map; - +import java.util.concurrent.ConcurrentHashMap; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Queue; @@ -25,7 +25,6 @@ import javax.jms.Session; import javax.jms.Topic; import javax.naming.NamingException; -import org.springframework.core.CollectionFactory; import org.springframework.jndi.JndiLocatorSupport; import org.springframework.util.Assert; @@ -61,7 +60,7 @@ public class JndiDestinationResolver extends JndiLocatorSupport implements Cachi private DestinationResolver dynamicDestinationResolver = new DynamicDestinationResolver(); - private final Map destinationCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map destinationCache = new ConcurrentHashMap(); /** @@ -103,7 +102,7 @@ public class JndiDestinationResolver extends JndiLocatorSupport implements Cachi throws JMSException { Assert.notNull(destinationName, "Destination name must not be null"); - Destination dest = (Destination) this.destinationCache.get(destinationName); + Destination dest = this.destinationCache.get(destinationName); if (dest != null) { validateDestination(dest, destinationName, pubSubDomain); } diff --git a/org.springframework.orm/orm.iml b/org.springframework.orm/orm.iml index 79336087e15..b8744d92c18 100644 --- a/org.springframework.orm/orm.iml +++ b/org.springframework.orm/orm.iml @@ -1,233 +1,233 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateAccessor.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateAccessor.java index 45d2228abbe..7fe337d6595 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateAccessor.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateAccessor.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. @@ -331,12 +331,12 @@ public abstract class HibernateAccessor implements InitializingBean, BeanFactory if (existingTransaction) { FlushMode previousFlushMode = session.getFlushMode(); if (!previousFlushMode.lessThan(FlushMode.COMMIT)) { - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); return previousFlushMode; } } else { - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); } } else if (getFlushMode() == FLUSH_EAGER) { diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java index 27d78697d58..57c21c42d74 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java @@ -17,7 +17,6 @@ package org.springframework.orm.hibernate3; import java.sql.Connection; - import javax.sql.DataSource; import org.hibernate.ConnectionReleaseMode; @@ -111,7 +110,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * support nested transactions! Hence, do not expect Hibernate access code to * semantically participate in a nested transaction. * - *

Requires Hibernate 3.1 or later, as of Spring 2.5. + *

Requires Hibernate 3.2 or later, as of Spring 3.0. * * @author Juergen Hoeller * @since 1.2 @@ -255,11 +254,6 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * call Connection.setReadOnly(true) for read-only transactions * anymore either. If this flag is turned off, no cleanup of a JDBC Connection * is required after a transaction, since no Connection settings will get modified. - *

It is recommended to turn this flag off if running against Hibernate 3.1 - * and a connection pool that does not reset connection settings (for example, - * Jakarta Commons DBCP). To keep this flag turned on, you can set the - * "hibernate.connection.release_mode" property to "on_close" instead, - * or consider using a smarter connection pool (for example, C3P0). * @see java.sql.Connection#setTransactionIsolation * @see java.sql.Connection#setReadOnly */ @@ -297,14 +291,14 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana /** * Set whether to perform an early flush before proceeding with a commit. - *

Default is "false", performing an implicit flush as part of the - * actual commit step. Switch this to "true" in order to enforce an - * explicit flush before the before-commit synchronization phase, making - * flushed state visible to beforeCommit callbacks of registered + *

Default is "false", performing an implicit flush as part of the actual + * commit step. Switch this to "true" in order to enforce an explicit early + * flush right before the actual commit step. + *

An early flush happens before the before-commit synchronization phase, + * making flushed state visible to beforeCommit callbacks of registered * {@link org.springframework.transaction.support.TransactionSynchronization} - * objects. - *

Such explicit flush behavior is also consistent with Spring-driven - * flushing in a JTA transaction environment, so may also be enforced for + * objects. Such explicit flush behavior is consistent with Spring-driven + * flushing in a JTA transaction environment, so may also get enforced for * consistency with JTA transaction behavior. * @see #prepareForCommit */ @@ -533,7 +527,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana if (definition.isReadOnly() && txObject.isNewSession()) { // Just set to NEVER in case of a new Session for this transaction. - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); } if (!definition.isReadOnly() && !txObject.isNewSession()) { @@ -550,7 +544,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana // Register transaction timeout. int timeout = determineTimeout(definition); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { - // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1 + // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+ // Applies to all statements, also to inserts, updates and deletes! hibTx = session.getTransaction(); hibTx.setTimeout(timeout); @@ -633,7 +627,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana @Override protected void prepareForCommit(DefaultTransactionStatus status) { - if (this.earlyFlushBeforeCommit) { + if (this.earlyFlushBeforeCommit && status.isNewTransaction()) { HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction(); Session session = txObject.getSessionHolder().getSession(); if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) { @@ -645,7 +639,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana throw convertHibernateAccessException(ex); } finally { - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); } } } diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java index 12b1c0bf4cc..fbeb3b3b18b 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java @@ -26,7 +26,6 @@ import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.sql.DataSource; import javax.transaction.TransactionManager; @@ -90,7 +89,7 @@ import org.springframework.util.StringUtils; * {@link org.springframework.orm.hibernate3.support.OpenSessionInViewFilter} / * {@link org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor}. * - *

Requires Hibernate 3.1 or later. Note that this factory will use + *

Requires Hibernate 3.2 or later. Note that this factory will use * "on_close" as default Hibernate connection release mode, unless in the * case of a "jtaTransactionManager" specified, for the reason that * this is appropriate for most Spring-based applications (in particular when @@ -447,8 +446,6 @@ public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implemen * <prop key="com.mycompany.Product">read-only,myRegion</prop> * </props> * </property> - * Note that appending a cache region name (with a comma separator) is only - * supported on Hibernate 3.1, where this functionality is publically available. * @param entityCacheStrategies properties that define entity cache strategies, * with class names as keys and cache concurrency strategies as values * @see org.hibernate.cfg.Configuration#setCacheConcurrencyStrategy(String, String) @@ -469,8 +466,6 @@ public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implemen * <prop key="com.mycompany.Product.categories">read-only,myRegion</prop> * </props> * </property> - * Note that appending a cache region name (with a comma separator) is only - * supported on Hibernate 3.1, where this functionality is publically available. * @param collectionCacheStrategies properties that define collection cache strategies, * with collection roles as keys and cache concurrency strategies as values * @see org.hibernate.cfg.Configuration#setCollectionCacheConcurrencyStrategy(String, String) @@ -481,10 +476,8 @@ public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implemen /** * Specify the Hibernate event listeners to register, with listener types - * as keys and listener objects as values. - *

Instead of a single listener object, you can also pass in a list - * or set of listeners objects as value. However, this is only supported - * on Hibernate 3.1. + * as keys and listener objects as values. Instead of a single listener object, + * you can also pass in a list or set of listeners objects as value. *

See the Hibernate documentation for further details on listener types * and associated listener interfaces. * @param eventListeners Map with listener type Strings as keys and @@ -549,7 +542,7 @@ public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implemen try { if (isExposeTransactionAwareSessionFactory()) { - // Set Hibernate 3.1 CurrentSessionContext implementation, + // Set Hibernate 3.1+ CurrentSessionContext implementation, // providing the Spring-managed Session as current Session. // Can be overridden by a custom value for the corresponding Hibernate property. config.setProperty( diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java index 34a3ae9e718..b36df9a455a 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.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. @@ -100,7 +100,7 @@ public class OpenSessionInViewFilter extends OncePerRequestFilter { private boolean singleSession = true; - private FlushMode flushMode = FlushMode.NEVER; + private FlushMode flushMode = FlushMode.MANUAL; /** diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoOperations.java b/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoOperations.java index 737a8b5b002..71ddbec81ee 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoOperations.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoOperations.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. @@ -217,36 +217,6 @@ public interface JdoOperations { */ Collection detachCopyAll(Collection entities); - /** - * Reattach the given detached instance (for example, a web form object) with - * the current JDO transaction, merging its changes into the current persistence - * instance that represents the corresponding entity. - *

Note that as of JDO 2.0 final, this operation is equivalent to a - * makePersistent call, with the latter method returning the - * persistence instance. - * @param detachedEntity the detached instance to attach - * @return the corresponding persistent instance - * @deprecated in favor of {@link #makePersistent(Object)}. - * To be removed in Spring 3.0. - */ - @Deprecated - Object attachCopy(Object detachedEntity); - - /** - * Reattach the given detached instances (for example, web form objects) with - * the current JDO transaction, merging their changes into the current persistence - * instances that represent the corresponding entities. - *

Note that as of JDO 2.0 final, this operation is equivalent to a - * makePersistentAll call, with the latter method returning the - * persistence instance. - * @param detachedEntities the detached instances to reattach - * @return the corresponding persistent instances - * @deprecated in favor of {@link #makePersistentAll(java.util.Collection)}. - * To be removed in Spring 3.0. - */ - @Deprecated - Collection attachCopyAll(Collection detachedEntities); - /** * Flush all transactional modifications to the database. *

Only invoke this for selective eager flushing, for example when JDBC code diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java b/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java index e5b11611522..89567920ae8 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java @@ -377,24 +377,6 @@ public class JdoTemplate extends JdoAccessor implements JdoOperations { }, true); } - /** - * @deprecated in favor of {@link #makePersistent(Object)}. - * To be removed in Spring 3.0. - */ - @Deprecated - public Object attachCopy(Object detachedEntity) { - return makePersistent(detachedEntity); - } - - /** - * @deprecated in favor of {@link #makePersistentAll(java.util.Collection)}. - * To be removed in Spring 3.0. - */ - @Deprecated - public Collection attachCopyAll(Collection detachedEntities) { - return makePersistentAll(detachedEntities); - } - public void flush() throws DataAccessException { execute(new JdoCallback() { public Object doInJdo(PersistenceManager pm) throws JDOException { 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 0945d2587f0..33060d4ff19 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 @@ -21,12 +21,10 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; - import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; @@ -85,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; @@ -168,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); } @@ -262,10 +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 (Iterator it = vendorPropertyMap.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry entry : vendorPropertyMap.entrySet()) { if (!this.jpaPropertyMap.containsKey(entry.getKey())) { this.jpaPropertyMap.put(entry.getKey(), entry.getValue()); } @@ -422,7 +419,7 @@ public abstract class AbstractEntityManagerFactoryBean implements } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManagerFactory proxy. - return new Integer(System.identityHashCode(proxy)); + return System.identityHashCode(proxy); } else if (method.getDeclaringClass().isAssignableFrom(EntityManagerFactoryInfo.class)) { return method.invoke(this.entityManagerFactoryInfo, args); diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java index 747781913ac..71f83fb9247 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaDialect.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. @@ -102,7 +102,19 @@ public class HibernateJpaDialect extends DefaultJpaDialect { } protected Session getSession(EntityManager em) { - return ((HibernateEntityManager) em).getSession(); + if (em instanceof HibernateEntityManager) { + return ((HibernateEntityManager) em).getSession(); + } + else { + Object delegate = em.getDelegate(); + if (delegate instanceof Session) { + return (Session) delegate; + } + else { + throw new IllegalStateException( + "Cannot obtain native Hibernate Session from given JPA EntityManager: " + em.getClass()); + } + } } 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 a816a048d8f..8d7353ca0f6 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,7 +18,6 @@ package org.springframework.orm.jpa.vendor; import java.util.Map; import java.util.Properties; - import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; @@ -30,7 +29,7 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.InformixDialect; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.Oracle9Dialect; +import org.hibernate.dialect.Oracle9iDialect; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseDialect; @@ -42,7 +41,7 @@ import org.springframework.orm.jpa.JpaDialect; /** * {@link org.springframework.orm.jpa.JpaVendorAdapter} implementation for - * Hibernate EntityManager. Developed and tested against Hibernate 3.2. + * Hibernate EntityManager. Developed and tested against Hibernate 3.2 and 3.3. * *

Exposes Hibernate's persistence provider and EntityManager extension interface, * and supports {@link AbstractJpaVendorAdapter}'s common configuration settings. @@ -106,7 +105,7 @@ public class HibernateJpaVendorAdapter extends AbstractJpaVendorAdapter { case HSQL: return HSQLDialect.class; case INFORMIX: return InformixDialect.class; case MYSQL: return MySQLDialect.class; - case ORACLE: return Oracle9Dialect.class; // deprecated since Hibernate 3.2.5 - to be updated in Spring 3.0 + case ORACLE: return Oracle9iDialect.class; case POSTGRESQL: return PostgreSQLDialect.class; case SQL_SERVER: return SQLServerDialect.class; case SYBASE: return SybaseDialect.class; diff --git a/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java b/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java index 517a945f723..e957562d6dd 100644 --- a/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java +++ b/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.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. @@ -79,7 +79,7 @@ public class HibernateInterceptorTests extends TestCase { sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.close(); sessionControl.setReturnValue(null, 1); diff --git a/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java b/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java index 53c87b41db0..9dcb05b7f66 100644 --- a/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java +++ b/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java @@ -55,6 +55,7 @@ import org.hibernate.exception.JDBCConnectionException; import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.SQLGrammarException; +import org.springframework.beans.TestBean; import org.springframework.dao.CannotAcquireLockException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; @@ -62,7 +63,6 @@ import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.InvalidDataAccessResourceUsageException; import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.beans.TestBean; /** * @author Juergen Hoeller @@ -112,7 +112,7 @@ public class HibernateTemplateTests extends TestCase { sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.close(); sessionControl.setReturnValue(null, 1); @@ -1266,7 +1266,7 @@ public class HibernateTemplateTests extends TestCase { session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER); + sessionControl.setReturnValue(FlushMode.MANUAL); session.close(); sessionControl.setReturnValue(null, 1); sfControl.replay(); @@ -1578,7 +1578,7 @@ public class HibernateTemplateTests extends TestCase { sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.flush(); sessionControl.setVoidCallable(1); diff --git a/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java b/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java index 300061e0205..6bc7340a729 100644 --- a/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java +++ b/org.springframework.orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java @@ -323,7 +323,7 @@ public class HibernateTransactionManagerTests extends TestCase { sessionControl.setReturnValue(FlushMode.AUTO, 1); session.flush(); sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); tx.commit(); txControl.setVoidCallable(1); @@ -756,15 +756,15 @@ public class HibernateTransactionManagerTests extends TestCase { session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER, 1); + sessionControl.setReturnValue(FlushMode.MANUAL, 1); session.setFlushMode(FlushMode.AUTO); sessionControl.setVoidCallable(1); session.flush(); sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER, 1); + sessionControl.setReturnValue(FlushMode.MANUAL, 1); session.close(); sessionControl.setReturnValue(null, 1); sfControl.replay(); @@ -1078,7 +1078,7 @@ public class HibernateTransactionManagerTests extends TestCase { sfControl.setReturnValue(session, 1); session.beginTransaction(); sessionControl.setReturnValue(tx, 1); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.connection(); sessionControl.setReturnValue(con, 2); @@ -1239,10 +1239,10 @@ public class HibernateTransactionManagerTests extends TestCase { session.isOpen(); sessionControl.setReturnValue(true, 1); session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER, 1); + sessionControl.setReturnValue(FlushMode.MANUAL, 1); session.setFlushMode(FlushMode.AUTO); sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.connection(); sessionControl.setReturnValue(con, 3); @@ -1339,10 +1339,10 @@ public class HibernateTransactionManagerTests extends TestCase { session.isOpen(); sessionControl.setReturnValue(true, 2); session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER, 2); + sessionControl.setReturnValue(FlushMode.MANUAL, 2); session.setFlushMode(FlushMode.AUTO); sessionControl.setVoidCallable(2); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(2); session.isConnected(); sessionControl.setReturnValue(true, 2); @@ -1465,10 +1465,10 @@ public class HibernateTransactionManagerTests extends TestCase { tx2Control.setVoidCallable(1); session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER, 2); + sessionControl.setReturnValue(FlushMode.MANUAL, 2); session.setFlushMode(FlushMode.AUTO); sessionControl.setVoidCallable(2); - session.setFlushMode(FlushMode.NEVER); + session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(2); sfControl.replay(); diff --git a/org.springframework.orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java b/org.springframework.orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java index f5d40a09ca1..a0c5f020fa3 100644 --- a/org.springframework.orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java +++ b/org.springframework.orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.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. @@ -358,37 +358,6 @@ public class JdoTemplateTests extends TestCase { assertEquals(detached, jt.detachCopyAll(attached)); } - public void testAttachCopy() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.makePersistent("0x"); - pmControl.setReturnValue("0", 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - - JdoTemplate jt = new JdoTemplate(pmf); - assertEquals("0", jt.attachCopy("0x")); - } - - public void testAttachCopyAll() { - Collection detached = new HashSet(); - Collection attached = new HashSet(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.makePersistentAll(detached); - pmControl.setReturnValue(attached, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - - JdoTemplate jt = new JdoTemplate(pmf); - assertEquals(attached, jt.attachCopyAll(detached)); - } - public void testFlush() { pmf.getPersistenceManager(); pmfControl.setReturnValue(pm); diff --git a/org.springframework.test/src/main/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java b/org.springframework.test/src/main/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java index 909f8984650..28670fd4383 100644 --- a/org.springframework.test/src/main/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java +++ b/org.springframework.test/src/main/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java @@ -17,6 +17,7 @@ package org.springframework.mock.jndi; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import javax.naming.NamingException; @@ -32,7 +33,7 @@ import org.springframework.jndi.JndiTemplate; */ public class ExpectedLookupTemplate extends JndiTemplate { - private final Map jndiObjects = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map jndiObjects = new ConcurrentHashMap(); /** 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 7586fa32f13..527f05c150a 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 @@ -106,7 +106,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private String contentType; - private final Map parameters = new LinkedHashMap(16); + private final Map parameters = new LinkedHashMap(16); private String protocol = DEFAULT_PROTOCOL; @@ -344,13 +344,12 @@ public class MockHttpServletRequest implements HttpServletRequest { /** * Sets all provided parameters replacing any * existing values for the provided parameter names. To add without - * replacing existing values, use {@link #addParameters(Map)}. + * replacing existing values, use {@link #addParameters(java.util.Map)}. */ public void setParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); - for (Iterator it = params.keySet().iterator(); it.hasNext();) { - Object key = it.next(); - Assert.isInstanceOf(String.class, key, + for (Object key : params.keySet()) { + Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); if (value instanceof String) { @@ -360,8 +359,9 @@ public class MockHttpServletRequest implements HttpServletRequest { this.setParameter((String) key, (String[]) value); } else { - throw new IllegalArgumentException("Parameter map value must be single value " + - " or array of type [" + String.class.getName() + "]"); + throw new IllegalArgumentException( + "Parameter map value must be single value " + " or array of type [" + String.class.getName() + + "]"); } } } @@ -382,7 +382,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void addParameter(String name, String[] values) { Assert.notNull(name, "Parameter name must not be null"); - 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); @@ -397,13 +397,12 @@ public class MockHttpServletRequest implements HttpServletRequest { /** * Adds all provided parameters without replacing * any existing values. To replace existing values, use - * {@link #setParameters(Map)}. + * {@link #setParameters(java.util.Map)}. */ public void addParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); - for (Iterator it = params.keySet().iterator(); it.hasNext();) { - Object key = it.next(); - Assert.isInstanceOf(String.class, key, + for (Object key : params.keySet()) { + Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); if (value instanceof String) { @@ -428,7 +427,7 @@ public class MockHttpServletRequest implements HttpServletRequest { } /** - * Removes all existing parameters. + * Removes all existing parameters. */ public void removeAllParameters() { this.parameters.clear(); @@ -436,7 +435,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public String getParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - String[] arr = (String[]) this.parameters.get(name); + String[] arr = this.parameters.get(name); return (arr != null && arr.length > 0 ? arr[0] : null); } @@ -446,7 +445,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public String[] getParameterValues(String name) { Assert.notNull(name, "Parameter name must not be null"); - return (String[]) this.parameters.get(name); + return this.parameters.get(name); } public Map getParameterMap() { @@ -750,14 +749,6 @@ public class MockHttpServletRequest implements HttpServletRequest { return this.remoteUser; } - /** - * @deprecated in favor of addUserRole - * @see #addUserRole - */ - public void addRole(String role) { - addUserRole(role); - } - public void addUserRole(String role) { this.userRoles.add(role); } diff --git a/org.springframework.test/src/main/java/org/springframework/test/context/TestContext.java b/org.springframework.test/src/main/java/org/springframework/test/context/TestContext.java index eb7e71b56ac..1775c59a0f5 100644 --- a/org.springframework.test/src/main/java/org/springframework/test/context/TestContext.java +++ b/org.springframework.test/src/main/java/org/springframework/test/context/TestContext.java @@ -34,8 +34,8 @@ import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** - * TestContext encapsulates the context in which a test is executed, agnostic of - * the actual testing framework in use. + * TestContext encapsulates the context in which a test is executed, + * agnostic of the actual testing framework in use. * * @author Sam Brannen * @author Juergen Hoeller @@ -43,12 +43,14 @@ import org.springframework.util.ObjectUtils; */ public class TestContext extends AttributeAccessorSupport { - private static final String DEFAULT_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.support.GenericXmlContextLoader"; - private static final long serialVersionUID = -5827157174866681233L; + private static final String DEFAULT_CONTEXT_LOADER_CLASS_NAME = + "org.springframework.test.context.support.GenericXmlContextLoader"; + private static final Log logger = LogFactory.getLog(TestContext.class); + private final ContextCache contextCache; private final ContextLoader contextLoader; @@ -117,8 +119,7 @@ public class TestContext extends AttributeAccessorSupport { /** * Retrieve {@link ApplicationContext} resource locations for the supplied * {@link Class class}, using the supplied {@link ContextLoader} to - * {@link ContextLoader#processLocations(Class, String...) process} the - * locations. + * {@link ContextLoader#processLocations(Class, String...) process} the locations. *

Note that the * {@link ContextConfiguration#inheritLocations() inheritLocations} flag of * {@link ContextConfiguration @ContextConfiguration} will be taken into @@ -160,23 +161,21 @@ public class TestContext extends AttributeAccessorSupport { } /** - * Build an {@link ApplicationContext} for this test context using the - * configured {@link #getContextLoader() ContextLoader} and - * {@link #getLocations() resource locations}. + * Build an ApplicationContext for this test context using the + * configured ContextLoader and resource locations. * @throws Exception if an error occurs while building the application context */ private ApplicationContext loadApplicationContext() throws Exception { - Assert.notNull(getContextLoader(), - "Can not build an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration."); - Assert.notNull(getLocations(), - "Can not build an ApplicationContext with a NULL 'locations' array. Consider annotating your test class with @ContextConfiguration."); - return getContextLoader().loadContext(getLocations()); + Assert.notNull(this.contextLoader, "Can not build an ApplicationContext with a NULL 'contextLoader'. " + + "Consider annotating your test class with @ContextConfiguration."); + Assert.notNull(this.locations, "Can not build an ApplicationContext with a NULL 'locations' array. " + + "Consider annotating your test class with @ContextConfiguration."); + return this.contextLoader.loadContext(this.locations); } /** * Convert the supplied context key to a String * representation for use in caching, logging, etc. - * @param key the context key to convert to a String */ private String contextKeyString(Serializable key) { return ObjectUtils.nullSafeToString(key); @@ -190,50 +189,19 @@ public class TestContext extends AttributeAccessorSupport { * @throws IllegalStateException if an error occurs while retrieving the application context */ public ApplicationContext getApplicationContext() { - ApplicationContext context = null; - ContextCache cache = getContextCache(); - synchronized (cache) { - context = cache.get(contextKeyString(getLocations())); + synchronized (this.contextCache) { + ApplicationContext context = this.contextCache.get(contextKeyString(this.locations)); if (context == null) { try { context = loadApplicationContext(); - cache.put(contextKeyString(getLocations()), context); + this.contextCache.put(contextKeyString(this.locations), context); } catch (Exception ex) { throw new IllegalStateException("Failed to load ApplicationContext", ex); } } + return context; } - return context; - } - - /** - * Get the {@link ContextCache context cache} for this test context. - * @return the context cache (never null) - */ - ContextCache getContextCache() { - return this.contextCache; - } - - /** - * Get the {@link ContextLoader} to use for loading the - * {@link ApplicationContext} for this test context. - * @return the context loader. May be null if the current - * test context is not configured to use an application context. - */ - ContextLoader getContextLoader() { - return this.contextLoader; - } - - /** - * Get the resource locations to use for loading the - * {@link ApplicationContext} for this test context. - * @return the application context resource locations. - * May be null if the current test context is - * not configured to use an application context. - */ - String[] getLocations() { - return this.locations; } /** @@ -245,7 +213,7 @@ public class TestContext extends AttributeAccessorSupport { } /** - * Gets the current {@link Object test instance} for this test context. + * Get the current {@link Object test instance} for this test context. *

Note: this is a mutable property. * @return the current test instance (may be null) * @see #updateState(Object,Method,Throwable) @@ -255,7 +223,7 @@ public class TestContext extends AttributeAccessorSupport { } /** - * Gets the current {@link Method test method} for this test context. + * Get the current {@link Method test method} for this test context. *

Note: this is a mutable property. * @return the current test method (may be null) * @see #updateState(Object, Method, Throwable) @@ -265,7 +233,7 @@ public class TestContext extends AttributeAccessorSupport { } /** - * Gets the {@link Throwable exception} that was thrown during execution of + * Get the {@link Throwable exception} that was thrown during execution of * the {@link #getTestMethod() test method}. *

Note: this is a mutable property. * @return the exception that was thrown, or null if no @@ -283,36 +251,31 @@ public class TestContext extends AttributeAccessorSupport { * modified the context (for example, by replacing a bean definition). */ public void markApplicationContextDirty() { - getContextCache().setDirty(contextKeyString(getLocations())); + this.contextCache.setDirty(contextKeyString(this.locations)); } /** - * Updates this test context to reflect the state of the currently executing test. + * Update this test context to reflect the state of the currently executing test. * @param testInstance the current test instance (may be null) * @param testMethod the current test method (may be null) * @param testException the exception that was thrown in the test method, * or null if no exception was thrown */ - synchronized void updateState(Object testInstance, Method testMethod, Throwable testException) { + void updateState(Object testInstance, Method testMethod, Throwable testException) { this.testInstance = testInstance; this.testMethod = testMethod; this.testException = testException; } /** - * Provides a string representation of this test context's - * {@link #getTestClass() test class}, - * {@link #getLocations() application context resource locations}, - * {@link #getTestInstance() test instance}, - * {@link #getTestMethod() test method}, and - * {@link #getTestException() test exception}. + * Provide a String representation of this test context's state. */ @Override public String toString() { return new ToStringCreator(this). - append("testClass", getTestClass()). - append("locations", getLocations()).append("testInstance", getTestInstance()). - append("testMethod", getTestMethod()).append("testException", getTestException()). + append("testClass", this.testClass). + append("locations", this.locations).append("testInstance", this.testInstance). + append("testMethod", this.testMethod).append("testException", this.testException). toString(); } diff --git a/org.springframework.test/test.iml b/org.springframework.test/test.iml index 29de2696dcb..e3f020edcbe 100644 --- a/org.springframework.test/test.iml +++ b/org.springframework.test/test.iml @@ -1,158 +1,158 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 2b127406e65..398f9ad69ab 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -48,6 +48,8 @@ import org.springframework.beans.PropertyValue; import org.springframework.beans.TestBean; import org.springframework.beans.TypeConverter; import org.springframework.beans.TypeMismatchException; +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -775,8 +777,12 @@ public class DefaultListableBeanFactoryTests extends TestCase { public void testCustomEditor() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); - lbf.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true)); + lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { + public void registerCustomEditors(PropertyEditorRegistry registry) { + NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); + registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true)); + } + }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("myFloat", "1,1"); lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, pvs)); @@ -786,8 +792,12 @@ public class DefaultListableBeanFactoryTests extends TestCase { public void testCustomEditorWithBeanReference() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); - NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); - lbf.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true)); + lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { + public void registerCustomEditors(PropertyEditorRegistry registry) { + NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); + registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true)); + } + }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("myFloat", new RuntimeBeanReference("myFloat")); lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, pvs)); diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/NoOpScope.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/NoOpScope.java index c681dabc7a1..fd92462e12d 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/NoOpScope.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/NoOpScope.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. @@ -34,6 +34,10 @@ public class NoOpScope implements Scope { public void registerDestructionCallback(String name, Runnable callback) { } + public Object resolveContextualObject(String key) { + return null; + } + public String getConversationId() { return null; } diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java index 3aedfb8de71..42fb9fd89d5 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.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,6 +64,10 @@ public class SimpleMapScope implements Scope, Serializable { this.callbacks.add(callback); } + public Object resolveContextualObject(String key) { + return null; + } + public void close() { for (Iterator it = this.callbacks.iterator(); it.hasNext();) { Runnable runnable = (Runnable) it.next(); diff --git a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java index 37782debb05..4632b985af4 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java @@ -32,6 +32,8 @@ import junit.framework.TestCase; import org.springframework.beans.GenericBean; import org.springframework.beans.GenericIntegerBean; import org.springframework.beans.GenericSetOfIntegerBean; +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.core.io.ClassPathResource; @@ -341,7 +343,11 @@ public class BeanFactoryGenericsTests extends TestCase { public void testGenericMapWithCollectionValueConstructor() throws MalformedURLException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - bf.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)); + bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { + public void registerCustomEditors(PropertyEditorRegistry registry) { + registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)); + } + }); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); Map input = new HashMap(); @@ -486,7 +492,11 @@ public class BeanFactoryGenericsTests extends TestCase { public void testGenericMapWithCollectionValueFactoryMethod() throws MalformedURLException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - bf.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)); + bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { + public void registerCustomEditors(PropertyEditorRegistry registry) { + registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)); + } + }); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); diff --git a/org.springframework.testsuite/src/test/java/org/springframework/jmx/access/CommonsAttributesMBeanProxyFactoryBeanTests.java b/org.springframework.testsuite/src/test/java/org/springframework/jmx/access/CommonsAttributesMBeanProxyFactoryBeanTests.java deleted file mode 100644 index db05ccd709f..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/jmx/access/CommonsAttributesMBeanProxyFactoryBeanTests.java +++ /dev/null @@ -1,94 +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.jmx.access; - -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.xml.XmlBeanFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.jmx.AbstractJmxTests; -import org.springframework.jmx.IJmxTestBean; -import org.springframework.jmx.support.ObjectNameManager; - -/** - * Tests creation of JMX MBean proxies. - * - * @author Rob Harrop - */ -public class CommonsAttributesMBeanProxyFactoryBeanTests extends AbstractJmxTests { - - private static final String OBJECT_NAME = "bean:name=testBean1"; - - protected ObjectName getObjectName() throws Exception { - return ObjectNameManager.getInstance(OBJECT_NAME); - } - - public void testProxyFactory() throws Exception { - MBeanProxyFactoryBean fb = getProxyFactory(); - fb.setProxyInterface(IJmxTestBean.class); - fb.afterPropertiesSet(); - - IJmxTestBean bean = (IJmxTestBean) fb.getObject(); - assertNotNull("Proxy should not be null", bean); - } - - public void testInvalidJdkProxy() throws Exception { - MBeanProxyFactoryBean fb = getProxyFactory(); - try { - fb.afterPropertiesSet(); - fail("Should not be able to create JDK proxy with no proxy interfaces"); - } - catch (Exception ex) { - // expected - } - } - - public void testWithLocatedMBeanServer() throws Exception { - MBeanProxyFactoryBean fb = new MBeanProxyFactoryBean(); - fb.setProxyInterface(IJmxTestBean.class); - fb.setObjectName(OBJECT_NAME); - fb.afterPropertiesSet(); - IJmxTestBean proxy = (IJmxTestBean)fb.getObject(); - assertNotNull("Proxy should not be null", proxy); - assertEquals("Incorrect name value", "TEST", proxy.getName()); - } - - public void testProxyFactoryBeanWithAutodetect() throws Exception { - try { - XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("proxyFactoryBean.xml", getClass())); - bf.preInstantiateSingletons(); - } - catch (BeanCreationException ex) { - if (ex.getCause().getClass() == MBeanInfoRetrievalException.class) { - fail("MBeanProxyFactoryBean should be ignored by MBeanExporter when running autodetect process"); - } - else { - throw ex; - } - } - } - - private MBeanProxyFactoryBean getProxyFactory() throws MalformedObjectNameException { - MBeanProxyFactoryBean fb = new MBeanProxyFactoryBean(); - fb.setServer(getServer()); - fb.setObjectName(OBJECT_NAME); - return fb; - } - -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/jmx/access/proxyFactoryBean.xml b/org.springframework.testsuite/src/test/java/org/springframework/jmx/access/proxyFactoryBean.xml deleted file mode 100644 index d7d5254f1c3..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/jmx/access/proxyFactoryBean.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.springframework.jmx.IJmxTestBean - - - bean:name=proxyTestBean1 - - - - - - TEST - - - 100 - - - - diff --git a/org.springframework.testsuite/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/org.springframework.testsuite/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index 1005694df80..a9b24d0c9ed 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -21,7 +21,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.management.Attribute; import javax.management.InstanceNotFoundException; import javax.management.JMException; diff --git a/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/RepeatedSpringMethodRoadieTests.java b/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/RepeatedSpringMethodRoadieTests.java deleted file mode 100644 index c0de6008f38..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/RepeatedSpringMethodRoadieTests.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2002-2007 the original author 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.test.context.junit4; - -import static org.junit.Assert.assertEquals; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; - -import org.easymock.MockControl; -import org.easymock.classextension.MockClassControl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.internal.runners.TestClass; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import org.springframework.test.annotation.Repeat; -import org.springframework.test.annotation.Timed; -import org.springframework.test.context.TestContextManager; - -/** - * Unit test for {@link SpringMethodRoadie} which focuses on proper support of - * the {@link Repeat @Repeat} annotation. - * - * @author Sam Brannen - * @since 2.5 - */ -@RunWith(Parameterized.class) -public class RepeatedSpringMethodRoadieTests { - - protected final String methodName; - protected final int expectedNumInvocations; - - protected final MockControl notifierMockControl = MockClassControl.createNiceControl(RunNotifier.class); - protected final RunNotifier notifier = (RunNotifier) this.notifierMockControl.getMock(); - - protected final MockControl descriptionMockControl = MockClassControl.createNiceControl(Description.class); - protected final Description description = (Description) this.descriptionMockControl.getMock(); - - protected final MockControl testContextManagerMockControl = MockClassControl.createNiceControl(TestContextManager.class); - protected final TestContextManager testContextManager = (TestContextManager) this.testContextManagerMockControl.getMock(); - - - public RepeatedSpringMethodRoadieTests(final String methodName, final int expectedNumInvocations) throws Exception { - this.methodName = methodName; - this.expectedNumInvocations = expectedNumInvocations; - } - - @Parameters - public static Collection repetitionData() { - return Arrays.asList(new Object[][] { { "testNonAnnotated", 1 }, { "testNegativeRepeatValue", 1 }, - { "testDefaultRepeatValue", 1 }, { "testRepeatedFiveTimes", 5 } }); - } - - @Test - public void assertRepetitions() throws Exception { - - final Class clazz = RepeatedTestCase.class; - final TestClass testClass = new TestClass(clazz); - final RepeatedTestCase testInstance = clazz.newInstance(); - final Method method = clazz.getMethod(this.methodName, (Class[]) null); - final SpringTestMethod testMethod = new SpringTestMethod(method, testClass); - - new SpringMethodRoadie(this.testContextManager, testInstance, testMethod, this.notifier, this.description).run(); - - assertEquals("Verifying number of @Test invocations for test method [" + this.methodName + "].", - this.expectedNumInvocations, testInstance.invocationCount); - assertEquals("Verifying number of @Before invocations for test method [" + this.methodName + "].", - this.expectedNumInvocations, testInstance.beforeCount); - assertEquals("Verifying number of @After invocations for test method [" + this.methodName + "].", - this.expectedNumInvocations, testInstance.afterCount); - } - - - protected static class RepeatedTestCase { - - int beforeCount = 0; - int afterCount = 0; - int invocationCount = 0; - - - @Before - protected void setUp() throws Exception { - this.beforeCount++; - } - - @After - protected void tearDown() throws Exception { - this.afterCount++; - } - - @Test - @Timed(millis = 10000) - public void testNonAnnotated() { - this.invocationCount++; - } - - @Test - @Repeat(-5) - @Timed(millis = 10000) - public void testNegativeRepeatValue() { - this.invocationCount++; - } - - @Test - @Repeat - @Timed(millis = 10000) - public void testDefaultRepeatValue() { - this.invocationCount++; - } - - @Test - @Repeat(5) - @Timed(millis = 10000) - public void testRepeatedFiveTimes() { - this.invocationCount++; - } - } - -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java b/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java index 34b2e967511..8484f1a720c 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java @@ -49,8 +49,6 @@ StandardJUnit4FeaturesTests.class, StandardJUnit4FeaturesSpringRunnerTests.class, -RepeatedSpringMethodRoadieTests.class, - EnabledAndIgnoredSpringRunnerTests.class, HardCodedProfileValueSourceSpringRunnerTests.class, diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/bind/RequestUtilsTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/bind/RequestUtilsTests.java deleted file mode 100644 index f2569f8bea3..00000000000 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/bind/RequestUtilsTests.java +++ /dev/null @@ -1,413 +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.web.bind; - -import javax.servlet.ServletException; - -import junit.framework.TestCase; - -import org.springframework.mock.web.MockHttpServletRequest; - -/** - * @author Juergen Hoeller - * @since 06.08.2003 - */ -public class RequestUtilsTests extends TestCase { - - public void testRejectMethod() throws ServletRequestBindingException { - String methodGet = "GET"; - String methodPost = "POST"; - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setMethod(methodPost); - - try { - RequestUtils.rejectRequestMethod(request, methodGet); - } catch (ServletException ex) { - fail("Shouldn't have thrown ServletException"); - } - try { - RequestUtils.rejectRequestMethod(request, methodPost); - fail("Should have thrown ServletException"); - } catch (ServletException ex) { - } - } - - public void testIntParameter() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param1", "5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertEquals(RequestUtils.getIntParameter(request, "param1"), new Integer(5)); - assertEquals(RequestUtils.getIntParameter(request, "param1", 6), 5); - assertEquals(RequestUtils.getRequiredIntParameter(request, "param1"), 5); - - assertEquals(RequestUtils.getIntParameter(request, "param2", 6), 6); - try { - RequestUtils.getRequiredIntParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - assertEquals(RequestUtils.getIntParameter(request, "param3"), null); - assertEquals(RequestUtils.getIntParameter(request, "param3", 6), 6); - try { - RequestUtils.getRequiredIntParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - try { - RequestUtils.getRequiredIntParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testIntParameters() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param", new String[] {"1", "2", "3"}); - - request.addParameter("param2", "1"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - int[] array = new int[] { 1, 2, 3 }; - int[] values = RequestUtils.getRequiredIntParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - - try { - RequestUtils.getRequiredIntParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - } - - public void testLongParameter() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param1", "5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertEquals(RequestUtils.getLongParameter(request, "param1"), new Long(5L)); - assertEquals(RequestUtils.getLongParameter(request, "param1", 6L), 5L); - assertEquals(RequestUtils.getRequiredIntParameter(request, "param1"), 5L); - - assertEquals(RequestUtils.getLongParameter(request, "param2", 6L), 6L); - try { - RequestUtils.getRequiredLongParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - assertEquals(RequestUtils.getLongParameter(request, "param3"), null); - assertEquals(RequestUtils.getLongParameter(request, "param3", 6L), 6L); - try { - RequestUtils.getRequiredLongParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - try { - RequestUtils.getRequiredLongParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testLongParameters() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setParameter("param", new String[] {"1", "2", "3"}); - - request.setParameter("param2", "0"); - request.setParameter("param2", "1"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - long[] array = new long[] { 1L, 2L, 3L }; - long[] values = RequestUtils.getRequiredLongParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - - try { - RequestUtils.getRequiredLongParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - request.setParameter("param2", new String[] {"1", "2"}); - values = RequestUtils.getRequiredLongParameters(request, "param2"); - assertEquals(2, values.length); - assertEquals(1, values[0]); - assertEquals(2, values[1]); - - request.removeParameter("param2"); - try { - RequestUtils.getRequiredLongParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testFloatParameter() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param1", "5.5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertTrue(RequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f))); - assertTrue(RequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f); - assertTrue(RequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f); - - assertTrue(RequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f); - try { - RequestUtils.getRequiredFloatParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - assertTrue(RequestUtils.getFloatParameter(request, "param3") == null); - assertTrue(RequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f); - try { - RequestUtils.getRequiredFloatParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - try { - RequestUtils.getRequiredFloatParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testFloatParameters() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param", new String[] {"1.5", "2.5", "3"}); - - request.addParameter("param2", "1.5"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - float[] array = new float[] { 1.5F, 2.5F, 3 }; - float[] values = RequestUtils.getRequiredFloatParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i], 0); - } - - try { - RequestUtils.getRequiredFloatParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testDoubleParameter() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param1", "5.5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertTrue(RequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5))); - assertTrue(RequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5); - assertTrue(RequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5); - - assertTrue(RequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5); - try { - RequestUtils.getRequiredDoubleParameter(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - assertTrue(RequestUtils.getDoubleParameter(request, "param3") == null); - assertTrue(RequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5); - try { - RequestUtils.getRequiredDoubleParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - try { - RequestUtils.getRequiredDoubleParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testDoubleParameters() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param", new String[] {"1.5", "2.5", "3"}); - - request.addParameter("param2", "1.5"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - double[] array = new double[] { 1.5, 2.5, 3 }; - double[] values = RequestUtils.getRequiredDoubleParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i], 0); - } - - try { - RequestUtils.getRequiredDoubleParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testBooleanParameter() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param1", "true"); - request.addParameter("param2", "e"); - request.addParameter("param4", "yes"); - request.addParameter("param5", "1"); - request.addParameter("paramEmpty", ""); - - assertTrue(RequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE)); - assertTrue(RequestUtils.getBooleanParameter(request, "param1", false)); - assertTrue(RequestUtils.getRequiredBooleanParameter(request, "param1")); - - assertFalse(RequestUtils.getBooleanParameter(request, "param2", true)); - assertFalse(RequestUtils.getRequiredBooleanParameter(request, "param2")); - - assertTrue(RequestUtils.getBooleanParameter(request, "param3") == null); - assertTrue(RequestUtils.getBooleanParameter(request, "param3", true)); - try { - RequestUtils.getRequiredBooleanParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - assertTrue(RequestUtils.getBooleanParameter(request, "param4", false)); - assertTrue(RequestUtils.getRequiredBooleanParameter(request, "param4")); - - assertTrue(RequestUtils.getBooleanParameter(request, "param5", false)); - assertTrue(RequestUtils.getRequiredBooleanParameter(request, "param5")); - try { - RequestUtils.getRequiredBooleanParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testBooleanParameters() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param", new String[] {"true", "yes", "off", "1", "bogus"}); - - request.addParameter("param2", "false"); - request.addParameter("param2", "true"); - request.addParameter("param2", ""); - - boolean[] array = new boolean[] { true, true, false, true, false }; - boolean[] values = RequestUtils.getRequiredBooleanParameters(request, "param"); - assertEquals(5, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - - try { - RequestUtils.getRequiredBooleanParameters(request, "param2"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - - public void testStringParameter() throws ServletRequestBindingException { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter("param1", "str"); - request.addParameter("paramEmpty", ""); - - assertEquals(RequestUtils.getStringParameter(request, "param1"), "str"); - assertEquals(RequestUtils.getStringParameter(request, "param1", "string"), "str"); - assertEquals(RequestUtils.getRequiredStringParameter(request, "param1"), "str"); - - assertEquals(RequestUtils.getStringParameter(request, "param3"), null); - assertEquals(RequestUtils.getStringParameter(request, "param3", "string"), "string"); - try { - RequestUtils.getRequiredStringParameter(request, "param3"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - - try { - RequestUtils.getStringParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - try { - RequestUtils.getRequiredStringParameter(request, "paramEmpty"); - fail("Should have thrown ServletRequestBindingException"); - } - catch (ServletRequestBindingException ex) { - // expected - } - } - -} diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/context/ContextLoaderTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/context/ContextLoaderTests.java index 1eb8fbabf29..0b175f16c1a 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/context/ContextLoaderTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/context/ContextLoaderTests.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. @@ -103,24 +103,6 @@ public class ContextLoaderTests extends TestCase { assertEquals("customizeContext() should have been called.", expectedContents, buffer.toString()); } - public void testContextLoaderServletWithDefaultContext() throws Exception { - MockServletContext sc = new MockServletContext(""); - sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, - "/org/springframework/web/context/WEB-INF/applicationContext.xml"); - HttpServlet servlet = new ContextLoaderServlet(); - ServletConfig config = new MockServletConfig(sc, "test"); - servlet.init(config); - WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - assertTrue("Correct WebApplicationContext exposed in ServletContext", - context instanceof XmlWebApplicationContext); - LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle"); - assertTrue("Not destroyed", !lb.isDestroyed()); - assertFalse(context.containsBean("beans1.bean1")); - assertFalse(context.containsBean("beans1.bean2")); - servlet.destroy(); - assertTrue("Destroyed", lb.isDestroyed()); - } - public void testContextLoaderWithDefaultContextAndParent() throws Exception { MockServletContext sc = new MockServletContext(""); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java index 8e36eb9e12e..b30b02e1123 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java @@ -35,7 +35,6 @@ import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.mvc.LastModified; import org.springframework.web.servlet.mvc.SimpleFormController; -import org.springframework.web.servlet.mvc.throwaway.ThrowawayController; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.servlet.theme.AbstractThemeResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -56,8 +55,6 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext { registerSingleton("/locale.do", LocaleChecker.class); - registerPrototype("/throwaway.do", TestThrowawayController.class); - addMessage("test", Locale.ENGLISH, "test message"); addMessage("test", Locale.CANADA, "Canadian & test message"); addMessage("testArgs", Locale.ENGLISH, "test {0} message {1}"); @@ -118,24 +115,4 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext { } } - - public static class TestThrowawayController implements ThrowawayController { - - public static int counter = 0; - - private int myInt; - - public TestThrowawayController() { - counter++; - } - - public void setMyInt(int myInt) { - this.myInt = myInt; - } - - public ModelAndView execute() throws Exception { - return new ModelAndView("view" + this.myInt); - } - } - } diff --git a/org.springframework.testsuite/src/test/java/org/springframework/web/util/Log4jWebConfigurerTests.java b/org.springframework.testsuite/src/test/java/org/springframework/web/util/Log4jWebConfigurerTests.java index aebe9edc148..1068788a8f2 100644 --- a/org.springframework.testsuite/src/test/java/org/springframework/web/util/Log4jWebConfigurerTests.java +++ b/org.springframework.testsuite/src/test/java/org/springframework/web/util/Log4jWebConfigurerTests.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. @@ -118,21 +118,4 @@ public class Log4jWebConfigurerTests extends TestCase { assertTrue(MockLog4jAppender.closeCalled); } - public void testLog4jConfigServlet() throws ServletException { - Log4jConfigServlet servlet = new Log4jConfigServlet(); - - MockServletContext sc = new MockServletContext("", new FileSystemResourceLoader()); - sc.addInitParameter(Log4jWebConfigurer.CONFIG_LOCATION_PARAM, - "test/org/springframework/util/testlog4j.properties"); - servlet.init(new MockServletConfig(sc)); - - try { - doTestLogOutput(); - } - finally { - servlet.destroy(); - } - assertTrue(MockLog4jAppender.closeCalled); - } - } diff --git a/org.springframework.testsuite/testsuite.iml b/org.springframework.testsuite/testsuite.iml index 11ecc5635d2..da030426db5 100644 --- a/org.springframework.testsuite/testsuite.iml +++ b/org.springframework.testsuite/testsuite.iml @@ -1,589 +1,569 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.transaction/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointManager.java b/org.springframework.transaction/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointManager.java index 2938a7b03cc..88a2c75cd85 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointManager.java +++ b/org.springframework.transaction/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointManager.java @@ -258,9 +258,7 @@ public class GenericMessageEndpointManager implements InitializingBean, Lifecycl getResourceAdapter().endpointActivation(getMessageEndpointFactory(), getActivationSpec()); } catch (ResourceException ex) { - IllegalStateException wrapped = new IllegalStateException("Could not activate message endpoint"); - wrapped.initCause(ex); - throw wrapped; + throw new IllegalStateException("Could not activate message endpoint", ex); } this.running = true; } diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java index 25a642c5647..86c6b528124 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java +++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java @@ -19,13 +19,12 @@ package org.springframework.transaction.interceptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.BridgeMethodResolver; -import org.springframework.core.CollectionFactory; -import org.springframework.core.JdkVersion; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -55,7 +54,7 @@ public abstract class AbstractFallbackTransactionAttributeSource implements Tran * Canonical value held in cache to indicate no transaction attribute was * found for this method, and we don't need to look again. */ - private final static Object NULL_TRANSACTION_ATTRIBUTE = new Object(); + private final static TransactionAttribute NULL_TRANSACTION_ATTRIBUTE = new DefaultTransactionAttribute(); /** @@ -70,7 +69,7 @@ public abstract class AbstractFallbackTransactionAttributeSource implements Tran *

As this base class is not marked Serializable, the cache will be recreated * after serialization - provided that the concrete subclass is Serializable. */ - final Map attributeCache = CollectionFactory.createConcurrentMapIfPossible(16); + final Map attributeCache = new ConcurrentHashMap(); /** @@ -139,9 +138,7 @@ public abstract class AbstractFallbackTransactionAttributeSource implements Tran // If the target class is null, the method will be unchanged. Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the original method. - if (JdkVersion.isAtLeastJava15()) { - specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); - } + specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); // First try is the method in the target class. TransactionAttribute txAtt = findTransactionAttribute(specificMethod); diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java index 6923e95f10d..244faf9d4f3 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java +++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttribute.java @@ -161,7 +161,7 @@ public class RuleBasedTransactionAttribute extends DefaultTransactionAttribute i @Override public String toString() { - StringBuffer result = getDefinitionDescription(); + StringBuilder result = getDefinitionDescription(); if (this.rollbackRules != null) { for (Iterator it = this.rollbackRules.iterator(); it.hasNext();) { RollbackRuleAttribute rule = (RollbackRuleAttribute) it.next(); diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java index 63b944a7768..9830dbcedee 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java +++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java @@ -143,7 +143,6 @@ import org.springframework.util.StringUtils; * @see #setTransactionManagerName * @see #setTransactionManager * @see JotmFactoryBean - * @see WebSphereTransactionManagerFactoryBean * @see WebLogicJtaTransactionManager */ public class JtaTransactionManager extends AbstractPlatformTransactionManager diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereTransactionManagerFactoryBean.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereTransactionManagerFactoryBean.java deleted file mode 100644 index 8c8c8672892..00000000000 --- a/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereTransactionManagerFactoryBean.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2002-2007 the original author 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.transaction.jta; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import javax.transaction.TransactionManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.transaction.TransactionSystemException; - -/** - * {@link org.springframework.beans.factory.FactoryBean} that retrieves - * the JTA TransactionManager for IBM's WebSphere application servers - * (versions 5.1, 6.0 and 6.1). - * - *

Uses WebSphere's static accessor methods to obtain the internal JTA - * TransactionManager. This is known to work reliably on all tested WebSphere - * versions; however, access to the internal TransactionManager facility - * is not officially supported by IBM. - * - *

In combination with Spring's JtaTransactionManager, this FactoryBean - * can be used to enable transaction suspension (PROPAGATION_REQUIRES_NEW, - * PROPAGATION_NOT_SUPPORTED) on WebSphere: - * - *

- * <bean id="wsJtaTm" class="org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean"/>
- *
- * <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
- *   <property name="transactionManager ref="wsJtaTm"/>
- * </bean>
- * - * Note that Spring's JtaTransactionManager will continue to use the JTA - * UserTransaction for standard transaction demarcation, as defined by - * standard J2EE. It will only use the provided WebSphere TransactionManager - * in case of actual transaction suspension needs. If you do not require - * transaction suspension in the first place, do not bother with this FactoryBean. - * - *

NOTE: On recent WebSphere 6.0.x and 6.1.x versions, this class has - * been superseded by the {@link WebSphereUowTransactionManager} class, which - * uses IBM's official UOWManager API facility for transaction suspension. - * The WebSphereUowTransactionManager class is a direct replacement for a - * standard JtaTransactionManager definition, without further configuration. - * - * @author Juergen Hoeller - * @since 21.01.2004 - * @see JtaTransactionManager#setTransactionManager - * @see com.ibm.ws.Transaction.TransactionManagerFactory#getTransactionManager - * @see WebSphereUowTransactionManager - */ -public class WebSphereTransactionManagerFactoryBean implements FactoryBean { - - private static final String FACTORY_CLASS_5_1 = "com.ibm.ws.Transaction.TransactionManagerFactory"; - - - protected final Log logger = LogFactory.getLog(getClass()); - - private final TransactionManager transactionManager; - - - /** - * This constructor retrieves the WebSphere TransactionManager factory class, - * so we can get access to the JTA TransactionManager. - */ - public WebSphereTransactionManagerFactoryBean() throws TransactionSystemException { - try { - // Using the thread context class loader for compatibility with the WSAD test server. - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(FACTORY_CLASS_5_1); - Method method = clazz.getMethod("getTransactionManager", (Class[]) null); - this.transactionManager = (TransactionManager) method.invoke(null, (Object[]) null); - } - catch (ClassNotFoundException ex) { - throw new TransactionSystemException( - "Could not find WebSphere 5.1/6.0/6.1 TransactionManager factory class", ex); - } - catch (InvocationTargetException ex) { - throw new TransactionSystemException( - "WebSphere's TransactionManagerFactory.getTransactionManager method failed", ex.getTargetException()); - } - catch (Exception ex) { - throw new TransactionSystemException( - "Could not access WebSphere's TransactionManagerFactory.getTransactionManager method", ex); - } - } - - - public Object getObject() { - return this.transactionManager; - } - - public Class getObjectType() { - return this.transactionManager.getClass(); - } - - public boolean isSingleton() { - return true; - } - -} diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereUowTransactionManager.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereUowTransactionManager.java index e4ce6aadf18..8f9fd2fa327 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereUowTransactionManager.java +++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/jta/WebSphereUowTransactionManager.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,7 +17,6 @@ package org.springframework.transaction.jta; import java.util.List; - import javax.naming.NamingException; import com.ibm.websphere.uow.UOWSynchronizationRegistry; @@ -65,12 +64,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * *

This transaction manager is compatible with WebSphere 7.0 as well as recent * WebSphere 6.0.x and 6.1.x versions. Check the documentation for your specific - * WebSphere version to find out whether UOWManager support is available. If it - * is not available, consider using Spring's standard {@link JtaTransactionManager} - * class, if necessary specifying the {@link WebSphereTransactionManagerFactoryBean} - * as "transactionManager" through the corresponding bean property. However, note - * that transaction suspension is not officially supported in such a scenario - * (despite it being known to work properly). + * WebSphere version to find out whether UOWManager support is available. * *

The default JNDI location for the UOWManager is "java:comp/websphere/UOWManager". * If the location happens to differ according to your WebSphere documentation, diff --git a/org.springframework.transaction/src/main/java/org/springframework/transaction/support/DefaultTransactionDefinition.java b/org.springframework.transaction/src/main/java/org/springframework/transaction/support/DefaultTransactionDefinition.java index 5d3bdc3dbf4..58766b43bf3 100644 --- a/org.springframework.transaction/src/main/java/org/springframework/transaction/support/DefaultTransactionDefinition.java +++ b/org.springframework.transaction/src/main/java/org/springframework/transaction/support/DefaultTransactionDefinition.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. @@ -252,20 +252,20 @@ public class DefaultTransactionDefinition implements TransactionDefinition, Seri * Return an identifying description for this transaction definition. *

Available to subclasses, for inclusion in their toString() result. */ - protected final StringBuffer getDefinitionDescription() { - StringBuffer desc = new StringBuffer(); - desc.append(constants.toCode(new Integer(this.propagationBehavior), PREFIX_PROPAGATION)); - desc.append(','); - desc.append(constants.toCode(new Integer(this.isolationLevel), PREFIX_ISOLATION)); + protected final StringBuilder getDefinitionDescription() { + StringBuilder result = new StringBuilder(); + result.append(constants.toCode(this.propagationBehavior, PREFIX_PROPAGATION)); + result.append(','); + result.append(constants.toCode(this.isolationLevel, PREFIX_ISOLATION)); if (this.timeout != TIMEOUT_DEFAULT) { - desc.append(','); - desc.append(PREFIX_TIMEOUT + this.timeout); + result.append(','); + result.append(PREFIX_TIMEOUT).append(this.timeout); } if (this.readOnly) { - desc.append(','); - desc.append(READ_ONLY_MARKER); + result.append(','); + result.append(READ_ONLY_MARKER); } - return desc; + return result; } } diff --git a/org.springframework.transaction/transaction.iml b/org.springframework.transaction/transaction.iml index 44e49c66654..b09f4a0f2e9 100644 --- a/org.springframework.transaction/transaction.iml +++ b/org.springframework.transaction/transaction.iml @@ -1,133 +1,133 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 a5990938150..d853ec8e366 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 @@ -20,10 +20,10 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; - import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; @@ -45,7 +45,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.SimpleLocaleContext; -import org.springframework.core.JdkVersion; import org.springframework.core.OrderComparator; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; @@ -262,16 +261,16 @@ public class DispatcherPortlet extends FrameworkPortlet { private PortletMultipartResolver multipartResolver; /** List of HandlerMappings used by this portlet */ - private List handlerMappings; + private List handlerMappings; /** List of HandlerAdapters used by this portlet */ - private List handlerAdapters; + private List handlerAdapters; /** List of HandlerExceptionResolvers used by this portlet */ - private List handlerExceptionResolvers; + private List handlerExceptionResolvers; /** List of ViewResolvers used by this portlet */ - private List viewResolvers; + private List viewResolvers; /** @@ -371,8 +370,7 @@ public class DispatcherPortlet extends FrameworkPortlet { */ private void initMultipartResolver(ApplicationContext context) { try { - this.multipartResolver = (PortletMultipartResolver) - context.getBean(MULTIPART_RESOLVER_BEAN_NAME, PortletMultipartResolver.class); + this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, PortletMultipartResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using MultipartResolver [" + this.multipartResolver + "]"); } @@ -396,19 +394,18 @@ public class DispatcherPortlet extends FrameworkPortlet { this.handlerMappings = null; if (this.detectAllHandlerMappings) { - // Find all HandlerMappings in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, HandlerMapping.class, true, false); if (!matchingBeans.isEmpty()) { - this.handlerMappings = new ArrayList(matchingBeans.values()); + this.handlerMappings = new ArrayList(matchingBeans.values()); // We keep HandlerMappings in sorted order. Collections.sort(this.handlerMappings, new OrderComparator()); } } else { try { - Object hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); + HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); this.handlerMappings = Collections.singletonList(hm); } catch (NoSuchBeanDefinitionException ex) { @@ -435,19 +432,18 @@ public class DispatcherPortlet extends FrameworkPortlet { this.handlerAdapters = null; if (this.detectAllHandlerAdapters) { - // Find all HandlerAdapters in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, HandlerAdapter.class, true, false); if (!matchingBeans.isEmpty()) { - this.handlerAdapters = new ArrayList(matchingBeans.values()); + this.handlerAdapters = new ArrayList(matchingBeans.values()); // We keep HandlerAdapters in sorted order. Collections.sort(this.handlerAdapters, new OrderComparator()); } } else { try { - Object ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); + HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); this.handlerAdapters = Collections.singletonList(ha); } catch (NoSuchBeanDefinitionException ex) { @@ -474,19 +470,18 @@ public class DispatcherPortlet extends FrameworkPortlet { this.handlerExceptionResolvers = null; if (this.detectAllHandlerExceptionResolvers) { - // Find all HandlerExceptionResolvers in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, HandlerExceptionResolver.class, true, false); if (!matchingBeans.isEmpty()) { - this.handlerExceptionResolvers = new ArrayList(matchingBeans.values()); + this.handlerExceptionResolvers = new ArrayList(matchingBeans.values()); // We keep HandlerExceptionResolvers in sorted order. Collections.sort(this.handlerExceptionResolvers, new OrderComparator()); } } else { try { - Object her = context.getBean( + HandlerExceptionResolver her = context.getBean( HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); this.handlerExceptionResolvers = Collections.singletonList(her); } @@ -514,19 +509,18 @@ public class DispatcherPortlet extends FrameworkPortlet { this.viewResolvers = null; if (this.detectAllViewResolvers) { - // Find all ViewResolvers in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all ViewResolvers in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, ViewResolver.class, true, false); if (!matchingBeans.isEmpty()) { - this.viewResolvers = new ArrayList(matchingBeans.values()); + this.viewResolvers = new ArrayList(matchingBeans.values()); // We keep ViewResolvers in sorted order. Collections.sort(this.viewResolvers, new OrderComparator()); } } else { try { - Object vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); + ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); this.viewResolvers = Collections.singletonList(vr); } catch (NoSuchBeanDefinitionException ex) { @@ -552,11 +546,10 @@ public class DispatcherPortlet extends FrameworkPortlet { * @param context the current Portlet ApplicationContext * @param strategyInterface the strategy interface * @return the corresponding strategy object - * @throws BeansException if initialization failed * @see #getDefaultStrategies */ - protected Object getDefaultStrategy(ApplicationContext context, Class strategyInterface) throws BeansException { - List strategies = getDefaultStrategies(context, strategyInterface); + protected T getDefaultStrategy(ApplicationContext context, Class strategyInterface) { + List strategies = getDefaultStrategies(context, strategyInterface); if (strategies.size() != 1) { throw new BeanInitializationException( "DispatcherPortlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]"); @@ -573,42 +566,36 @@ public class DispatcherPortlet extends FrameworkPortlet { * @param context the current Portlet ApplicationContext * @param strategyInterface the strategy interface * @return the List of corresponding strategy objects - * @throws BeansException if initialization failed */ - protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) throws BeansException { + @SuppressWarnings("unchecked") + protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) { String key = strategyInterface.getName(); - List strategies = null; String value = defaultStrategies.getProperty(key); if (value != null) { String[] classNames = StringUtils.commaDelimitedListToStringArray(value); - strategies = new ArrayList(classNames.length); - for (int i = 0; i < classNames.length; i++) { - String className = classNames[i]; - if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15 && className.indexOf("Annotation") != -1) { - // Skip Java 5 specific strategies when running on JDK 1.4... - continue; - } + List strategies = new ArrayList(classNames.length); + for (String className : classNames) { try { Class clazz = ClassUtils.forName(className, DispatcherPortlet.class.getClassLoader()); Object strategy = createDefaultStrategy(context, clazz); - strategies.add(strategy); + strategies.add((T) strategy); } catch (ClassNotFoundException ex) { throw new BeanInitializationException( "Could not find DispatcherPortlet's default strategy class [" + className + - "] for interface [" + key + "]", ex); + "] for interface [" + key + "]", ex); } catch (LinkageError err) { throw new BeanInitializationException( "Error loading DispatcherPortlet's default strategy class [" + className + - "] for interface [" + key + "]: problem with class file or dependent class", err); + "] for interface [" + key + "]: problem with class file or dependent class", err); } } + return strategies; } else { - strategies = Collections.EMPTY_LIST; + return new LinkedList(); } - return strategies; } /** @@ -767,7 +754,6 @@ public class DispatcherPortlet extends FrameworkPortlet { logger.debug("Bound render request context to thread: " + request); } - RenderRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; @@ -790,9 +776,9 @@ public class DispatcherPortlet extends FrameworkPortlet { } // Determine handler for the current request. - mappedHandler = getHandler(processedRequest, false); + mappedHandler = getHandler(request, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { - noHandlerFound(processedRequest, response); + noHandlerFound(request, response); return; } @@ -801,8 +787,8 @@ public class DispatcherPortlet extends FrameworkPortlet { if (interceptors != null) { for (int i = 0; i < interceptors.length; i++) { HandlerInterceptor interceptor = interceptors[i]; - if (!interceptor.preHandleRender(processedRequest, response, mappedHandler.getHandler())) { - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); + if (!interceptor.preHandleRender(request, response, mappedHandler.getHandler())) { + triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null); return; } interceptorIndex = i; @@ -811,13 +797,13 @@ public class DispatcherPortlet extends FrameworkPortlet { // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); - mv = ha.handleRender(processedRequest, response, mappedHandler.getHandler()); + mv = ha.handleRender(request, response, mappedHandler.getHandler()); // Apply postHandle methods of registered interceptors. if (interceptors != null) { for (int i = interceptors.length - 1; i >= 0; i--) { HandlerInterceptor interceptor = interceptors[i]; - interceptor.postHandleRender(processedRequest, response, mappedHandler.getHandler(), mv); + interceptor.postHandleRender(request, response, mappedHandler.getHandler(), mv); } } } @@ -832,7 +818,7 @@ public class DispatcherPortlet extends FrameworkPortlet { // Did the handler return a view to render? if (mv != null && !mv.isEmpty()) { - render(mv, processedRequest, response); + render(mv, request, response); } else { if (logger.isDebugEnabled()) { @@ -842,19 +828,19 @@ public class DispatcherPortlet extends FrameworkPortlet { } // Trigger after-completion for successful outcome. - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); + triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null); } catch (Exception ex) { // Trigger after-completion for thrown exception. - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); + triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex); throw ex; } catch (Error err) { PortletException ex = new PortletException("Error occured during request processing: " + err.getMessage(), err); // Trigger after-completion for thrown exception. - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); + triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex); throw ex; } @@ -918,12 +904,10 @@ public class DispatcherPortlet extends FrameworkPortlet { return handler; } - Iterator it = this.handlerMappings.iterator(); - while (it.hasNext()) { - HandlerMapping hm = (HandlerMapping) it.next(); + for (HandlerMapping hm : this.handlerMappings) { if (logger.isDebugEnabled()) { - logger.debug("Testing handler map [" + hm + "] in DispatcherPortlet with name '" + - getPortletName() + "'"); + logger.debug( + "Testing handler map [" + hm + "] in DispatcherPortlet with name '" + getPortletName() + "'"); } handler = hm.getHandler(request); if (handler != null) { @@ -961,9 +945,7 @@ public class DispatcherPortlet extends FrameworkPortlet { * This is a fatal error. */ protected HandlerAdapter getHandlerAdapter(Object handler) throws PortletException { - Iterator it = this.handlerAdapters.iterator(); - while (it.hasNext()) { - HandlerAdapter ha = (HandlerAdapter) it.next(); + for (HandlerAdapter ha : this.handlerAdapters) { if (logger.isDebugEnabled()) { logger.debug("Testing handler adapter [" + ha + "]"); } @@ -1070,11 +1052,6 @@ public class DispatcherPortlet extends FrameworkPortlet { view = (View) viewObject; } - if (view == null) { - throw new PortletException("Could not resolve view with name '" + mv.getViewName() + - "' in portlet with name '" + getPortletName() + "'"); - } - // Set the content type on the response if needed and if possible. // The Portlet spec requires the content type to be set on the RenderResponse; // it's not sufficient to let the View set it on the ServletResponse. @@ -1111,8 +1088,7 @@ public class DispatcherPortlet extends FrameworkPortlet { * @see ViewResolver#resolveViewName */ protected View resolveViewName(String viewName, Map model, RenderRequest request) throws Exception { - for (Iterator it = this.viewResolvers.iterator(); it.hasNext();) { - ViewResolver viewResolver = (ViewResolver) it.next(); + for (ViewResolver viewResolver : this.viewResolvers) { View view = viewResolver.resolveViewName(viewName, request.getLocale()); if (view != null) { return view; 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 d3a2effdc20..f4bcf3fc59a 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 @@ -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. @@ -290,15 +290,15 @@ public class ModelAndView { */ @Override public String toString() { - StringBuffer buf = new StringBuffer("ModelAndView: "); + StringBuilder result = new StringBuilder("ModelAndView: "); if (isReference()) { - buf.append("reference to view with name '").append(this.view).append("'"); + result.append("reference to view with name '").append(this.view).append("'"); } else { - buf.append("materialized View is [").append(this.view).append(']'); + result.append("materialized View is [").append(this.view).append(']'); } - buf.append("; model is ").append(this.model); - return buf.toString(); + result.append("; model is ").append(this.model); + return result.toString(); } } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java index 56540697a3b..b10750fa932 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java @@ -148,6 +148,7 @@ public abstract class AbstractRefreshablePortletApplicationContext extends Abstr beanFactory.registerResolvableDependency(PortletConfig.class, this.portletConfig); PortletApplicationContextUtils.registerPortletApplicationScopes(beanFactory); + PortletApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.portletContext); } /** diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java index 11c676c3e77..6d4da7e0775 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.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,10 @@ package org.springframework.web.portlet.context; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; import javax.portlet.PortletContext; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; @@ -127,4 +131,38 @@ public abstract class PortletApplicationContextUtils { }); } + /** + * Register web-specific environment beans with the given BeanFactory, + * as used by the Portlet ApplicationContext. + * @param bf the BeanFactory to configure + * @param pc the PortletContext that we're running within + */ + static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf, PortletContext pc) { + if (!bf.containsBean(WebApplicationContext.CONTEXT_PROPERTIES_BEAN_NAME)) { + Map parameterMap = new HashMap(); + if (pc != null) { + Enumeration paramNameEnum = pc.getInitParameterNames(); + while (paramNameEnum.hasMoreElements()) { + String paramName = (String) paramNameEnum.nextElement(); + parameterMap.put(paramName, pc.getInitParameter(paramName)); + } + } + bf.registerSingleton(WebApplicationContext.CONTEXT_PROPERTIES_BEAN_NAME, + Collections.unmodifiableMap(parameterMap)); + } + + if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) { + Map attributeMap = new HashMap(); + if (pc != null) { + Enumeration attrNameEnum = pc.getAttributeNames(); + while (attrNameEnum.hasMoreElements()) { + String attrName = (String) attrNameEnum.nextElement(); + attributeMap.put(attrName, pc.getAttribute(attrName)); + } + } + bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME, + Collections.unmodifiableMap(attributeMap)); + } + } + } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java index d67a78ed7d7..7ab37755033 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java @@ -17,18 +17,14 @@ package org.springframework.web.portlet.context; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; - import javax.portlet.PortletRequest; import javax.portlet.PortletSession; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.context.request.AbstractRequestAttributes; +import org.springframework.web.context.request.DestructionCallbackBindingListener; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.portlet.util.PortletUtils; @@ -52,18 +48,20 @@ import org.springframework.web.portlet.util.PortletUtils; public class PortletRequestAttributes extends AbstractRequestAttributes { /** - * We'll create a lot of these objects, so we don't want a new logger every time. + * Constant identifying the {@link String} prefixed to the name of a + * destruction callback when it is stored in a {@link PortletSession}. */ - private static final Log logger = LogFactory.getLog(PortletRequestAttributes.class); + public static final String DESTRUCTION_CALLBACK_NAME_PREFIX = + PortletRequestAttributes.class.getName() + ".DESTRUCTION_CALLBACK."; private final PortletRequest request; private volatile PortletSession session; - private final Map sessionAttributesToUpdate = new HashMap(); + private final Map sessionAttributesToUpdate = new HashMap(); - private final Map globalSessionAttributesToUpdate = new HashMap(); + private final Map globalSessionAttributesToUpdate = new HashMap(); /** @@ -222,6 +220,18 @@ public class PortletRequestAttributes extends AbstractRequestAttributes { } } + public Object resolveReference(String key) { + if (REFERENCE_REQUEST.equals(key)) { + return this.request; + } + else if (REFERENCE_SESSION.equals(key)) { + return getSession(true); + } + else { + return null; + } + } + public String getSessionId() { return getSession(true).getId(); } @@ -240,9 +250,8 @@ public class PortletRequestAttributes extends AbstractRequestAttributes { this.session = this.request.getPortletSession(false); synchronized (this.sessionAttributesToUpdate) { if (this.session != null) { - for (Iterator it = this.sessionAttributesToUpdate.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String name = (String) entry.getKey(); + for (Map.Entry entry : this.sessionAttributesToUpdate.entrySet()) { + String name = entry.getKey(); Object newValue = entry.getValue(); Object oldValue = this.session.getAttribute(name); if (oldValue == newValue) { @@ -254,9 +263,8 @@ public class PortletRequestAttributes extends AbstractRequestAttributes { } synchronized (this.globalSessionAttributesToUpdate) { if (this.session != null) { - for (Iterator it = this.globalSessionAttributesToUpdate.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String name = (String) entry.getKey(); + for (Map.Entry entry : this.globalSessionAttributesToUpdate.entrySet()) { + String name = entry.getKey(); Object newValue = entry.getValue(); Object oldValue = this.session.getAttribute(name, PortletSession.APPLICATION_SCOPE); if (oldValue == newValue) { @@ -274,10 +282,9 @@ public class PortletRequestAttributes extends AbstractRequestAttributes { * @param callback the callback to be executed for destruction */ private void registerSessionDestructionCallback(String name, Runnable callback) { - if (logger.isWarnEnabled()) { - logger.warn("Could not register destruction callback [" + callback + "] for attribute '" + name + - "' for session scope because Portlet API 1.0 does not support session attribute callbacks"); - } + PortletSession session = getSession(true); + session.setAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name, + new DestructionCallbackBindingListener(callback)); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java index 4b052eee786..3bb0eb787f3 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.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. @@ -108,7 +108,7 @@ public class PortletRequestHandledEvent extends RequestHandledEvent { @Override public String getShortDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("portlet=[").append(this.portletName).append("]; "); sb.append(super.getShortDescription()); return sb.toString(); @@ -116,7 +116,7 @@ public class PortletRequestHandledEvent extends RequestHandledEvent { @Override public String getDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("portlet=[").append(this.portletName).append("]; "); sb.append("mode=[").append(this.portletMode).append("]; "); sb.append("type=[").append(this.requestType).append("]; "); diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java index 0c6b454489f..08c4e397512 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java @@ -19,7 +19,6 @@ package org.springframework.web.portlet.context; import java.security.Principal; import java.util.Locale; import java.util.Map; - import javax.portlet.PortletRequest; import javax.portlet.PortletResponse; import javax.portlet.PortletSession; @@ -82,7 +81,8 @@ public class PortletWebRequest extends PortletRequestAttributes implements Nativ return getRequest().getParameterValues(paramName); } - public Map getParameterMap() { + @SuppressWarnings("unchecked") + public Map getParameterMap() { return getRequest().getParameterMap(); } @@ -121,19 +121,19 @@ public class PortletWebRequest extends PortletRequestAttributes implements Nativ public String getDescription(boolean includeClientInfo) { PortletRequest request = getRequest(); - StringBuffer buffer = new StringBuffer(); - buffer.append("context=").append(request.getContextPath()); + StringBuilder result = new StringBuilder(); + result.append("context=").append(request.getContextPath()); if (includeClientInfo) { PortletSession session = request.getPortletSession(false); if (session != null) { - buffer.append(";session=").append(session.getId()); + result.append(";session=").append(session.getId()); } String user = getRequest().getRemoteUser(); if (StringUtils.hasLength(user)) { - buffer.append(";user=").append(user); + result.append(";user=").append(user); } } - return buffer.toString(); + return result.toString(); } @Override diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java index 9e2b9209585..457b4c2cad0 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java @@ -144,6 +144,7 @@ public class StaticPortletApplicationContext extends StaticApplicationContext beanFactory.registerResolvableDependency(PortletConfig.class, this.portletConfig); PortletApplicationContextUtils.registerPortletApplicationScopes(beanFactory); + PortletApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.portletContext); } /** 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 0a665606d99..5797e5fd718 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 @@ -17,7 +17,6 @@ package org.springframework.web.portlet.multipart; import java.util.List; - import javax.portlet.ActionRequest; import javax.portlet.PortletContext; @@ -26,10 +25,8 @@ import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.portlet.PortletFileUpload; -import org.apache.commons.fileupload.portlet.PortletRequestContext; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.commons.CommonsFileUploadSupport; @@ -39,7 +36,7 @@ import org.springframework.web.portlet.util.PortletUtils; /** * {@link PortletMultipartResolver} implementation for * Jakarta Commons FileUpload - * 1.1 or above. Commons FileUpload 1.2 or above is recommended. + * 1.2 or above. * *

Provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as * bean properties (inherited from {@link CommonsFileUploadSupport}). See corresponding @@ -61,9 +58,6 @@ import org.springframework.web.portlet.util.PortletUtils; public class CommonsPortletMultipartResolver extends CommonsFileUploadSupport implements PortletMultipartResolver, PortletContextAware { - private final boolean commonsFileUpload12Present = - ClassUtils.hasMethod(PortletFileUpload.class, "isMultipartContent", new Class[] {ActionRequest.class}); - private boolean resolveLazily = false; @@ -122,11 +116,8 @@ public class CommonsPortletMultipartResolver extends CommonsFileUploadSupport if (request == null) { return false; } - else if (commonsFileUpload12Present) { - return PortletFileUpload.isMultipartContent(request); - } else { - return PortletFileUpload.isMultipartContent(new PortletRequestContext(request)); + return PortletFileUpload.isMultipartContent(request); } } diff --git a/org.springframework.web.portlet/web-portlet.iml b/org.springframework.web.portlet/web-portlet.iml index a523f9f9098..04f745d1e53 100644 --- a/org.springframework.web.portlet/web-portlet.iml +++ b/org.springframework.web.portlet/web-portlet.iml @@ -1,68 +1,68 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/RequestUtils.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/RequestUtils.java deleted file mode 100644 index 94e5e631e1e..00000000000 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/RequestUtils.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright 2002-2007 the original author 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.bind; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.web.HttpRequestMethodNotSupportedException; - -/** - * Parameter extraction methods, for an approach distinct from data binding, - * in which parameters of specific types are required. - * - *

This approach is very useful for simple submissions, where binding - * request parameters to a command object would be overkill. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @author Keith Donald - * @deprecated as of Spring 2.0: use ServletRequestUtils instead - * @see ServletRequestUtils - */ -@Deprecated -public abstract class RequestUtils { - - /** - * Throw a ServletException if the given HTTP request method should be rejected. - * @param request request to check - * @param method method (such as "GET") which should be rejected - * @throws ServletException if the given HTTP request is rejected - */ - public static void rejectRequestMethod(HttpServletRequest request, String method) throws ServletException { - if (request.getMethod().equals(method)) { - throw new HttpRequestMethodNotSupportedException(method); - } - } - - - /** - * Get an Integer parameter, or null if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @return the Integer value, or null if not present - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static Integer getIntParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getIntParameter(request, name); - } - - /** - * Get an int parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current HTTP request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static int getIntParameter(HttpServletRequest request, String name, int defaultVal) { - return ServletRequestUtils.getIntParameter(request, name, defaultVal); - } - - /** - * Get an array of int parameters, return an empty array if not found. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - */ - public static int[] getIntParameters(HttpServletRequest request, String name) { - return ServletRequestUtils.getIntParameters(request, name); - } - - /** - * Get an int parameter, throwing an exception if it isn't found or isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static int getRequiredIntParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredIntParameter(request, name); - } - - /** - * Get an array of int parameters, throwing an exception if not found or one is not a number.. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static int[] getRequiredIntParameters(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredIntParameters(request, name); - } - - - /** - * Get a Long parameter, or null if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @return the Long value, or null if not present - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static Long getLongParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getLongParameter(request, name); - } - - /** - * Get a long parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current HTTP request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static long getLongParameter(HttpServletRequest request, String name, long defaultVal) { - return ServletRequestUtils.getLongParameter(request, name, defaultVal); - } - - /** - * Get an array of long parameters, return an empty array if not found. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - */ - public static long[] getLongParameters(HttpServletRequest request, String name) { - return ServletRequestUtils.getLongParameters(request, name); - } - - /** - * Get a long parameter, throwing an exception if it isn't found or isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static long getRequiredLongParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredLongParameter(request, name); - } - - /** - * Get an array of long parameters, throwing an exception if not found or one is not a number. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static long[] getRequiredLongParameters(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredLongParameters(request, name); - } - - - /** - * Get a Float parameter, or null if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @return the Float value, or null if not present - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static Float getFloatParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getFloatParameter(request, name); - } - - /** - * Get a float parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current HTTP request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static float getFloatParameter(HttpServletRequest request, String name, float defaultVal) { - return ServletRequestUtils.getFloatParameter(request, name, defaultVal); - } - - /** - * Get an array of float parameters, return an empty array if not found. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - */ - public static float[] getFloatParameters(HttpServletRequest request, String name) { - return ServletRequestUtils.getFloatParameters(request, name); - } - - /** - * Get a float parameter, throwing an exception if it isn't found or isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static float getRequiredFloatParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredFloatParameter(request, name); - } - - /** - * Get an array of float parameters, throwing an exception if not found or one is not a number. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static float[] getRequiredFloatParameters(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredFloatParameters(request, name); - } - - - /** - * Get a Double parameter, or null if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @return the Double value, or null if not present - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static Double getDoubleParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getDoubleParameter(request, name); - } - - /** - * Get a double parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current HTTP request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static double getDoubleParameter(HttpServletRequest request, String name, double defaultVal) { - return ServletRequestUtils.getDoubleParameter(request, name, defaultVal); - } - - /** - * Get an array of double parameters, return an empty array if not found. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - */ - public static double[] getDoubleParameters(HttpServletRequest request, String name) { - return ServletRequestUtils.getDoubleParameters(request, name); - } - - /** - * Get a double parameter, throwing an exception if it isn't found or isn't a number. - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static double getRequiredDoubleParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredDoubleParameter(request, name); - } - - /** - * Get an array of double parameters, throwing an exception if not found or one is not a number. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static double[] getRequiredDoubleParameters(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - return ServletRequestUtils.getRequiredDoubleParameters(request, name); - } - - - /** - * Get a Boolean parameter, or null if not present. - * Throws an exception if it the parameter value isn't a boolean. - *

Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current HTTP request - * @param name the name of the parameter - * @return the Boolean value, or null if not present - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static Boolean getBooleanParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return (getRequiredBooleanParameter(request, name) ? Boolean.TRUE : Boolean.FALSE); - } - - /** - * Get a boolean parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - *

Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current HTTP request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static boolean getBooleanParameter(HttpServletRequest request, String name, boolean defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredBooleanParameter(request, name); - } - catch (ServletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of boolean parameters, return an empty array if not found. - *

Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - */ - public static boolean[] getBooleanParameters(HttpServletRequest request, String name) { - try { - return getRequiredBooleanParameters(request, name); - } - catch (ServletRequestBindingException ex) { - return new boolean[0]; - } - } - - /** - * Get a boolean parameter, throwing an exception if it isn't found - * or isn't a boolean. - *

Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static boolean getRequiredBooleanParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - boolean value = ServletRequestUtils.getRequiredBooleanParameter(request, name); - if (!value && "".equals(request.getParameter(name))) { - throw new ServletRequestBindingException( - "Required boolean parameter '" + name + "' contains no value"); - } - return value; - } - - /** - * Get an array of boolean parameters, throwing an exception if not found - * or one isn't a boolean. - *

Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static boolean[] getRequiredBooleanParameters(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - boolean[] values = ServletRequestUtils.getRequiredBooleanParameters(request, name); - for (int i = 0; i < values.length; i++) { - if (!values[i] && "".equals(request.getParameterValues(name)[i])) { - throw new ServletRequestBindingException( - "Required boolean parameter '" + name + "' contains no value"); - } - } - return values; - } - - - /** - * Get a String parameter, or null if not present. - * Throws an exception if it the parameter value is empty. - * @param request current HTTP request - * @param name the name of the parameter - * @return the String value, or null if not present - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static String getStringParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return getRequiredStringParameter(request, name); - } - - /** - * Get a String parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value to default to enable checks of whether it was supplied. - * @param request current HTTP request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static String getStringParameter(HttpServletRequest request, String name, String defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredStringParameter(request, name); - } - catch (ServletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of String parameters, return an empty array if not found. - * @param request current HTTP request - * @param name the name of the parameter with multiple possible values - */ - public static String[] getStringParameters(HttpServletRequest request, String name) { - try { - return getRequiredStringParameters(request, name); - } - catch (ServletRequestBindingException ex) { - return new String[0]; - } - } - - /** - * Get a String parameter, throwing an exception if it isn't found or is empty. - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static String getRequiredStringParameter(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - String value = ServletRequestUtils.getRequiredStringParameter(request, name); - if ("".equals(value)) { - throw new ServletRequestBindingException( - "Required string parameter '" + name + "' contains no value"); - } - return value; - } - - /** - * Get an array of String parameters, throwing an exception if not found or one is empty. - * @param request current HTTP request - * @param name the name of the parameter - * @throws ServletRequestBindingException a subclass of ServletException, - * so it doesn't need to be caught - */ - public static String[] getRequiredStringParameters(HttpServletRequest request, String name) - throws ServletRequestBindingException { - - String[] values = ServletRequestUtils.getRequiredStringParameters(request, name); - for (int i = 0; i < values.length; i++) { - if ("".equals(values[i])) { - throw new ServletRequestBindingException( - "Required string parameter '" + name + "' contains no value"); - } - } - return values; - } - -} diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java index 3d4f08da011..3136f153994 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java @@ -16,6 +16,7 @@ package org.springframework.web.bind.annotation.support; +import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; @@ -86,6 +87,7 @@ public class HandlerMethodInvoker { private final SimpleSessionStatus sessionStatus = new SimpleSessionStatus(); + public HandlerMethodInvoker(HandlerMethodResolver methodResolver) { this(methodResolver, null); } @@ -94,11 +96,9 @@ public class HandlerMethodInvoker { this(methodResolver, bindingInitializer, new DefaultSessionAttributeStore(), null); } - public HandlerMethodInvoker(HandlerMethodResolver methodResolver, - WebBindingInitializer bindingInitializer, - SessionAttributeStore sessionAttributeStore, - ParameterNameDiscoverer parameterNameDiscoverer, - WebArgumentResolver... customArgumentResolvers) { + public HandlerMethodInvoker(HandlerMethodResolver methodResolver, WebBindingInitializer bindingInitializer, + SessionAttributeStore sessionAttributeStore, ParameterNameDiscoverer parameterNameDiscoverer, + WebArgumentResolver... customArgumentResolvers) { this.methodResolver = methodResolver; this.bindingInitializer = bindingInitializer; @@ -107,10 +107,9 @@ public class HandlerMethodInvoker { this.customArgumentResolvers = customArgumentResolvers; } - public final Object invokeHandlerMethod(Method handlerMethod, - Object handler, - NativeWebRequest webRequest, - ExtendedModelMap implicitModel) throws Exception { + + public final Object invokeHandlerMethod(Method handlerMethod, Object handler, + NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod); try { @@ -145,9 +144,9 @@ public class HandlerMethodInvoker { @SuppressWarnings("unchecked") private Object[] resolveHandlerArguments(Method handlerMethod, - Object handler, - NativeWebRequest webRequest, - ExtendedModelMap implicitModel) throws Exception { + Object handler, + NativeWebRequest webRequest, + ExtendedModelMap implicitModel) throws Exception { Class[] paramTypes = handlerMethod.getParameterTypes(); Object[] args = new Object[paramTypes.length]; @@ -161,9 +160,9 @@ public class HandlerMethodInvoker { String paramDefaultValue = null; String pathVarName = null; String attrName = null; - Object[] paramAnns = methodParam.getParameterAnnotations(); + Annotation[] paramAnns = methodParam.getParameterAnnotations(); - for (Object paramAnn : paramAnns) { + for (Annotation paramAnn : paramAnns) { if (RequestParam.class.isInstance(paramAnn)) { RequestParam requestParam = (RequestParam) paramAnn; paramName = requestParam.value(); @@ -174,7 +173,8 @@ public class HandlerMethodInvoker { else if (ModelAttribute.class.isInstance(paramAnn)) { ModelAttribute attr = (ModelAttribute) paramAnn; attrName = attr.value(); - } else if (PathVariable.class.isInstance(paramAnn)) { + } + else if (PathVariable.class.isInstance(paramAnn)) { PathVariable pathVar = (PathVariable) paramAnn; pathVarName = pathVar.value(); } @@ -185,7 +185,7 @@ public class HandlerMethodInvoker { "choices - do not specify both on the same parameter: " + handlerMethod); } - if (paramName == null && attrName == null && pathVarName == null) { + if (paramName == null && attrName == null && pathVarName == null) { Object argValue = resolveCommonArgument(methodParam, webRequest); if (argValue != WebArgumentResolver.UNRESOLVED) { args[i] = argValue; @@ -227,7 +227,8 @@ public class HandlerMethodInvoker { i++; } implicitModel.putAll(binder.getBindingResult().getModel()); - } else if (pathVarName != null) { + } + else if (pathVarName != null) { args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler); } } @@ -265,10 +266,8 @@ public class HandlerMethodInvoker { } } - private Object[] resolveInitBinderArguments(Object handler, - Method initBinderMethod, - WebDataBinder binder, - NativeWebRequest webRequest) throws Exception { + private Object[] resolveInitBinderArguments(Object handler, Method initBinderMethod, + WebDataBinder binder, NativeWebRequest webRequest) throws Exception { Class[] initBinderParams = initBinderMethod.getParameterTypes(); Object[] initBinderArgs = new Object[initBinderParams.length]; @@ -281,9 +280,9 @@ public class HandlerMethodInvoker { boolean paramRequired = false; String paramDefaultValue = null; String pathVarName = null; - Object[] paramAnns = methodParam.getParameterAnnotations(); + Annotation[] paramAnns = methodParam.getParameterAnnotations(); - for (Object paramAnn : paramAnns) { + for (Annotation paramAnn : paramAnns) { if (RequestParam.class.isInstance(paramAnn)) { RequestParam requestParam = (RequestParam) paramAnn; paramName = requestParam.value(); @@ -315,16 +314,18 @@ public class HandlerMethodInvoker { paramName = ""; } else { - throw new IllegalStateException("Unsupported argument [" + paramType.getName() + - "] for @InitBinder method: " + initBinderMethod); + throw new IllegalStateException( + "Unsupported argument [" + paramType.getName() + "] for @InitBinder method: " + + initBinderMethod); } } } if (paramName != null) { - initBinderArgs[i] = - resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null); - } else if (pathVarName != null) { + initBinderArgs[i] = resolveRequestParam( + paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null); + } + else if (pathVarName != null) { initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null); } } @@ -332,19 +333,17 @@ public class HandlerMethodInvoker { return initBinderArgs; } - private Object resolveRequestParam(String paramName, - boolean paramRequired, - String paramDefaultValue, - MethodParameter methodParam, - NativeWebRequest webRequest, - Object handlerForInitBinderCall) throws Exception { + private Object resolveRequestParam(String paramName, boolean paramRequired, String paramDefaultValue, + MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) + throws Exception { Class paramType = methodParam.getParameterType(); if (paramName.length() == 0) { paramName = methodParam.getParameterName(); if (paramName == null) { - throw new IllegalStateException("No parameter specified for @RequestParam argument of type [" + - paramType.getName() + "], and no parameter name information found in class file either."); + throw new IllegalStateException( + "No parameter specified for @RequestParam argument of type [" + paramType.getName() + + "], and no parameter name information found in class file either."); } } Object paramValue = null; @@ -375,11 +374,9 @@ public class HandlerMethodInvoker { return binder.convertIfNecessary(paramValue, paramType, methodParam); } - private WebDataBinder resolveModelAttribute(String attrName, - MethodParameter methodParam, - ExtendedModelMap implicitModel, - NativeWebRequest webRequest, - Object handler) throws Exception { + private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, + ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) + throws Exception { // Bind request parameter onto object... String name = attrName; @@ -406,22 +403,21 @@ public class HandlerMethodInvoker { } /** - * Resolves the given {@link org.springframework.web.bind.annotation.PathVariable @PathVariable} variable. Overriden in - * {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.ServletHandlerMethodInvoker}, - * throws an UnsupportedOperationException by default. + * Resolves the given {@link org.springframework.web.bind.annotation.PathVariable @PathVariable} + * variable. Throws an UnsupportedOperationException by default. Overridden in + * {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.ServletHandlerMethodInvoker}. */ - protected Object resolvePathVariable(String pathVarName, - MethodParameter methodParam, - NativeWebRequest webRequest, - Object handlerForInitBinderCall) throws Exception { + protected Object resolvePathVariable(String pathVarName, MethodParameter methodParam, + NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { + throw new UnsupportedOperationException("@PathVariable not supported"); } @SuppressWarnings("unchecked") public final void updateModelAttributes(Object handler, - Map mavModel, - ExtendedModelMap implicitModel, - NativeWebRequest webRequest) throws Exception { + Map mavModel, + ExtendedModelMap implicitModel, + NativeWebRequest webRequest) throws Exception { if (this.methodResolver.hasSessionAttributes() && this.sessionStatus.isComplete()) { for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { @@ -511,9 +507,10 @@ public class HandlerMethodInvoker { Class paramType = methodParameter.getParameterType(); Object value = resolveStandardArgument(paramType, webRequest); if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) { - throw new IllegalStateException("Standard argument type [" + paramType.getName() + - "] resolved to incompatible value of type [" + (value != null ? value.getClass() : null) + - "]. Consider declaring the argument type in a less specific fashion."); + throw new IllegalStateException( + "Standard argument type [" + paramType.getName() + "] resolved to incompatible value of type [" + + (value != null ? value.getClass() : null) + + "]. Consider declaring the argument type in a less specific fashion."); } return value; } 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 b5a850ef146..cdb19d7a32f 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 @@ -17,7 +17,6 @@ package org.springframework.web.multipart.commons; import java.util.List; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -26,10 +25,8 @@ import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.fileupload.servlet.ServletRequestContext; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartException; @@ -41,7 +38,7 @@ import org.springframework.web.util.WebUtils; /** * Servlet-based {@link org.springframework.web.multipart.MultipartResolver} implementation * for Jakarta Commons FileUpload - * 1.1 or above. Commons FileUpload 1.2 or above is recommended. + * 1.2 or above. * *

Provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as * bean properties (inherited from {@link CommonsFileUploadSupport}). See corresponding @@ -64,9 +61,6 @@ import org.springframework.web.util.WebUtils; public class CommonsMultipartResolver extends CommonsFileUploadSupport implements MultipartResolver, ServletContextAware { - private final boolean commonsFileUpload12Present = - ClassUtils.hasMethod(ServletFileUpload.class, "isMultipartContent", new Class[] {HttpServletRequest.class}); - private boolean resolveLazily = false; @@ -127,11 +121,8 @@ public class CommonsMultipartResolver extends CommonsFileUploadSupport if (request == null) { return false; } - else if (commonsFileUpload12Present) { - return ServletFileUpload.isMultipartContent(request); - } else { - return ServletFileUpload.isMultipartContent(new ServletRequestContext(request)); + return ServletFileUpload.isMultipartContent(request); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java index 9d6c09d92fd..ee8e34392a5 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditor.java @@ -38,9 +38,7 @@ public class ByteArrayMultipartFileEditor extends ByteArrayPropertyEditor { super.setValue(multipartFile.getBytes()); } catch (IOException ex) { - IllegalArgumentException iae = new IllegalArgumentException("Cannot read contents of multipart file"); - iae.initCause(ex); - throw iae; + throw new IllegalArgumentException("Cannot read contents of multipart file", ex); } } else if (value instanceof byte[]) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java index 585eb926936..9c551c315f2 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/multipart/support/StringMultipartFileEditor.java @@ -67,9 +67,7 @@ public class StringMultipartFileEditor extends PropertyEditorSupport { new String(multipartFile.getBytes())); } catch (IOException ex) { - IllegalArgumentException iae = new IllegalArgumentException("Cannot read contents of multipart file"); - iae.initCause(ex); - throw iae; + throw new IllegalArgumentException("Cannot read contents of multipart file", ex); } } else { 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 b662217f235..54de4f55883 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 @@ -23,6 +23,7 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -34,6 +35,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanInitializationException; @@ -41,7 +43,6 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.core.JdkVersion; import org.springframework.core.OrderComparator; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; @@ -83,11 +84,9 @@ import org.springframework.web.util.WebUtils; * *

  • It can use any {@link HandlerAdapter}; this allows for using any handler interface. * Default adapters are {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter}, - * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter} and - * {@link org.springframework.web.servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter}, - * for Spring's {@link org.springframework.web.HttpRequestHandler}, - * {@link org.springframework.web.servlet.mvc.Controller} and - * {@link org.springframework.web.servlet.mvc.throwaway.ThrowawayController} interfaces, + * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter}, + * for Spring's {@link org.springframework.web.HttpRequestHandler} and + * {@link org.springframework.web.servlet.mvc.Controller} interfaces, * respectively. When running in a Java 5+ environment, a default * {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter} * will be registered as well. HandlerAdapter objects can be added as beans in the @@ -298,19 +297,19 @@ public class DispatcherServlet extends FrameworkServlet { private ThemeResolver themeResolver; /** List of HandlerMappings used by this servlet */ - private List handlerMappings; + private List handlerMappings; /** List of HandlerAdapters used by this servlet */ - private List handlerAdapters; + private List handlerAdapters; /** List of HandlerExceptionResolvers used by this servlet */ - private List handlerExceptionResolvers; + private List handlerExceptionResolvers; /** RequestToViewNameTranslator used by this servlet */ private RequestToViewNameTranslator viewNameTranslator; /** List of ViewResolvers used by this servlet */ - private List viewResolvers; + private List viewResolvers; /** @@ -422,8 +421,7 @@ public class DispatcherServlet extends FrameworkServlet { */ private void initMultipartResolver(ApplicationContext context) { try { - this.multipartResolver = (MultipartResolver) - context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); + this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using MultipartResolver [" + this.multipartResolver + "]"); } @@ -445,15 +443,14 @@ public class DispatcherServlet extends FrameworkServlet { */ private void initLocaleResolver(ApplicationContext context) { try { - this.localeResolver = (LocaleResolver) - context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class); + this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using LocaleResolver [" + this.localeResolver + "]"); } } catch (NoSuchBeanDefinitionException ex) { // We need to use the default. - this.localeResolver = (LocaleResolver) getDefaultStrategy(context, LocaleResolver.class); + this.localeResolver = getDefaultStrategy(context, LocaleResolver.class); if (logger.isDebugEnabled()) { logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME + "': using default [" + this.localeResolver + "]"); @@ -468,15 +465,14 @@ public class DispatcherServlet extends FrameworkServlet { */ private void initThemeResolver(ApplicationContext context) { try { - this.themeResolver = (ThemeResolver) - context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class); + this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using ThemeResolver [" + this.themeResolver + "]"); } } catch (NoSuchBeanDefinitionException ex) { // We need to use the default. - this.themeResolver = (ThemeResolver) getDefaultStrategy(context, ThemeResolver.class); + this.themeResolver = getDefaultStrategy(context, ThemeResolver.class); if (logger.isDebugEnabled()) { logger.debug("Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME + "': using default [" + this.themeResolver + "]"); @@ -493,19 +489,18 @@ public class DispatcherServlet extends FrameworkServlet { this.handlerMappings = null; if (this.detectAllHandlerMappings) { - // Find all HandlerMappings in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, HandlerMapping.class, true, false); if (!matchingBeans.isEmpty()) { - this.handlerMappings = new ArrayList(matchingBeans.values()); + this.handlerMappings = new ArrayList(matchingBeans.values()); // We keep HandlerMappings in sorted order. Collections.sort(this.handlerMappings, new OrderComparator()); } } else { try { - Object hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); + HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); this.handlerMappings = Collections.singletonList(hm); } catch (NoSuchBeanDefinitionException ex) { @@ -532,19 +527,18 @@ public class DispatcherServlet extends FrameworkServlet { this.handlerAdapters = null; if (this.detectAllHandlerAdapters) { - // Find all HandlerAdapters in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, HandlerAdapter.class, true, false); if (!matchingBeans.isEmpty()) { - this.handlerAdapters = new ArrayList(matchingBeans.values()); + this.handlerAdapters = new ArrayList(matchingBeans.values()); // We keep HandlerAdapters in sorted order. Collections.sort(this.handlerAdapters, new OrderComparator()); } } else { try { - Object ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); + HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); this.handlerAdapters = Collections.singletonList(ha); } catch (NoSuchBeanDefinitionException ex) { @@ -571,19 +565,18 @@ public class DispatcherServlet extends FrameworkServlet { this.handlerExceptionResolvers = null; if (this.detectAllHandlerExceptionResolvers) { - // Find all HandlerExceptionResolvers in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, HandlerExceptionResolver.class, true, false); if (!matchingBeans.isEmpty()) { - this.handlerExceptionResolvers = new ArrayList(matchingBeans.values()); + this.handlerExceptionResolvers = new ArrayList(matchingBeans.values()); // We keep HandlerExceptionResolvers in sorted order. Collections.sort(this.handlerExceptionResolvers, new OrderComparator()); } } else { try { - Object her = context.getBean( + HandlerExceptionResolver her = context.getBean( HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); this.handlerExceptionResolvers = Collections.singletonList(her); } @@ -608,7 +601,7 @@ public class DispatcherServlet extends FrameworkServlet { */ private void initRequestToViewNameTranslator(ApplicationContext context) { try { - this.viewNameTranslator = (RequestToViewNameTranslator) context.getBean( + this.viewNameTranslator = context.getBean( REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class); if (logger.isDebugEnabled()) { logger.debug("Using RequestToViewNameTranslator [" + this.viewNameTranslator + "]"); @@ -616,8 +609,7 @@ public class DispatcherServlet extends FrameworkServlet { } catch (NoSuchBeanDefinitionException ex) { // We need to use the default. - this.viewNameTranslator = - (RequestToViewNameTranslator) getDefaultStrategy(context, RequestToViewNameTranslator.class); + this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class); if (logger.isDebugEnabled()) { logger.debug("Unable to locate RequestToViewNameTranslator with name '" + REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME + @@ -635,19 +627,18 @@ public class DispatcherServlet extends FrameworkServlet { this.viewResolvers = null; if (this.detectAllViewResolvers) { - // Find all ViewResolvers in the ApplicationContext, - // including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( + // Find all ViewResolvers in the ApplicationContext, including ancestor contexts. + Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( context, ViewResolver.class, true, false); if (!matchingBeans.isEmpty()) { - this.viewResolvers = new ArrayList(matchingBeans.values()); + this.viewResolvers = new ArrayList(matchingBeans.values()); // We keep ViewResolvers in sorted order. Collections.sort(this.viewResolvers, new OrderComparator()); } } else { try { - Object vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); + ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); this.viewResolvers = Collections.singletonList(vr); } catch (NoSuchBeanDefinitionException ex) { @@ -698,11 +689,10 @@ public class DispatcherServlet extends FrameworkServlet { * @param context the current WebApplicationContext * @param strategyInterface the strategy interface * @return the corresponding strategy object - * @throws BeansException if initialization failed * @see #getDefaultStrategies */ - protected Object getDefaultStrategy(ApplicationContext context, Class strategyInterface) throws BeansException { - List strategies = getDefaultStrategies(context, strategyInterface); + protected T getDefaultStrategy(ApplicationContext context, Class strategyInterface) { + List strategies = getDefaultStrategies(context, strategyInterface); if (strategies.size() != 1) { throw new BeanInitializationException( "DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]"); @@ -718,42 +708,36 @@ public class DispatcherServlet extends FrameworkServlet { * @param context the current WebApplicationContext * @param strategyInterface the strategy interface * @return the List of corresponding strategy objects - * @throws BeansException if initialization failed */ - protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) throws BeansException { + @SuppressWarnings("unchecked") + protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) { String key = strategyInterface.getName(); - List strategies = null; String value = defaultStrategies.getProperty(key); if (value != null) { String[] classNames = StringUtils.commaDelimitedListToStringArray(value); - strategies = new ArrayList(classNames.length); - for (int i = 0; i < classNames.length; i++) { - String className = classNames[i]; - if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15 && className.indexOf("Annotation") != -1) { - // Skip Java 5 specific strategies when running on JDK 1.4... - continue; - } + List strategies = new ArrayList(classNames.length); + for (String className : classNames) { try { Class clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader()); Object strategy = createDefaultStrategy(context, clazz); - strategies.add(strategy); + strategies.add((T) strategy); } catch (ClassNotFoundException ex) { throw new BeanInitializationException( "Could not find DispatcherServlet's default strategy class [" + className + - "] for interface [" + key + "]", ex); + "] for interface [" + key + "]", ex); } catch (LinkageError err) { throw new BeanInitializationException( "Error loading DispatcherServlet's default strategy class [" + className + - "] for interface [" + key + "]: problem with class file or dependent class", err); + "] for interface [" + key + "]: problem with class file or dependent class", err); } } + return strategies; } else { - strategies = Collections.EMPTY_LIST; + return new LinkedList(); } - return strategies; } /** @@ -786,10 +770,10 @@ public class DispatcherServlet extends FrameworkServlet { // Keep a snapshot of the request attributes in case of an include, // to be able to restore the original attributes after the include. - Map attributesSnapshot = null; + Map attributesSnapshot = null; if (WebUtils.isIncludeRequest(request)) { logger.debug("Taking snapshot of request attributes before include"); - attributesSnapshot = new HashMap(); + attributesSnapshot = new HashMap(); Enumeration attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); @@ -1051,12 +1035,10 @@ public class DispatcherServlet extends FrameworkServlet { return handler; } - Iterator it = this.handlerMappings.iterator(); - while (it.hasNext()) { - HandlerMapping hm = (HandlerMapping) it.next(); + for (HandlerMapping hm : this.handlerMappings) { if (logger.isTraceEnabled()) { - logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" + - getServletName() + "'"); + logger.trace( + "Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'"); } handler = hm.getHandler(request); if (handler != null) { @@ -1091,9 +1073,7 @@ public class DispatcherServlet extends FrameworkServlet { * This is a fatal error. */ protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException { - Iterator it = this.handlerAdapters.iterator(); - while (it.hasNext()) { - HandlerAdapter ha = (HandlerAdapter) it.next(); + for (HandlerAdapter ha : this.handlerAdapters) { if (logger.isTraceEnabled()) { logger.trace("Testing handler adapter [" + ha + "]"); } @@ -1214,8 +1194,7 @@ public class DispatcherServlet extends FrameworkServlet { protected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest request) throws Exception { - for (Iterator it = this.viewResolvers.iterator(); it.hasNext();) { - ViewResolver viewResolver = (ViewResolver) it.next(); + for (ViewResolver viewResolver : this.viewResolvers) { View view = viewResolver.resolveViewName(viewName, locale); if (view != null) { return view; @@ -1266,7 +1245,7 @@ public class DispatcherServlet extends FrameworkServlet { // Need to copy into separate Collection here, to avoid side effects // on the Enumeration when removing attributes. - Set attrsToCheck = new HashSet(); + Set attrsToCheck = new HashSet(); Enumeration attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); @@ -1277,8 +1256,7 @@ public class DispatcherServlet extends FrameworkServlet { // Iterate over the attributes to check, restoring the original value // or removing the attribute, respectively, if appropriate. - for (Iterator it = attrsToCheck.iterator(); it.hasNext();) { - String attrName = (String) it.next(); + for (String attrName : attrsToCheck) { Object attrValue = attributesSnapshot.get(attrName); if (attrValue != null) { if (logger.isDebugEnabled()) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties index 977a04a99bf..95404a75500 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties @@ -11,7 +11,6 @@ org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.h org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\ org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\ - org.springframework.web.servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter,\ org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/UrlFilenameViewController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/UrlFilenameViewController.java index b7abc02dc43..8b692442b94 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/UrlFilenameViewController.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/UrlFilenameViewController.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,10 +17,9 @@ package org.springframework.web.servlet.mvc; import java.util.Map; - +import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; -import org.springframework.core.CollectionFactory; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerMapping; @@ -55,7 +54,7 @@ public class UrlFilenameViewController extends AbstractUrlViewController { private String suffix = ""; /** Request URL path String --> view name String */ - private final Map viewNameCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map viewNameCache = new ConcurrentHashMap(); /** @@ -125,7 +124,7 @@ public class UrlFilenameViewController extends AbstractUrlViewController { * @see #postProcessViewName */ protected String getViewNameForUrlPath(String uri) { - String viewName = (String) this.viewNameCache.get(uri); + String viewName = this.viewNameCache.get(uri); if (viewName == null) { viewName = extractViewNameFromUrlPath(uri); viewName = postProcessViewName(viewName); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java index 86155739489..466e67b0e85 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java @@ -654,10 +654,9 @@ public class AnnotationMethodHandlerAdapter extends WebContentGenerator implemen @Override @SuppressWarnings({"unchecked"}) - protected Object resolvePathVariable(String pathVarName, - MethodParameter methodParam, - NativeWebRequest webRequest, - Object handlerForInitBinderCall) throws Exception { + protected Object resolvePathVariable(String pathVarName, MethodParameter methodParam, + NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { + Class paramType = methodParam.getParameterType(); if (pathVarName.length() == 0) { pathVarName = methodParam.getParameterName(); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/InternalPathMethodNameResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/InternalPathMethodNameResolver.java index e345a148b94..875e132b67c 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/InternalPathMethodNameResolver.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/multiaction/InternalPathMethodNameResolver.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,8 +17,8 @@ package org.springframework.web.servlet.mvc.multiaction; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; -import org.springframework.core.CollectionFactory; import org.springframework.web.util.WebUtils; /** @@ -43,7 +43,7 @@ public class InternalPathMethodNameResolver extends AbstractUrlMethodNameResolve private String suffix = ""; /** Request URL path String --> method name String */ - private final Map methodNameCache = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map methodNameCache = new ConcurrentHashMap(); /** @@ -86,7 +86,7 @@ public class InternalPathMethodNameResolver extends AbstractUrlMethodNameResolve */ @Override protected String getHandlerMethodNameForUrlPath(String urlPath) { - String methodName = (String) this.methodNameCache.get(urlPath); + String methodName = this.methodNameCache.get(urlPath); if (methodName == null) { methodName = extractHandlerMethodNameFromUrlPath(urlPath); methodName = postProcessHandlerMethodName(methodName); diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/AbstractControllerUrlHandlerMapping.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/AbstractControllerUrlHandlerMapping.java index 153616d4af6..478752851c0 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/AbstractControllerUrlHandlerMapping.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/AbstractControllerUrlHandlerMapping.java @@ -19,11 +19,8 @@ package org.springframework.web.servlet.mvc.support; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; -import org.springframework.core.JdkVersion; -import org.springframework.util.ClassUtils; import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping; /** @@ -37,32 +34,19 @@ import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMappin */ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping { - private static final String ANNOTATION_PREDICATE_NAME = - "org.springframework.web.servlet.mvc.support.AnnotationControllerTypePredicate"; + private ControllerTypePredicate predicate = new AnnotationControllerTypePredicate(); - private ControllerTypePredicate predicate; + private Set excludedPackages = Collections.singleton("org.springframework.web.servlet.mvc"); - private Set excludedPackages = Collections.singleton("org.springframework.web.servlet.mvc"); - - private Set excludedClasses = Collections.EMPTY_SET; - - - /** - * Activates detection of annotated controllers when running on JDK 1.5 or higher. - */ - public AbstractControllerUrlHandlerMapping() { - this.predicate = (JdkVersion.isAtLeastJava15() ? - instantiateAnnotationPredicate() : new ControllerTypePredicate()); - } + private Set excludedClasses = Collections.emptySet(); /** * Set whether to activate or deactivate detection of annotated controllers. - *

    Annotated controllers will by included by default when runnong on JDK 1.5 or higher. */ public void setIncludeAnnotatedControllers(boolean includeAnnotatedControllers) { this.predicate = (includeAnnotatedControllers ? - instantiateAnnotationPredicate() : new ControllerTypePredicate()); + new AnnotationControllerTypePredicate() : new ControllerTypePredicate()); } /** @@ -77,8 +61,8 @@ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetect * alongside this ControllerClassNameHandlerMapping for application controllers. */ public void setExcludedPackages(String[] excludedPackages) { - this.excludedPackages = - (excludedPackages != null ? new HashSet(Arrays.asList(excludedPackages)) : Collections.EMPTY_SET); + this.excludedPackages = (excludedPackages != null) ? + new HashSet(Arrays.asList(excludedPackages)) : new HashSet(); } /** @@ -86,19 +70,8 @@ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetect * Any such classes will simply be ignored by this HandlerMapping. */ public void setExcludedClasses(Class[] excludedClasses) { - this.excludedClasses = - (excludedClasses != null ? new HashSet(Arrays.asList(excludedClasses)) : Collections.EMPTY_SET); - } - - - private ControllerTypePredicate instantiateAnnotationPredicate() { - try { - return (ControllerTypePredicate) ClassUtils.forName(ANNOTATION_PREDICATE_NAME, - AbstractControllerUrlHandlerMapping.class.getClassLoader()).newInstance(); - } - catch (Exception ex) { - throw new IllegalStateException("Cannot load AnnotationControllerTypePredicate", ex); - } + this.excludedClasses = (excludedClasses != null) ? + new HashSet(Arrays.asList(excludedClasses)) : new HashSet(); } @@ -141,8 +114,7 @@ public abstract class AbstractControllerUrlHandlerMapping extends AbstractDetect return false; } String beanClassName = beanClass.getName(); - for (Iterator it = this.excludedPackages.iterator(); it.hasNext();) { - String packageName = (String) it.next(); + for (String packageName : this.excludedPackages) { if (beanClassName.startsWith(packageName)) { if (logger.isDebugEnabled()) { logger.debug("Excluding controller bean '" + beanName + "' from class name mapping " + diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerTypePredicate.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerTypePredicate.java index 50fcba66092..fb0c149968c 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerTypePredicate.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/support/ControllerTypePredicate.java @@ -18,7 +18,6 @@ package org.springframework.web.servlet.mvc.support; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; -import org.springframework.web.servlet.mvc.throwaway.ThrowawayController; /** * Internal helper class that identifies controller types. @@ -29,12 +28,11 @@ import org.springframework.web.servlet.mvc.throwaway.ThrowawayController; class ControllerTypePredicate { public boolean isControllerType(Class beanClass) { - return (Controller.class.isAssignableFrom(beanClass) || - ThrowawayController.class.isAssignableFrom(beanClass)); + return Controller.class.isAssignableFrom(beanClass); } public boolean isMultiActionControllerType(Class beanClass) { - return (MultiActionController.class.isAssignableFrom(beanClass)); + return MultiActionController.class.isAssignableFrom(beanClass); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/ThrowawayController.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/ThrowawayController.java deleted file mode 100644 index 49535eac2b9..00000000000 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/ThrowawayController.java +++ /dev/null @@ -1,70 +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.web.servlet.mvc.throwaway; - -import org.springframework.web.servlet.ModelAndView; - -/** - * ThrowawayController is an alternative to Spring's default Controller interface, - * for executable per-request command instances that are not aware of the Servlet API. - * In contrast to Controller, implementing beans are not supposed to be defined as - * Servlet/Struts-style singletons that process a HttpServletRequest but rather as - * WebWork/Maverick-style prototypes that get populated with request parameters, - * executed to determine a view, and thrown away afterwards. - * - *

    The main advantage of this controller programming model is that controllers - * are testable without HttpServletRequest/HttpServletResponse mocks, just like - * WebWork actions. They are still web UI workflow controllers: Spring does not - * aim for the arguably hard-to-achieve reusability of such controllers in non-web - * environments, as XWork (the generic command framework from WebWork2) does - * but just for ease of testing. - * - *

    A ThrowawayController differs from the command notion of Base- or - * AbstractCommandController in that a ThrowawayController is an executable - * command that contains workflow logic to determine the next view to render, - * while BaseCommandController treats commands as plain parameter holders. - * - *

    If binding request parameters to this controller fails, a fatal BindException - * will be thrown. - * - *

    If you need access to the HttpServletRequest and/or HttpServletResponse, - * consider implementing Controller or deriving from AbstractCommandController. - * ThrowawayController is specifically intended for controllers that are not aware - * of the Servlet API at all. Accordingly, if you need to handle session form objects - * or even wizard forms, consider the corresponding Controller subclasses. - * - * @author Juergen Hoeller - * @since 08.12.2003 - * @see org.springframework.web.servlet.mvc.Controller - * @see org.springframework.web.servlet.mvc.AbstractCommandController - * @deprecated as of Spring 2.5, in favor of annotation-based controllers. - * To be removed in Spring 3.0. - */ -@Deprecated -public interface ThrowawayController { - - /** - * Execute this controller according to its bean properties. - * Gets invoked after a new instance of the controller has been populated with request - * parameters. Is supposed to return a ModelAndView in any case, as it is not able to - * generate a response itself. - * @return a ModelAndView to render - * @throws Exception in case of errors - */ - ModelAndView execute() throws Exception; - -} diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/ThrowawayControllerHandlerAdapter.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/ThrowawayControllerHandlerAdapter.java deleted file mode 100644 index 0bb1fcdbb98..00000000000 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/ThrowawayControllerHandlerAdapter.java +++ /dev/null @@ -1,135 +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.web.servlet.mvc.throwaway; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.bind.ServletRequestDataBinder; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.ModelAndView; - -/** - * Adapter to use the ThrowawayController workflow interface with the - * generic DispatcherServlet. Does not support last-modified checks. - * - *

    This is an SPI class, not used directly by application code. - * It can be explicitly configured in a DispatcherServlet context, to use a - * customized version instead of the default ThrowawayControllerHandlerAdapter. - * - * @author Juergen Hoeller - * @since 08.12.2003 - * @deprecated as of Spring 2.5, in favor of annotation-based controllers. - * To be removed in Spring 3.0. - */ -@Deprecated -public class ThrowawayControllerHandlerAdapter implements HandlerAdapter { - - public static final String DEFAULT_COMMAND_NAME = "throwawayController"; - - private String commandName = DEFAULT_COMMAND_NAME; - - - /** - * Set the name of the command in the model. - * The command object will be included in the model under this name. - */ - public final void setCommandName(String commandName) { - this.commandName = commandName; - } - - /** - * Return the name of the command in the model. - */ - public final String getCommandName() { - return this.commandName; - } - - - public boolean supports(Object handler) { - return (handler instanceof ThrowawayController); - } - - - /** - * This implementation binds request parameters to the ThrowawayController - * instance and then calls execute on it. - * @see #createBinder - * @see ThrowawayController#execute - */ - public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - - ThrowawayController throwaway = (ThrowawayController) handler; - - ServletRequestDataBinder binder = createBinder(request, throwaway); - binder.bind(request); - binder.closeNoCatch(); - - return throwaway.execute(); - } - - /** - * Create a new binder instance for the given command and request. - *

    Called by bindAndValidate. Can be overridden to plug in - * custom ServletRequestDataBinder subclasses. - *

    Default implementation creates a standard ServletRequestDataBinder, - * sets the specified MessageCodesResolver (if any), and invokes initBinder. - * Note that initBinder will not be invoked if you override this method! - * @param request current HTTP request - * @param command the command to bind onto - * @return the new binder instance - * @throws Exception in case of invalid state or arguments - * @see #initBinder - * @see #getCommandName - */ - protected ServletRequestDataBinder createBinder(HttpServletRequest request, ThrowawayController command) - throws Exception { - - ServletRequestDataBinder binder = new ServletRequestDataBinder(command, getCommandName()); - initBinder(request, binder); - return binder; - } - - /** - * Initialize the given binder instance, for example with custom editors. - * Called by createBinder. - *

    This method allows you to register custom editors for certain fields of your - * command class. For instance, you will be able to transform Date objects into a - * String pattern and back, in order to allow your JavaBeans to have Date properties - * and still be able to set and display them in an HTML interface. - *

    Default implementation is empty. - * @param request current HTTP request - * @param binder new binder instance - * @throws Exception in case of invalid state or arguments - * @see #createBinder - * @see org.springframework.validation.DataBinder#registerCustomEditor - * @see org.springframework.beans.propertyeditors.CustomDateEditor - */ - protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) - throws Exception { - } - - - /** - * This implementation always returns -1, as last-modified checks are not supported. - */ - public long getLastModified(HttpServletRequest request, Object handler) { - return -1; - } - -} diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/package.html b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/package.html deleted file mode 100644 index c8edb529dd2..00000000000 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/throwaway/package.html +++ /dev/null @@ -1,8 +0,0 @@ - - - -Throwaway command controllers are a WebWork/Maverick-style alternative -to Spring's default Servlet/Struts-style Controller approach. - - - diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java index 6c57dbdc40a..854082aed53 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java @@ -19,10 +19,8 @@ package org.springframework.web.servlet.tags.form; import java.beans.PropertyEditor; import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; -import org.springframework.core.JdkVersion; import org.springframework.core.enums.LabeledEnum; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; @@ -134,14 +132,13 @@ abstract class SelectedValueComparator { private static boolean exhaustiveCollectionCompare( Collection collection, Object candidateValue, BindStatus bindStatus) { - Map convertedValueCache = new HashMap(1); + Map convertedValueCache = new HashMap(1); PropertyEditor editor = null; boolean candidateIsString = (candidateValue instanceof String); if (!candidateIsString) { editor = bindStatus.findEditor(candidateValue.getClass()); } - for (Iterator it = collection.iterator(); it.hasNext();) { - Object element = it.next(); + for (Object element : collection) { if (editor == null && element != null && candidateIsString) { editor = bindStatus.findEditor(element.getClass()); } @@ -152,8 +149,8 @@ abstract class SelectedValueComparator { return false; } - private static boolean exhaustiveCompare( - Object boundValue, Object candidate, PropertyEditor editor, Map convertedValueCache) { + private static boolean exhaustiveCompare(Object boundValue, Object candidate, + PropertyEditor editor, Map convertedValueCache) { String candidateDisplayString = ValueFormatter.getDisplayString(candidate, editor, false); if (boundValue instanceof LabeledEnum) { @@ -167,7 +164,7 @@ abstract class SelectedValueComparator { return true; } } - else if (JdkVersion.isAtLeastJava15() && boundValue.getClass().isEnum()) { + else if (boundValue.getClass().isEnum()) { Enum boundEnum = (Enum) boundValue; String enumCodeAsString = ObjectUtils.getDisplayString(boundEnum.name()); if (enumCodeAsString.equals(candidateDisplayString)) { 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 67893c54a3a..1180b2268b8 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 @@ -18,13 +18,11 @@ package org.springframework.web.servlet.view; import java.util.Enumeration; import java.util.Map; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import org.springframework.util.ClassUtils; import org.springframework.web.servlet.support.RequestContext; /** @@ -54,12 +52,6 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView { public static final String SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE = "springMacroRequestContext"; - // Determine whether the Servlet 2.4 HttpServletResponse.getContentType() - // method is available. - private static boolean responseGetContentTypeAvailable = - ClassUtils.hasMethod(HttpServletResponse.class, "getContentType", new Class[0]); - - private boolean exposeRequestAttributes = false; private boolean allowRequestOverride = false; @@ -185,18 +177,7 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView { * @see #setContentType */ protected void applyContentType(HttpServletResponse response) { - boolean apply = true; - if (responseGetContentTypeAvailable) { - try { - apply = (response.getContentType() == null); - } - catch (Throwable ex) { - // Probably Servlet 2.4 API present but not implemented. - // Behave like on Servlet 2.3... - apply = true; - } - } - if (apply) { + if (response.getContentType() == null) { response.setContentType(getContentType()); } } 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 d6c10325732..39e5171053f 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 @@ -26,7 +26,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; @@ -797,9 +796,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView { return provider.create(report); } catch (JRException ex) { - IllegalArgumentException iaex = new IllegalArgumentException("Supplied JRDataSourceProvider is invalid"); - iaex.initCause(ex); - throw iaex; + throw new IllegalArgumentException("Supplied JRDataSourceProvider is invalid", ex); } } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SimpleSpringPreparerFactory.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SimpleSpringPreparerFactory.java index 8a76f833d64..3fa0999403c 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SimpleSpringPreparerFactory.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SimpleSpringPreparerFactory.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,13 +17,13 @@ package org.springframework.web.servlet.view.tiles2; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.tiles.TilesException; import org.apache.tiles.preparer.NoSuchPreparerException; import org.apache.tiles.preparer.PreparerException; import org.apache.tiles.preparer.ViewPreparer; -import org.springframework.core.CollectionFactory; import org.springframework.web.context.WebApplicationContext; /** @@ -39,16 +39,16 @@ import org.springframework.web.context.WebApplicationContext; public class SimpleSpringPreparerFactory extends AbstractSpringPreparerFactory { /** Cache of shared ViewPreparer instances: bean name --> bean instance */ - private final Map sharedPreparers = CollectionFactory.createConcurrentMapIfPossible(16); + private final Map sharedPreparers = new ConcurrentHashMap(); @Override protected ViewPreparer getPreparer(String name, WebApplicationContext context) throws TilesException { // Quick check on the concurrent map first, with minimal locking. - ViewPreparer preparer = (ViewPreparer) this.sharedPreparers.get(name); + ViewPreparer preparer = this.sharedPreparers.get(name); if (preparer == null) { synchronized (this.sharedPreparers) { - preparer = (ViewPreparer) this.sharedPreparers.get(name); + preparer = this.sharedPreparers.get(name); if (preparer == null) { try { Class beanClass = context.getClassLoader().loadClass(name); diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java b/org.springframework.web.servlet/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java index 93976202b20..527f05c150a 100644 --- a/org.springframework.web.servlet/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java +++ b/org.springframework.web.servlet/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java @@ -106,7 +106,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private String contentType; - private final Map parameters = new LinkedHashMap(16); + private final Map parameters = new LinkedHashMap(16); private String protocol = DEFAULT_PROTOCOL; @@ -145,7 +145,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private Cookie[] cookies; /** - * The key is the lowercase header name; the value is a {@link org.springframework.mock.web.HeaderValueHolder} object. + * The key is the lowercase header name; the value is a {@link HeaderValueHolder} object. */ private final Hashtable headers = new Hashtable(); @@ -182,8 +182,8 @@ public class MockHttpServletRequest implements HttpServletRequest { /** * Create a new MockHttpServletRequest with a default - * {@link org.springframework.mock.web.MockServletContext}. - * @see org.springframework.mock.web.MockServletContext + * {@link MockServletContext}. + * @see MockServletContext */ public MockHttpServletRequest() { this(null, "", ""); @@ -191,12 +191,12 @@ public class MockHttpServletRequest implements HttpServletRequest { /** * Create a new MockHttpServletRequest with a default - * {@link org.springframework.mock.web.MockServletContext}. + * {@link MockServletContext}. * @param method the request method (may be null) * @param requestURI the request URI (may be null) * @see #setMethod * @see #setRequestURI - * @see org.springframework.mock.web.MockServletContext + * @see MockServletContext */ public MockHttpServletRequest(String method, String requestURI) { this(null, method, requestURI); @@ -206,7 +206,7 @@ public class MockHttpServletRequest implements HttpServletRequest { * Create a new MockHttpServletRequest. * @param servletContext the ServletContext that the request runs in * (may be null to use a default MockServletContext) - * @see org.springframework.mock.web.MockServletContext + * @see MockServletContext */ public MockHttpServletRequest(ServletContext servletContext) { this(servletContext, "", ""); @@ -220,7 +220,7 @@ public class MockHttpServletRequest implements HttpServletRequest { * @param requestURI the request URI (may be null) * @see #setMethod * @see #setRequestURI - * @see org.springframework.mock.web.MockServletContext + * @see MockServletContext */ public MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) { this.servletContext = (servletContext != null ? servletContext : new MockServletContext()); @@ -348,8 +348,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void setParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); - for (Iterator it = params.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + for (Object key : params.keySet()) { Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); @@ -360,8 +359,9 @@ public class MockHttpServletRequest implements HttpServletRequest { this.setParameter((String) key, (String[]) value); } else { - throw new IllegalArgumentException("Parameter map value must be single value " + - " or array of type [" + String.class.getName() + "]"); + throw new IllegalArgumentException( + "Parameter map value must be single value " + " or array of type [" + String.class.getName() + + "]"); } } } @@ -382,7 +382,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void addParameter(String name, String[] values) { Assert.notNull(name, "Parameter name must not be null"); - 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); @@ -401,8 +401,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void addParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); - for (Iterator it = params.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + for (Object key : params.keySet()) { Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); @@ -436,7 +435,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public String getParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - String[] arr = (String[]) this.parameters.get(name); + String[] arr = this.parameters.get(name); return (arr != null && arr.length > 0 ? arr[0] : null); } @@ -446,7 +445,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public String[] getParameterValues(String name) { Assert.notNull(name, "Parameter name must not be null"); - return (String[]) this.parameters.get(name); + return this.parameters.get(name); } public Map getParameterMap() { @@ -750,14 +749,6 @@ public class MockHttpServletRequest implements HttpServletRequest { return this.remoteUser; } - /** - * @deprecated in favor of addUserRole - * @see #addUserRole - */ - public void addRole(String role) { - addUserRole(role); - } - public void addUserRole(String role) { this.userRoles.add(role); } @@ -855,4 +846,4 @@ public class MockHttpServletRequest implements HttpServletRequest { return isRequestedSessionIdFromURL(); } -} \ No newline at end of file +} diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index 0364bc6abb4..3cf02ee6a68 100644 --- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -698,43 +698,6 @@ public class DispatcherServletTests extends TestCase { assertNull(myServlet.getServletConfig()); } - public void testThrowawayController() throws Exception { - SimpleWebApplicationContext.TestThrowawayController.counter = 0; - - MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/throwaway.do"); - request.addParameter("myInt", "5"); - MockHttpServletResponse response = new MockHttpServletResponse(); - - simpleDispatcherServlet.service(request, response); - assertTrue("Correct response", "view5".equals(response.getForwardedUrl())); - Assert.assertEquals(1, SimpleWebApplicationContext.TestThrowawayController.counter); - - request = new MockHttpServletRequest(getServletContext(), "GET", "/throwaway.do"); - request.addParameter("myInt", "5"); - response = new MockHttpServletResponse(); - - simpleDispatcherServlet.service(request, response); - assertTrue("Correct response", "view5".equals(response.getForwardedUrl())); - Assert.assertEquals(2, SimpleWebApplicationContext.TestThrowawayController.counter); - } - - public void testThrowawayControllerWithBindingFailure() throws Exception { - SimpleWebApplicationContext.TestThrowawayController.counter = 0; - MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/throwaway.do"); - request.addParameter("myInt", "5x"); - MockHttpServletResponse response = new MockHttpServletResponse(); - - try { - simpleDispatcherServlet.service(request, response); - fail("Should have thrown ServletException"); - } - catch (ServletException ex) { - // expected - assertTrue(ex.getRootCause() instanceof BindException); - Assert.assertEquals(1, SimpleWebApplicationContext.TestThrowawayController.counter); - } - } - public void testWebApplicationContextLookup() { MockServletContext servletContext = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/invalid.do"); diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java index 7851da8c297..b30b02e1123 100644 --- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java +++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java @@ -35,7 +35,6 @@ import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.mvc.LastModified; import org.springframework.web.servlet.mvc.SimpleFormController; -import org.springframework.web.servlet.mvc.throwaway.ThrowawayController; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.servlet.theme.AbstractThemeResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -56,8 +55,6 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext { registerSingleton("/locale.do", LocaleChecker.class); - registerPrototype("/throwaway.do", TestThrowawayController.class); - addMessage("test", Locale.ENGLISH, "test message"); addMessage("test", Locale.CANADA, "Canadian & test message"); addMessage("testArgs", Locale.ENGLISH, "test {0} message {1}"); @@ -118,24 +115,4 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext { } } - - public static class TestThrowawayController implements ThrowawayController { - - public static int counter = 0; - - private int myInt; - - public TestThrowawayController() { - counter++; - } - - public void setMyInt(int myInt) { - this.myInt = myInt; - } - - public ModelAndView execute() throws Exception { - return new ModelAndView("view" + this.myInt); - } - } - -} \ No newline at end of file +} diff --git a/org.springframework.web.servlet/web-servlet.iml b/org.springframework.web.servlet/web-servlet.iml index 4c57df3e71b..98ac6a0be88 100644 --- a/org.springframework.web.servlet/web-servlet.iml +++ b/org.springframework.web.servlet/web-servlet.iml @@ -1,267 +1,267 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.springframework.web/ivy.xml b/org.springframework.web/ivy.xml index bfbf665f3d7..95780925b31 100644 --- a/org.springframework.web/ivy.xml +++ b/org.springframework.web/ivy.xml @@ -42,7 +42,6 @@ - diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapExporter.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapExporter.java index 6d2d245db25..27d4ba86d2a 100644 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapExporter.java +++ b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapExporter.java @@ -19,13 +19,11 @@ package org.springframework.remoting.caucho; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.lang.reflect.Constructor; import com.caucho.burlap.io.BurlapInput; import com.caucho.burlap.io.BurlapOutput; import com.caucho.burlap.server.BurlapSkeleton; -import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.remoting.support.RemoteExporter; import org.springframework.util.Assert; @@ -36,9 +34,7 @@ import org.springframework.util.Assert; *

    Burlap is a slim, XML-based RPC protocol. * For information on Burlap, see the * Burlap website. - * - *

    This exporter will work with both Burlap 2.x and 3.x (respectively - * Resin 2.x and 3.x), autodetecting the corresponding skeleton class. + * This exporter requires Burlap 3.x. * * @author Juergen Hoeller * @since 2.5.1 @@ -59,24 +55,9 @@ public class BurlapExporter extends RemoteExporter implements InitializingBean { * Initialize this service exporter. */ public void prepare() { - try { - try { - // Try Burlap 3.x (with service interface argument). - Constructor ctor = BurlapSkeleton.class.getConstructor(new Class[] {Object.class, Class.class}); - checkService(); - checkServiceInterface(); - this.skeleton = (BurlapSkeleton) - ctor.newInstance(new Object[] {getProxyForService(), getServiceInterface()}); - } - catch (NoSuchMethodException ex) { - // Fall back to Burlap 2.x (without service interface argument). - Constructor ctor = BurlapSkeleton.class.getConstructor(new Class[] {Object.class}); - this.skeleton = (BurlapSkeleton) ctor.newInstance(new Object[] {getProxyForService()}); - } - } - catch (Exception ex) { - throw new BeanInitializationException("Burlap skeleton initialization failed", ex); - } + checkService(); + checkServiceInterface(); + this.skeleton = new BurlapSkeleton(getProxyForService(), getServiceInterface()); } @@ -97,11 +78,13 @@ public class BurlapExporter extends RemoteExporter implements InitializingBean { inputStream.close(); } catch (IOException ex) { + // ignore } try { outputStream.close(); } catch (IOException ex) { + // ignore } resetThreadContextClassLoader(originalClassLoader); } diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapServiceExporter.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapServiceExporter.java index 4f1dc14a6b7..34c28129a43 100644 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapServiceExporter.java +++ b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/BurlapServiceExporter.java @@ -36,9 +36,7 @@ import org.springframework.web.util.NestedServletException; *

    Burlap is a slim, XML-based RPC protocol. * For information on Burlap, see the * Burlap website. - * - *

    This exporter will work with both Burlap 2.x and 3.x (respectively - * Resin 2.x and 3.x), autodetecting the corresponding skeleton class. + * This exporter requires Burlap 3.x. * *

    Note: Burlap services exported with this class can be accessed by * any Burlap client, as there isn't any special handling involved. diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/Hessian1SkeletonInvoker.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/Hessian1SkeletonInvoker.java deleted file mode 100644 index 62b25571eb6..00000000000 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/Hessian1SkeletonInvoker.java +++ /dev/null @@ -1,89 +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.remoting.caucho; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Method; - -import com.caucho.hessian.io.HessianInput; -import com.caucho.hessian.io.HessianOutput; -import com.caucho.hessian.io.SerializerFactory; -import com.caucho.hessian.server.HessianSkeleton; - -import org.springframework.util.ClassUtils; - -/** - * Concrete HessianSkeletonInvoker for the Hessian 1 protocol - * (version 3.0.19 or lower). - * - * @author Juergen Hoeller - * @since 2.0 - */ -class Hessian1SkeletonInvoker extends HessianSkeletonInvoker { - - private static final Method invokeMethod; - - private static final boolean applySerializerFactoryToOutput; - - static { - invokeMethod = ClassUtils.getMethodIfAvailable( - HessianSkeleton.class, "invoke", new Class[] {HessianInput.class, HessianOutput.class}); - applySerializerFactoryToOutput = - ClassUtils.hasMethod(HessianOutput.class, "setSerializerFactory", new Class[] {SerializerFactory.class}); - } - - - public Hessian1SkeletonInvoker(HessianSkeleton skeleton, SerializerFactory serializerFactory) { - super(skeleton, serializerFactory); - if (invokeMethod == null) { - throw new IllegalStateException("Hessian 1 (version 3.0.19-) not present"); - } - } - - @Override - public void invoke(InputStream inputStream, OutputStream outputStream) throws Throwable { - HessianInput in = new HessianInput(inputStream); - HessianOutput out = new HessianOutput(outputStream); - if (this.serializerFactory != null) { - in.setSerializerFactory(this.serializerFactory); - if (applySerializerFactoryToOutput) { - out.setSerializerFactory(this.serializerFactory); - } - } - try { - invokeMethod.invoke(this.skeleton, new Object[] {in, out}); - } - finally { - try { - in.close(); - inputStream.close(); - } - catch (IOException ex) { - } - try { - out.close(); - outputStream.close(); - } - catch (IOException ex) { - } - } - - } - -} diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/Hessian2SkeletonInvoker.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/Hessian2SkeletonInvoker.java deleted file mode 100644 index 2e66647be82..00000000000 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/Hessian2SkeletonInvoker.java +++ /dev/null @@ -1,124 +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.remoting.caucho; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; - -import com.caucho.hessian.io.AbstractHessianOutput; -import com.caucho.hessian.io.Hessian2Input; -import com.caucho.hessian.io.Hessian2Output; -import com.caucho.hessian.io.HessianDebugInputStream; -import com.caucho.hessian.io.HessianDebugOutputStream; -import com.caucho.hessian.io.HessianOutput; -import com.caucho.hessian.io.SerializerFactory; -import com.caucho.hessian.server.HessianSkeleton; -import org.apache.commons.logging.Log; - -import org.springframework.util.ClassUtils; -import org.springframework.util.CommonsLogWriter; - -/** - * Concrete HessianSkeletonInvoker for the Hessian 2 protocol - * (version 3.0.20 or higher). - * - * @author Juergen Hoeller - * @author Andy Piper - * @since 2.0 - */ -class Hessian2SkeletonInvoker extends HessianSkeletonInvoker { - - private static final boolean debugOutputStreamAvailable = ClassUtils.isPresent( - "com.caucho.hessian.io.HessianDebugOutputStream", Hessian2SkeletonInvoker.class.getClassLoader()); - - private final Log debugLogger; - - - public Hessian2SkeletonInvoker(HessianSkeleton skeleton, SerializerFactory serializerFactory, Log debugLog) { - super(skeleton, serializerFactory); - this.debugLogger = debugLog; - } - - @Override - public void invoke(final InputStream inputStream, final OutputStream outputStream) throws Throwable { - InputStream isToUse = inputStream; - OutputStream osToUse = outputStream; - - if (this.debugLogger != null && this.debugLogger.isDebugEnabled()) { - PrintWriter debugWriter = new PrintWriter(new CommonsLogWriter(this.debugLogger)); - isToUse = new HessianDebugInputStream(inputStream, debugWriter); - if (debugOutputStreamAvailable) { - osToUse = DebugStreamFactory.createDebugOutputStream(outputStream, debugWriter); - } - } - - Hessian2Input in = new Hessian2Input(isToUse); - if (this.serializerFactory != null) { - in.setSerializerFactory(this.serializerFactory); - } - - int code = in.read(); - if (code != 'c') { - throw new IOException("expected 'c' in hessian input at " + code); - } - - AbstractHessianOutput out = null; - int major = in.read(); - int minor = in.read(); - if (major >= 2) { - out = new Hessian2Output(osToUse); - } - else { - out = new HessianOutput(osToUse); - } - if (this.serializerFactory != null) { - out.setSerializerFactory(this.serializerFactory); - } - - try { - this.skeleton.invoke(in, out); - } - finally { - try { - in.close(); - isToUse.close(); - } - catch (IOException ex) { - } - try { - out.close(); - osToUse.close(); - } - catch (IOException ex) { - } - } - } - - - /** - * Inner class to avoid hard dependency on Hessian 3.1.3's HessianDebugOutputStream. - */ - private static class DebugStreamFactory { - - public static OutputStream createDebugOutputStream(OutputStream os, PrintWriter debug) { - return new HessianDebugOutputStream(os, debug); - } - } - -} diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianExporter.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianExporter.java index 0608a5fe89d..07c68ece49c 100644 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianExporter.java +++ b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianExporter.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,19 +16,26 @@ package org.springframework.remoting.caucho; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.lang.reflect.Constructor; +import java.io.PrintWriter; +import com.caucho.hessian.io.AbstractHessianOutput; +import com.caucho.hessian.io.Hessian2Input; +import com.caucho.hessian.io.Hessian2Output; +import com.caucho.hessian.io.HessianDebugInputStream; +import com.caucho.hessian.io.HessianDebugOutputStream; +import com.caucho.hessian.io.HessianOutput; import com.caucho.hessian.io.SerializerFactory; import com.caucho.hessian.server.HessianSkeleton; import org.apache.commons.logging.Log; -import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.remoting.support.RemoteExporter; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.CommonsLogWriter; /** * General stream-based protocol exporter for a Hessian endpoint. @@ -36,11 +43,7 @@ import org.springframework.util.ClassUtils; *

    Hessian is a slim, binary RPC protocol. * For information on Hessian, see the * Hessian website. - * - *

    This exporter will work with both Hessian 2.x and 3.x (respectively - * Resin 2.x and 3.x), autodetecting the corresponding skeleton class. - * As of Spring 2.0, it is also compatible with the new Hessian 2 protocol - * (a.k.a. Hessian 3.0.20+), while remaining compatible with older versions. + * This exporter requires Hessian 3.0.20 or above. * * @author Juergen Hoeller * @since 2.5.1 @@ -50,15 +53,14 @@ import org.springframework.util.ClassUtils; */ public class HessianExporter extends RemoteExporter implements InitializingBean { - private static final boolean hessian2Available = - ClassUtils.isPresent("com.caucho.hessian.io.Hessian2Input", HessianServiceExporter.class.getClassLoader()); - + private static final boolean debugOutputStreamAvailable = ClassUtils.isPresent( + "com.caucho.hessian.io.HessianDebugOutputStream", HessianExporter.class.getClassLoader()); private SerializerFactory serializerFactory = new SerializerFactory(); private Log debugLogger; - private HessianSkeletonInvoker skeletonInvoker; + private HessianSkeleton skeleton; /** @@ -97,35 +99,9 @@ public class HessianExporter extends RemoteExporter implements InitializingBean * Initialize this exporter. */ public void prepare() { - HessianSkeleton skeleton = null; - - try { - try { - // Try Hessian 3.x (with service interface argument). - Constructor ctor = HessianSkeleton.class.getConstructor(new Class[] {Object.class, Class.class}); - checkService(); - checkServiceInterface(); - skeleton = (HessianSkeleton) - ctor.newInstance(new Object[] {getProxyForService(), getServiceInterface()}); - } - catch (NoSuchMethodException ex) { - // Fall back to Hessian 2.x (without service interface argument). - Constructor ctor = HessianSkeleton.class.getConstructor(new Class[] {Object.class}); - skeleton = (HessianSkeleton) ctor.newInstance(new Object[] {getProxyForService()}); - } - } - catch (Throwable ex) { - throw new BeanInitializationException("Hessian skeleton initialization failed", ex); - } - - if (hessian2Available) { - // Hessian 2 (version 3.0.20+). - this.skeletonInvoker = new Hessian2SkeletonInvoker(skeleton, this.serializerFactory, this.debugLogger); - } - else { - // Hessian 1 (version 3.0.19-). - this.skeletonInvoker = new Hessian1SkeletonInvoker(skeleton, this.serializerFactory); - } + checkService(); + checkServiceInterface(); + this.skeleton = new HessianSkeleton(getProxyForService(), getServiceInterface()); } @@ -136,14 +112,81 @@ public class HessianExporter extends RemoteExporter implements InitializingBean * @throws Throwable if invocation failed */ public void invoke(InputStream inputStream, OutputStream outputStream) throws Throwable { - Assert.notNull(this.skeletonInvoker, "Hessian exporter has not been initialized"); + Assert.notNull(this.skeleton, "Hessian exporter has not been initialized"); ClassLoader originalClassLoader = overrideThreadContextClassLoader(); try { - this.skeletonInvoker.invoke(inputStream, outputStream); + doInvoke(inputStream, outputStream); } finally { resetThreadContextClassLoader(originalClassLoader); } } + public void doInvoke(final InputStream inputStream, final OutputStream outputStream) throws Throwable { + InputStream isToUse = inputStream; + OutputStream osToUse = outputStream; + + if (this.debugLogger != null && this.debugLogger.isDebugEnabled()) { + PrintWriter debugWriter = new PrintWriter(new CommonsLogWriter(this.debugLogger)); + isToUse = new HessianDebugInputStream(inputStream, debugWriter); + if (debugOutputStreamAvailable) { + osToUse = DebugStreamFactory.createDebugOutputStream(outputStream, debugWriter); + } + } + + Hessian2Input in = new Hessian2Input(isToUse); + if (this.serializerFactory != null) { + in.setSerializerFactory(this.serializerFactory); + } + + int code = in.read(); + if (code != 'c') { + throw new IOException("expected 'c' in hessian input at " + code); + } + + AbstractHessianOutput out = null; + int major = in.read(); + int minor = in.read(); + if (major >= 2) { + out = new Hessian2Output(osToUse); + } + else { + out = new HessianOutput(osToUse); + } + if (this.serializerFactory != null) { + out.setSerializerFactory(this.serializerFactory); + } + + try { + this.skeleton.invoke(in, out); + } + finally { + try { + in.close(); + isToUse.close(); + } + catch (IOException ex) { + // ignore + } + try { + out.close(); + osToUse.close(); + } + catch (IOException ex) { + // ignore + } + } + } + + + /** + * Inner class to avoid hard dependency on Hessian 3.1.3's HessianDebugOutputStream. + */ + private static class DebugStreamFactory { + + public static OutputStream createDebugOutputStream(OutputStream os, PrintWriter debug) { + return new HessianDebugOutputStream(os, debug); + } + } + } diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianServiceExporter.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianServiceExporter.java index 751fbc9a732..b55c3a03c54 100644 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianServiceExporter.java +++ b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianServiceExporter.java @@ -36,11 +36,7 @@ import org.springframework.web.util.NestedServletException; *

    Hessian is a slim, binary RPC protocol. * For information on Hessian, see the * Hessian website. - * - *

    This exporter will work with both Hessian 2.x and 3.x (respectively - * Resin 2.x and 3.x), autodetecting the corresponding skeleton class. - * As of Spring 2.0, it is also compatible with the new Hessian 2 protocol - * (a.k.a. Hessian 3.0.20+), while remaining compatible with older versions. + * This exporter requires Hessian 3.0.20 or above. * *

    Note: Hessian services exported with this class can be accessed by * any Hessian client, as there isn't any special handling involved. diff --git a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianSkeletonInvoker.java b/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianSkeletonInvoker.java deleted file mode 100644 index 86d9bf98a3e..00000000000 --- a/org.springframework.web/src/main/java/org/springframework/remoting/caucho/HessianSkeletonInvoker.java +++ /dev/null @@ -1,67 +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.remoting.caucho; - -import java.io.InputStream; -import java.io.OutputStream; - -import com.caucho.hessian.server.HessianSkeleton; -import com.caucho.hessian.io.SerializerFactory; - -import org.springframework.util.Assert; - -/** - * Internal invoker strategy for a Hessian skeleton. - * Allows for common handling of Hessian protocol version 1 and 2. - * - * @author Juergen Hoeller - * @since 2.0 - */ -abstract class HessianSkeletonInvoker { - - /** - * Wrapped HessianSkeleton, available to subclasses. - */ - protected final HessianSkeleton skeleton; - - /** - * Hessian SerializerFactory (if any), available to subclasses. - */ - protected final SerializerFactory serializerFactory; - - - /** - * Create a new HessianSkeletonInvoker for the given skeleton. - * @param skeleton the HessianSkeleton to wrap - * @param serializerFactory the Hessian SerializerFactory to use, if any - */ - public HessianSkeletonInvoker(HessianSkeleton skeleton, SerializerFactory serializerFactory) { - Assert.notNull(skeleton, "HessianSkeleton must not be null"); - this.skeleton = skeleton; - this.serializerFactory = serializerFactory; - } - - - /** - * Invoke the given skeleton based on the given input/output streams. - * @param inputStream the stream containing the Hessian input - * @param outputStream the stream to receive the Hessian output - * @throws Throwable if the skeleton invocation failed - */ - public abstract void invoke(InputStream inputStream, OutputStream outputStream) throws Throwable; - -} diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java index 4f0c26f220b..6281d964114 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java @@ -19,7 +19,7 @@ package org.springframework.web.context; import java.io.IOException; import java.util.Map; import java.util.Properties; - +import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; @@ -32,14 +32,13 @@ import org.springframework.beans.factory.access.BeanFactoryReference; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; import org.springframework.context.access.ContextSingletonBeanFactoryLocator; -import org.springframework.core.CollectionFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.util.ClassUtils; /** * Performs the actual initialization work for the root application context. - * Called by {@link ContextLoaderListener} and {@link ContextLoaderServlet}. + * Called by {@link ContextLoaderListener}. * *

    Looks for a {@link #CONTEXT_CLASS_PARAM "contextClass"} parameter * at the web.xml context-param level to specify the context @@ -72,7 +71,6 @@ import org.springframework.util.ClassUtils; * @author Sam Brannen * @since 17.02.2003 * @see ContextLoaderListener - * @see ContextLoaderServlet * @see ConfigurableWebApplicationContext * @see org.springframework.web.context.support.XmlWebApplicationContext */ @@ -150,7 +148,8 @@ public class ContextLoader { * Often just holding one reference - if the ContextLoader class is * deployed in the web app ClassLoader itself! */ - private static final Map currentContextPerThread = CollectionFactory.createConcurrentMapIfPossible(1); + private static final Map currentContextPerThread = + new ConcurrentHashMap(1); /** * The root WebApplicationContext instance that this loader manages. @@ -380,7 +379,7 @@ public class ContextLoader { * @see org.springframework.web.context.support.SpringBeanAutowiringSupport */ public static WebApplicationContext getCurrentWebApplicationContext() { - return (WebApplicationContext) currentContextPerThread.get(Thread.currentThread().getContextClassLoader()); + return currentContextPerThread.get(Thread.currentThread().getContextClassLoader()); } } diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderListener.java b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderListener.java index d754d73ffb0..eea4a68d2f9 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderListener.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderListener.java @@ -29,7 +29,6 @@ import javax.servlet.ServletContextListener; * * @author Juergen Hoeller * @since 17.02.2003 - * @see ContextLoaderServlet * @see org.springframework.web.util.Log4jConfigListener */ public class ContextLoaderListener implements ServletContextListener { diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderServlet.java b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderServlet.java deleted file mode 100644 index e25c55bdfce..00000000000 --- a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoaderServlet.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2002-2007 the original author 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.context; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Bootstrap servlet to start up Spring's root {@link WebApplicationContext}. - * Simply delegates to {@link ContextLoader}. - * - *

    This servlet should have a lower load-on-startup value - * in web.xml than any servlets that access the root web - * application context. - * - *

    Note that this class has been deprecated for containers implementing - * Servlet API 2.4 or higher, in favor of {@link ContextLoaderListener}.
    - * According to Servlet 2.4, listeners must be initialized before load-on-startup - * servlets. Many Servlet 2.3 containers already enforce this behavior. If you - * use such a container, this servlet can be replaced with ContextLoaderListener. - * - *

    Servlet 2.3 containers known to work with bootstrap listeners are: - *

      - *
    • Apache Tomcat 4.x+ - *
    • Jetty 4.x+ - *
    • Resin 2.1.8+ - *
    • Orion 2.0.2+ - *
    • BEA WebLogic 8.1 SP3 - *
    - * For working with any of them, ContextLoaderListener is recommended. - * - *

    Servlet 2.3 containers known not to work with bootstrap listeners are: - *

      - *
    • BEA WebLogic up to 8.1 SP2 - *
    • IBM WebSphere 5.x - *
    • Oracle OC4J 9.0.3 - *
    - * If you happen to work with such a server, this servlet has to be used. - * - *

    So unfortunately, the only context initialization option that is compatible - * with all Servlet 2.3 containers is this servlet. - * - *

    Note that a startup failure of this servlet will not stop the rest of the - * web application from starting, in contrast to a listener failure. This can - * lead to peculiar side effects if other servlets get started that depend on - * initialization of the root web application context. - * - * @author Juergen Hoeller - * @author Darren Davison - * @see ContextLoaderListener - * @see org.springframework.web.util.Log4jConfigServlet - */ -public class ContextLoaderServlet extends HttpServlet { - - private ContextLoader contextLoader; - - - /** - * Initialize the root web application context. - */ - @Override - public void init() throws ServletException { - this.contextLoader = createContextLoader(); - this.contextLoader.initWebApplicationContext(getServletContext()); - } - - /** - * Create the ContextLoader to use. Can be overridden in subclasses. - * @return the new ContextLoader - */ - protected ContextLoader createContextLoader() { - return new ContextLoader(); - } - - /** - * Return the ContextLoader used by this servlet. - * @return the current ContextLoader - */ - public ContextLoader getContextLoader() { - return this.contextLoader; - } - - - /** - * Close the root web application context. - */ - @Override - public void destroy() { - if (this.contextLoader != null) { - this.contextLoader.closeWebApplicationContext(getServletContext()); - } - } - - - /** - * This should never even be called since no mapping to this servlet should - * ever be created in web.xml. That's why a correctly invoked Servlet 2.3 - * listener is much more appropriate for initialization work ;-) - */ - @Override - public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { - getServletContext().log( - "Attempt to call service method on ContextLoaderServlet as [" + - request.getRequestURI() + "] was ignored"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - } - - - @Override - public String getServletInfo() { - return "ContextLoaderServlet for Servlet API 2.3 " + - "(deprecated in favor of ContextLoaderListener for Servlet API 2.4)"; - } - -} diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/WebApplicationContext.java b/org.springframework.web/src/main/java/org/springframework/web/context/WebApplicationContext.java index 1a6bd9f6fe2..d5ede5d6a8e 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/WebApplicationContext.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/WebApplicationContext.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. @@ -24,17 +24,17 @@ import org.springframework.context.ApplicationContext; * Interface to provide configuration for a web application. This is read-only while * the application is running, but may be reloaded if the implementation supports this. * - *

    This interface adds a getServletContext method to the generic ApplicationContext - * interface, and defines a well-known application attribute name that the root - * context must be bound to in the bootstrap process. + *

    This interface adds a getServletContext() method to the generic + * ApplicationContext interface, and defines a well-known application attribute name + * that the root context must be bound to in the bootstrap process. * *

    Like generic application contexts, web application contexts are hierarchical. * There is a single root context per application, while each servlet in the application * (including a dispatcher servlet in the MVC framework) has its own child context. * *

    In addition to standard application context lifecycle capabilities, - * WebApplicationContext implementations need to detect ServletContextAware - * beans and invoke the setServletContext method accordingly. + * WebApplicationContext implementations need to detect {@link ServletContextAware} + * beans and invoke the setServletContext method accordingly. * * @author Rod Johnson * @author Juergen Hoeller @@ -53,7 +53,6 @@ public interface WebApplicationContext extends ApplicationContext { */ String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT"; - /** * Scope identifier for request scope: "request". * Supported in addition to the standard scopes "singleton" and "prototype". @@ -72,6 +71,20 @@ public interface WebApplicationContext extends ApplicationContext { */ String SCOPE_GLOBAL_SESSION = "globalSession"; + /** + * Name of the ServletContext init-params environment bean in the factory. + * @see javax.servlet.ServletContext#getInitParameterNames() + * @see javax.servlet.ServletContext#getInitParameter(String) + */ + String CONTEXT_PROPERTIES_BEAN_NAME = "contextProperties"; + + /** + * Name of the ServletContext attributes environment bean in the factory. + * @see javax.servlet.ServletContext#getAttributeNames() + * @see javax.servlet.ServletContext#getAttribute(String) + */ + String CONTEXT_ATTRIBUTES_BEAN_NAME = "contextAttributes"; + /** * Return the standard Servlet API ServletContext for this application. diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributes.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributes.java index 31b407ed0f6..164c5c6314b 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributes.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributes.java @@ -16,7 +16,6 @@ package org.springframework.web.context.request; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; @@ -34,7 +33,7 @@ import org.springframework.util.Assert; public abstract class AbstractRequestAttributes implements RequestAttributes { /** Map from attribute name String to destruction callback Runnable */ - protected final Map requestDestructionCallbacks = new LinkedHashMap(8); + protected final Map requestDestructionCallbacks = new LinkedHashMap(8); private volatile boolean requestActive = true; @@ -88,8 +87,8 @@ public abstract class AbstractRequestAttributes implements RequestAttributes { */ private void executeRequestDestructionCallbacks() { synchronized (this.requestDestructionCallbacks) { - for (Iterator it = this.requestDestructionCallbacks.values().iterator(); it.hasNext();) { - ((Runnable) it.next()).run(); + for (Runnable runnable : this.requestDestructionCallbacks.values()) { + runnable.run(); } this.requestDestructionCallbacks.clear(); } diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributesScope.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributesScope.java index 1b81a41f0a2..1d1105103e6 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributesScope.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/AbstractRequestAttributesScope.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. @@ -63,6 +63,10 @@ public abstract class AbstractRequestAttributesScope implements Scope { attributes.registerDestructionCallback(name, callback, getScope()); } + public Object resolveContextualObject(String key) { + return null; + } + /** * Template method that determines the actual target scope. diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/DestructionCallbackBindingListener.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/DestructionCallbackBindingListener.java new file mode 100644 index 00000000000..2290d8fc174 --- /dev/null +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/DestructionCallbackBindingListener.java @@ -0,0 +1,44 @@ +/* + * 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.context.request; + +import java.io.Serializable; +import javax.servlet.http.HttpSessionBindingEvent; +import javax.servlet.http.HttpSessionBindingListener; + +/** + * Adapter that implements the Servlet 2.3 HttpSessionBindingListener + * interface, wrapping a session destruction callback. + */ +public class DestructionCallbackBindingListener implements HttpSessionBindingListener, Serializable { + + private final Runnable destructionCallback; + + + public DestructionCallbackBindingListener(Runnable destructionCallback) { + this.destructionCallback = destructionCallback; + } + + + public void valueBound(HttpSessionBindingEvent event) { + } + + public void valueUnbound(HttpSessionBindingEvent event) { + this.destructionCallback.run(); + } + +} diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java index 6db824c88a5..1cf58cfa0e5 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java @@ -18,7 +18,6 @@ package org.springframework.web.context.request; import java.lang.reflect.Method; import java.util.Map; - import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; @@ -71,7 +70,7 @@ public class FacesRequestAttributes implements RequestAttributes { /** * Return the JSF FacesContext that this adapter operates on. */ - protected FacesContext getFacesContext() { + protected final FacesContext getFacesContext() { return this.facesContext; } @@ -79,7 +78,7 @@ public class FacesRequestAttributes implements RequestAttributes { * Return the JSF ExternalContext that this adapter operates on. * @see javax.faces.context.FacesContext#getExternalContext() */ - protected ExternalContext getExternalContext() { + protected final ExternalContext getExternalContext() { return getFacesContext().getExternalContext(); } @@ -90,7 +89,7 @@ public class FacesRequestAttributes implements RequestAttributes { * @see #SCOPE_REQUEST * @see #SCOPE_SESSION */ - protected Map getAttributeMap(int scope) { + protected Map getAttributeMap(int scope) { if (scope == SCOPE_REQUEST) { return getExternalContext().getRequestMap(); } @@ -113,7 +112,7 @@ public class FacesRequestAttributes implements RequestAttributes { } public String[] getAttributeNames(int scope) { - return StringUtils.toStringArray(getAttributeMap(scope).entrySet()); + return StringUtils.toStringArray(getAttributeMap(scope).keySet()); } public void registerDestructionCallback(String name, Runnable callback, int scope) { @@ -123,6 +122,54 @@ public class FacesRequestAttributes implements RequestAttributes { } } + public Object resolveReference(String key) { + if (REFERENCE_REQUEST.equals(key)) { + return getExternalContext().getRequest(); + } + else if (REFERENCE_SESSION.equals(key)) { + return getExternalContext().getSession(true); + } + else if ("application".equals(key)) { + return getExternalContext().getContext(); + } + else if ("requestScope".equals(key)) { + return getExternalContext().getRequestMap(); + } + else if ("sessionScope".equals(key)) { + return getExternalContext().getSessionMap(); + } + else if ("applicationScope".equals(key)) { + return getExternalContext().getApplicationMap(); + } + else if ("cookie".equals(key)) { + return getExternalContext().getRequestCookieMap(); + } + else if ("header".equals(key)) { + return getExternalContext().getRequestHeaderMap(); + } + else if ("headerValues".equals(key)) { + return getExternalContext().getRequestHeaderValuesMap(); + } + else if ("param".equals(key)) { + return getExternalContext().getRequestParameterMap(); + } + else if ("paramValues".equals(key)) { + return getExternalContext().getRequestParameterValuesMap(); + } + else if ("initParam".equals(key)) { + return getExternalContext().getInitParameterMap(); + } + else if ("view".equals(key)) { + return getFacesContext().getViewRoot(); + } + else if ("facesContext".equals(key)) { + return getFacesContext(); + } + else { + return null; + } + } + public String getSessionId() { Object session = getExternalContext().getSession(true); try { diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java index a83defa82fa..a567d447eeb 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java @@ -19,7 +19,6 @@ package org.springframework.web.context.request; import java.security.Principal; import java.util.Locale; import java.util.Map; - import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; @@ -53,15 +52,15 @@ public class FacesWebRequest extends FacesRequestAttributes implements NativeWeb public String getParameter(String paramName) { - return (String) getExternalContext().getRequestParameterMap().get(paramName); + return getExternalContext().getRequestParameterMap().get(paramName); } public String[] getParameterValues(String paramName) { - return (String[]) getExternalContext().getRequestParameterValuesMap().get(paramName); + return getExternalContext().getRequestParameterValuesMap().get(paramName); } - public Map getParameterMap() { - return getExternalContext().getRequestParameterMap(); + public Map getParameterMap() { + return getExternalContext().getRequestParameterValuesMap(); } public Locale getLocale() { @@ -95,19 +94,19 @@ public class FacesWebRequest extends FacesRequestAttributes implements NativeWeb public String getDescription(boolean includeClientInfo) { ExternalContext externalContext = getExternalContext(); - StringBuffer buffer = new StringBuffer(); - buffer.append("context=").append(externalContext.getRequestContextPath()); + StringBuilder sb = new StringBuilder(); + sb.append("context=").append(externalContext.getRequestContextPath()); if (includeClientInfo) { Object session = externalContext.getSession(false); if (session != null) { - buffer.append(";session=").append(getSessionId()); + sb.append(";session=").append(getSessionId()); } String user = externalContext.getRemoteUser(); if (StringUtils.hasLength(user)) { - buffer.append(";user=").append(user); + sb.append(";user=").append(user); } } - return buffer.toString(); + return sb.toString(); } @Override diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/RequestAttributes.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/RequestAttributes.java index 26211179704..ea7666b6426 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/RequestAttributes.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/RequestAttributes.java @@ -53,6 +53,12 @@ public interface RequestAttributes { int SCOPE_GLOBAL_SESSION = 2; + String REFERENCE_REQUEST = "request"; + + String REFERENCE_SESSION = "session"; + + + /** * Return the value for the scoped attribute of the given name, if any. * @param name the name of the attribute @@ -108,6 +114,15 @@ public interface RequestAttributes { */ void registerDestructionCallback(String name, Runnable callback, int scope); + /** + * Resolve the contextual reference for the given key, if any. + *

    At a minimum: the HttpServletRequest/PortletRequest reference for key + * "request", and the HttpSession/PortletSession reference for key "session". + * @param key the contextual key + * @return the corresponding object, or null if none found + */ + Object resolveReference(String key); + /** * Return an id for the current underlying session. * @return the session id as String (never null diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java index 874483339d4..1cd6c2c28d9 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java @@ -16,15 +16,10 @@ package org.springframework.web.context.request; -import java.io.Serializable; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -55,7 +50,7 @@ public class ServletRequestAttributes extends AbstractRequestAttributes { private volatile HttpSession session; - private final Map sessionAttributesToUpdate = new HashMap(); + private final Map sessionAttributesToUpdate = new HashMap(); /** @@ -164,6 +159,7 @@ public class ServletRequestAttributes extends AbstractRequestAttributes { } } + @SuppressWarnings("unchecked") public String[] getAttributeNames(int scope) { if (scope == SCOPE_REQUEST) { if (!isRequestActive()) { @@ -195,6 +191,18 @@ public class ServletRequestAttributes extends AbstractRequestAttributes { } } + public Object resolveReference(String key) { + if (REFERENCE_REQUEST.equals(key)) { + return this.request; + } + else if (REFERENCE_SESSION.equals(key)) { + return getSession(true); + } + else { + return null; + } + } + public String getSessionId() { return getSession(true).getId(); } @@ -216,9 +224,8 @@ public class ServletRequestAttributes extends AbstractRequestAttributes { synchronized (this.sessionAttributesToUpdate) { if (this.session != null) { try { - for (Iterator it = this.sessionAttributesToUpdate.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - String name = (String) entry.getKey(); + for (Map.Entry entry : this.sessionAttributesToUpdate.entrySet()) { + String name = entry.getKey(); Object newValue = entry.getValue(); Object oldValue = this.session.getAttribute(name); if (oldValue == newValue) { @@ -251,25 +258,4 @@ public class ServletRequestAttributes extends AbstractRequestAttributes { return this.request.toString(); } - - /** - * Adapter that implements the Servlet 2.3 HttpSessionBindingListener - * interface, wrapping a session destruction callback. - */ - private static class DestructionCallbackBindingListener implements HttpSessionBindingListener, Serializable { - - private final Runnable destructionCallback; - - public DestructionCallbackBindingListener(Runnable destructionCallback) { - this.destructionCallback = destructionCallback; - } - - public void valueBound(HttpSessionBindingEvent event) { - } - - public void valueUnbound(HttpSessionBindingEvent event) { - this.destructionCallback.run(); - } - } - } diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java index 554f75a41e2..d04d1b396bd 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java @@ -19,7 +19,6 @@ package org.springframework.web.context.request; import java.security.Principal; import java.util.Locale; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -87,7 +86,8 @@ public class ServletWebRequest extends ServletRequestAttributes implements Nativ return getRequest().getParameterValues(paramName); } - public Map getParameterMap() { + @SuppressWarnings("unchecked") + public Map getParameterMap() { return getRequest().getParameterMap(); } @@ -140,23 +140,23 @@ public class ServletWebRequest extends ServletRequestAttributes implements Nativ public String getDescription(boolean includeClientInfo) { HttpServletRequest request = getRequest(); - StringBuffer buffer = new StringBuffer(); - buffer.append("uri=").append(request.getRequestURI()); + StringBuilder sb = new StringBuilder(); + sb.append("uri=").append(request.getRequestURI()); if (includeClientInfo) { String client = request.getRemoteAddr(); if (StringUtils.hasLength(client)) { - buffer.append(";client=").append(client); + sb.append(";client=").append(client); } HttpSession session = request.getSession(false); if (session != null) { - buffer.append(";session=").append(session.getId()); + sb.append(";session=").append(session.getId()); } String user = request.getRemoteUser(); if (StringUtils.hasLength(user)) { - buffer.append(";user=").append(user); + sb.append(";user=").append(user); } } - return buffer.toString(); + return sb.toString(); } @Override diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/WebRequest.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/WebRequest.java index a2529bccad8..670be89b8d8 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/WebRequest.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/WebRequest.java @@ -52,7 +52,7 @@ public interface WebRequest extends RequestAttributes { *

    A single-value parameter will be exposed as an array with a single element. * @see javax.servlet.http.HttpServletRequest#getParameterMap() */ - Map getParameterMap(); + Map getParameterMap(); /** * Return the primary Locale for this request. diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java b/org.springframework.web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java index 0561b4139ff..70fa076c5d2 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java @@ -143,6 +143,7 @@ public abstract class AbstractRefreshableWebApplicationContext extends AbstractR beanFactory.registerResolvableDependency(ServletConfig.class, this.servletConfig); WebApplicationContextUtils.registerWebApplicationScopes(beanFactory); + WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); } /** diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java b/org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java index 25bc3ca2c10..e59b406f48b 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.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. @@ -106,6 +106,7 @@ public class GenericWebApplicationContext extends GenericApplicationContext beanFactory.registerResolvableDependency(ServletContext.class, this.servletContext); WebApplicationContextUtils.registerWebApplicationScopes(beanFactory); + WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); } /** diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java b/org.springframework.web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java index a999434e018..ebb3e138512 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/support/RequestHandledEvent.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. @@ -124,7 +124,7 @@ public class RequestHandledEvent extends ApplicationEvent { * the most important context data. */ public String getShortDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("session=[").append(this.sessionId).append("]; "); sb.append("user=[").append(this.userName).append("]; "); return sb.toString(); @@ -135,7 +135,7 @@ public class RequestHandledEvent extends ApplicationEvent { * all available context data. */ public String getDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("session=[").append(this.sessionId).append("]; "); sb.append("user=[").append(this.userName).append("]; "); sb.append("time=[").append(this.processingTimeMillis).append("ms]; "); diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/support/ServletRequestHandledEvent.java b/org.springframework.web/src/main/java/org/springframework/web/context/support/ServletRequestHandledEvent.java index d06dc082736..8e6e21747bf 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/support/ServletRequestHandledEvent.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/support/ServletRequestHandledEvent.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. @@ -119,7 +119,7 @@ public class ServletRequestHandledEvent extends RequestHandledEvent { @Override public String getShortDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("url=[").append(getRequestUrl()).append("]; "); sb.append("client=[").append(getClientAddress()).append("]; "); sb.append(super.getShortDescription()); @@ -128,7 +128,7 @@ public class ServletRequestHandledEvent extends RequestHandledEvent { @Override public String getDescription() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("url=[").append(getRequestUrl()).append("]; "); sb.append("client=[").append(getClientAddress()).append("]; "); sb.append("method=[").append(getMethod()).append("]; "); diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java b/org.springframework.web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java index a8dd09dc490..7a638e08e66 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java @@ -134,13 +134,14 @@ public class StaticWebApplicationContext extends StaticApplicationContext */ @Override protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - beanFactory.registerScope(SCOPE_REQUEST, new RequestScope()); - beanFactory.registerScope(SCOPE_SESSION, new SessionScope(false)); - beanFactory.registerScope(SCOPE_GLOBAL_SESSION, new SessionScope(true)); - beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); beanFactory.ignoreDependencyInterface(ServletConfigAware.class); + beanFactory.registerResolvableDependency(ServletContext.class, this.servletContext); + beanFactory.registerResolvableDependency(ServletConfig.class, this.servletConfig); + + WebApplicationContextUtils.registerWebApplicationScopes(beanFactory); + WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); } /** diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java b/org.springframework.web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java index 48f1d136af2..913a5d16c3b 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java @@ -16,6 +16,10 @@ package org.springframework.web.context.support; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpSession; @@ -53,8 +57,7 @@ public abstract class WebApplicationContextUtils { /** * Find the root WebApplicationContext for this web application, which is - * typically loaded via {@link org.springframework.web.context.ContextLoaderListener} or - * {@link org.springframework.web.context.ContextLoaderServlet}. + * typically loaded via {@link org.springframework.web.context.ContextLoaderListener}. *

    Will rethrow an exception that happened on root context startup, * to differentiate between a failed context startup and no context at all. * @param sc ServletContext to find the web application context for @@ -74,8 +77,7 @@ public abstract class WebApplicationContextUtils { /** * Find the root WebApplicationContext for this web application, which is - * typically loaded via {@link org.springframework.web.context.ContextLoaderListener} or - * {@link org.springframework.web.context.ContextLoaderServlet}. + * typically loaded via {@link org.springframework.web.context.ContextLoaderListener}. *

    Will rethrow an exception that happened on root context startup, * to differentiate between a failed context startup and no context at all. * @param sc ServletContext to find the web application context for @@ -105,9 +107,7 @@ public abstract class WebApplicationContextUtils { throw (Error) attr; } if (attr instanceof Exception) { - IllegalStateException ex = new IllegalStateException(); - ex.initCause((Exception) attr); - throw ex; + throw new IllegalStateException((Exception) attr); } if (!(attr instanceof WebApplicationContext)) { throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr); @@ -121,7 +121,7 @@ public abstract class WebApplicationContextUtils { * as used by the WebApplicationContext. * @param beanFactory the BeanFactory to configure */ - public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) { + static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) { beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false)); beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true)); @@ -146,4 +146,38 @@ public abstract class WebApplicationContextUtils { }); } + /** + * Register web-specific environment beans with the given BeanFactory, + * as used by the WebApplicationContext. + * @param bf the BeanFactory to configure + * @param sc the ServletContext that we're running within + */ + static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf, ServletContext sc) { + if (!bf.containsBean(WebApplicationContext.CONTEXT_PROPERTIES_BEAN_NAME)) { + Map parameterMap = new HashMap(); + if (sc != null) { + Enumeration paramNameEnum = sc.getInitParameterNames(); + while (paramNameEnum.hasMoreElements()) { + String paramName = (String) paramNameEnum.nextElement(); + parameterMap.put(paramName, sc.getInitParameter(paramName)); + } + } + bf.registerSingleton(WebApplicationContext.CONTEXT_PROPERTIES_BEAN_NAME, + Collections.unmodifiableMap(parameterMap)); + } + + if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) { + Map attributeMap = new HashMap(); + if (sc != null) { + Enumeration attrNameEnum = sc.getAttributeNames(); + while (attrNameEnum.hasMoreElements()) { + String attrName = (String) attrNameEnum.nextElement(); + attributeMap.put(attrName, sc.getAttribute(attrName)); + } + } + bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME, + Collections.unmodifiableMap(attributeMap)); + } + } + } diff --git a/org.springframework.web/src/main/java/org/springframework/web/filter/AbstractRequestLoggingFilter.java b/org.springframework.web/src/main/java/org/springframework/web/filter/AbstractRequestLoggingFilter.java index be0693a5b30..b294e7cd22d 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/filter/AbstractRequestLoggingFilter.java +++ b/org.springframework.web/src/main/java/org/springframework/web/filter/AbstractRequestLoggingFilter.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. @@ -188,28 +188,28 @@ public abstract class AbstractRequestLoggingFilter extends OncePerRequestFilter * and the supplied prefix and suffix. */ protected String createMessage(HttpServletRequest request, String prefix, String suffix) { - StringBuffer buffer = new StringBuffer(); - buffer.append(prefix); - buffer.append("uri=").append(request.getRequestURI()); + StringBuilder msg = new StringBuilder(); + msg.append(prefix); + msg.append("uri=").append(request.getRequestURI()); if (isIncludeQueryString()) { - buffer.append('?').append(request.getQueryString()); + msg.append('?').append(request.getQueryString()); } if (isIncludeClientInfo()) { String client = request.getRemoteAddr(); if (StringUtils.hasLength(client)) { - buffer.append(";client=").append(client); + msg.append(";client=").append(client); } HttpSession session = request.getSession(false); if (session != null) { - buffer.append(";session=").append(session.getId()); + msg.append(";session=").append(session.getId()); } String user = request.getRemoteUser(); if (user != null) { - buffer.append(";user=").append(user); + msg.append(";user=").append(user); } } - buffer.append(suffix); - return buffer.toString(); + msg.append(suffix); + return msg.toString(); } diff --git a/org.springframework.web/src/main/java/org/springframework/web/filter/CharacterEncodingFilter.java b/org.springframework.web/src/main/java/org/springframework/web/filter/CharacterEncodingFilter.java index 277170f12b0..c1ccfdd278d 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/filter/CharacterEncodingFilter.java +++ b/org.springframework.web/src/main/java/org/springframework/web/filter/CharacterEncodingFilter.java @@ -17,14 +17,11 @@ package org.springframework.web.filter; import java.io.IOException; - import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.util.ClassUtils; - /** * Servlet 2.3/2.4 Filter that allows one to specify a character encoding for * requests. This is useful because current browsers typically do not set a @@ -45,12 +42,6 @@ import org.springframework.util.ClassUtils; */ public class CharacterEncodingFilter extends OncePerRequestFilter { - // Determine whether the Servlet 2.4 HttpServletResponse.setCharacterEncoding(String) - // method is available, for use in the "doFilterInternal" implementation. - private final static boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod( - HttpServletResponse.class, "setCharacterEncoding", new Class[] {String.class}); - - private String encoding; private boolean forceEncoding = false; @@ -90,7 +81,7 @@ public class CharacterEncodingFilter extends OncePerRequestFilter { if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) { request.setCharacterEncoding(this.encoding); - if (this.forceEncoding && responseSetCharacterEncodingAvailable) { + if (this.forceEncoding) { response.setCharacterEncoding(this.encoding); } } diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/ExpressionEvaluationUtils.java b/org.springframework.web/src/main/java/org/springframework/web/util/ExpressionEvaluationUtils.java index 1763bd6a88c..e03d72a060e 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/ExpressionEvaluationUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/ExpressionEvaluationUtils.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,53 +19,33 @@ package org.springframework.web.util; import java.util.Collections; import java.util.HashMap; import java.util.Map; - import javax.servlet.ServletContext; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.el.ELException; import javax.servlet.jsp.el.Expression; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager; - import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; /** - * Convenience methods for transparent access to JSP 2.0's built-in - * {@link javax.servlet.jsp.el.ExpressionEvaluator} or the standalone - * {@link org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager} - * of Jakarta's JSTL implementation. + * Convenience methods for accessing JSP 2.0's + * {@link javax.servlet.jsp.el.ExpressionEvaluator}. * - *

    Automatically detects JSP 2.0 or Jakarta JSTL, preferring the JSP 2.0 - * mechanism if available. Also detects the JSP 2.0 API being present but - * the runtime JSP engine not actually supporting JSP 2.0, falling back to - * the Jakarta JSTL in this case. Throws an exception when encountering actual - * EL expressions if neither JSP 2.0 nor the Jakarta JSTL is available. - * - *

    In the case of JSP 2.0, this class will by default use standard - * evaluate calls. If your application server happens to be - * inefficient in that respect, consider setting Spring's "cacheJspExpressions" - * context-param in web.xml to "true", which will use - * parseExpression calls with cached Expression objects instead. + *

    This class will by default use standard evaluate calls. + * If your application server happens to be inefficient in that respect, + * consider setting Spring's "cacheJspExpressions" context-param in + * web.xml to "true", which will use parseExpression + * calls with cached Expression objects instead. * *

    The evaluation methods check if the value contains "${" before * invoking the EL evaluator, treating the value as "normal" expression * (i.e. a literal String value) else. * - *

    Note: The evaluation methods do not have a runtime dependency on - * JSP 2.0 or on Jakarta's JSTL implementation, as long as they are not - * asked to process actual EL expressions. This allows for using EL-aware - * tags with Java-based JSP expressions instead, for example. - * * @author Juergen Hoeller * @author Alef Arendsen * @since 11.07.2003 * @see javax.servlet.jsp.el.ExpressionEvaluator#evaluate * @see javax.servlet.jsp.el.ExpressionEvaluator#parseExpression - * @see org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager */ public abstract class ExpressionEvaluationUtils { @@ -86,40 +66,6 @@ public abstract class ExpressionEvaluationUtils { private static final String EXPRESSION_CACHE_MAP_CONTEXT_ATTR = ExpressionEvaluationUtils.class.getName() + ".JSP_EXPRESSION_CACHE"; - private static final String JSP_20_CLASS_NAME = - "javax.servlet.jsp.el.ExpressionEvaluator"; - - private static final String JAKARTA_JSTL_CLASS_NAME = - "org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager"; - - - private static final Log logger = LogFactory.getLog(ExpressionEvaluationUtils.class); - - private static ExpressionEvaluationHelper helper; - - - static { - ClassLoader cl = ExpressionEvaluationUtils.class.getClassLoader(); - if (ClassUtils.isPresent(JSP_20_CLASS_NAME, cl)) { - logger.debug("Found JSP 2.0 ExpressionEvaluator"); - if (ClassUtils.isPresent(JAKARTA_JSTL_CLASS_NAME, cl)) { - logger.debug("Found Jakarta JSTL ExpressionEvaluatorManager"); - helper = new Jsp20ExpressionEvaluationHelper(new JakartaExpressionEvaluationHelper()); - } - else { - helper = new Jsp20ExpressionEvaluationHelper(new NoExpressionEvaluationHelper()); - } - } - else if (ClassUtils.isPresent(JAKARTA_JSTL_CLASS_NAME, cl)) { - logger.debug("Found Jakarta JSTL ExpressionEvaluatorManager"); - helper = new JakartaExpressionEvaluationHelper(); - } - else { - logger.debug("JSP expression evaluation not available"); - helper = new NoExpressionEvaluationHelper(); - } - } - /** * Check if the given expression value is an EL expression. @@ -128,7 +74,7 @@ public abstract class ExpressionEvaluationUtils { * false otherwise */ public static boolean isExpressionLanguage(String value) { - return (value != null && value.indexOf(EXPRESSION_PREFIX) != -1); + return (value != null && value.contains(EXPRESSION_PREFIX)); } /** @@ -208,7 +154,7 @@ public abstract class ExpressionEvaluationUtils { throws JspException { if (isExpressionLanguage(attrValue)) { - return ((Integer) doEvaluate(attrName, attrValue, Integer.class, pageContext)).intValue(); + return (Integer) doEvaluate(attrName, attrValue, Integer.class, pageContext); } else { return Integer.parseInt(attrValue); @@ -227,10 +173,10 @@ public abstract class ExpressionEvaluationUtils { throws JspException { if (isExpressionLanguage(attrValue)) { - return ((Boolean) doEvaluate(attrName, attrValue, Boolean.class, pageContext)).booleanValue(); + return (Boolean) doEvaluate(attrName, attrValue, Boolean.class, pageContext); } else { - return Boolean.valueOf(attrValue).booleanValue(); + return Boolean.valueOf(attrValue); } } @@ -247,56 +193,81 @@ public abstract class ExpressionEvaluationUtils { * @throws JspException in case of parsing errors */ private static Object doEvaluate(String attrName, String attrValue, Class resultClass, PageContext pageContext) - throws JspException { + throws JspException { Assert.notNull(attrValue, "Attribute value must not be null"); Assert.notNull(resultClass, "Result class must not be null"); Assert.notNull(pageContext, "PageContext must not be null"); - if (resultClass.isAssignableFrom(String.class)) { - StringBuffer resultValue = null; - int exprPrefixIndex = -1; - int exprSuffixIndex = 0; - do { - exprPrefixIndex = attrValue.indexOf(EXPRESSION_PREFIX, exprSuffixIndex); - if (exprPrefixIndex != -1) { - int prevExprSuffixIndex = exprSuffixIndex; - exprSuffixIndex = attrValue.indexOf(EXPRESSION_SUFFIX, exprPrefixIndex + EXPRESSION_PREFIX.length()); - String expr = null; - if (exprSuffixIndex != -1) { - exprSuffixIndex += EXPRESSION_SUFFIX.length(); - expr = attrValue.substring(exprPrefixIndex, exprSuffixIndex); - } - else { - expr = attrValue.substring(exprPrefixIndex); - } - if (expr.length() == attrValue.length()) { - // A single expression without static prefix or suffix -> - // parse it with the specified result class rather than String. - return helper.evaluate(attrName, attrValue, resultClass, pageContext); - } - else { - // We actually need to concatenate partial expressions into a String. - if (resultValue == null) { - resultValue = new StringBuffer(); + try { + if (resultClass.isAssignableFrom(String.class)) { + StringBuilder resultValue = null; + int exprPrefixIndex = -1; + int exprSuffixIndex = 0; + do { + exprPrefixIndex = attrValue.indexOf(EXPRESSION_PREFIX, exprSuffixIndex); + if (exprPrefixIndex != -1) { + int prevExprSuffixIndex = exprSuffixIndex; + exprSuffixIndex = attrValue.indexOf(EXPRESSION_SUFFIX, exprPrefixIndex + EXPRESSION_PREFIX.length()); + String expr = null; + if (exprSuffixIndex != -1) { + exprSuffixIndex += EXPRESSION_SUFFIX.length(); + expr = attrValue.substring(exprPrefixIndex, exprSuffixIndex); } - resultValue.append(attrValue.substring(prevExprSuffixIndex, exprPrefixIndex)); - resultValue.append(helper.evaluate(attrName, expr, String.class, pageContext)); + else { + expr = attrValue.substring(exprPrefixIndex); + } + if (expr.length() == attrValue.length()) { + // A single expression without static prefix or suffix -> + // parse it with the specified result class rather than String. + return evaluateExpression(attrValue, resultClass, pageContext); + } + else { + // We actually need to concatenate partial expressions into a String. + if (resultValue == null) { + resultValue = new StringBuilder(); + } + resultValue.append(attrValue.substring(prevExprSuffixIndex, exprPrefixIndex)); + resultValue.append(evaluateExpression(expr, String.class, pageContext)); + } + } + else { + if (resultValue == null) { + resultValue = new StringBuilder(); + } + resultValue.append(attrValue.substring(exprSuffixIndex)); } } - else { - if (resultValue == null) { - resultValue = new StringBuffer(); - } - resultValue.append(attrValue.substring(exprSuffixIndex)); - } + while (exprPrefixIndex != -1 && exprSuffixIndex != -1); + return resultValue.toString(); + } + else { + return evaluateExpression(attrValue, resultClass, pageContext); } - while (exprPrefixIndex != -1 && exprSuffixIndex != -1); - return resultValue.toString(); } + catch (ELException ex) { + throw new JspException("Parsing of JSP EL expression failed for attribute '" + attrName + "'", ex); + } + } + private static Object evaluateExpression(String exprValue, Class resultClass, PageContext pageContext) + throws ELException { + + Map expressionCache = getJspExpressionCache(pageContext); + if (expressionCache != null) { + // We are supposed to explicitly create and cache JSP Expression objects. + ExpressionCacheKey cacheKey = new ExpressionCacheKey(exprValue, resultClass); + Expression expr = expressionCache.get(cacheKey); + if (expr == null) { + expr = pageContext.getExpressionEvaluator().parseExpression(exprValue, resultClass, null); + expressionCache.put(cacheKey, expr); + } + return expr.evaluate(pageContext.getVariableResolver()); + } else { - return helper.evaluate(attrName, attrValue, resultClass, pageContext); + // We're simply calling the JSP 2.0 evaluate method straight away. + return pageContext.getExpressionEvaluator().evaluate( + exprValue, resultClass, pageContext.getVariableResolver(), null); } } @@ -307,17 +278,19 @@ public abstract class ExpressionEvaluationUtils { * @param pageContext current JSP PageContext * @return the cache Map, or null if caching is disabled */ - private static Map getJspExpressionCache(PageContext pageContext) { + @SuppressWarnings("unchecked") + private static Map getJspExpressionCache(PageContext pageContext) { ServletContext servletContext = pageContext.getServletContext(); - Map cacheMap = (Map) servletContext.getAttribute(EXPRESSION_CACHE_MAP_CONTEXT_ATTR); + Map cacheMap = + (Map) servletContext.getAttribute(EXPRESSION_CACHE_MAP_CONTEXT_ATTR); if (cacheMap == null) { Boolean cacheFlag = (Boolean) servletContext.getAttribute(EXPRESSION_CACHE_FLAG_CONTEXT_ATTR); if (cacheFlag == null) { cacheFlag = Boolean.valueOf(servletContext.getInitParameter(EXPRESSION_CACHE_CONTEXT_PARAM)); servletContext.setAttribute(EXPRESSION_CACHE_FLAG_CONTEXT_ATTR, cacheFlag); } - if (cacheFlag.booleanValue()) { - cacheMap = Collections.synchronizedMap(new HashMap()); + if (cacheFlag) { + cacheMap = Collections.synchronizedMap(new HashMap()); servletContext.setAttribute(EXPRESSION_CACHE_MAP_CONTEXT_ATTR, cacheMap); } } @@ -325,106 +298,6 @@ public abstract class ExpressionEvaluationUtils { } - /** - * Internal interface for evaluating a JSP EL expression. - */ - private static interface ExpressionEvaluationHelper { - - public Object evaluate(String attrName, String attrValue, Class resultClass, PageContext pageContext) - throws JspException; - } - - - /** - * Fallback ExpressionEvaluationHelper: - * always throws an exception in case of an actual EL expression. - */ - private static class NoExpressionEvaluationHelper implements ExpressionEvaluationHelper { - - public Object evaluate(String attrName, String attrValue, Class resultClass, PageContext pageContext) - throws JspException { - - throw new JspException( - "Neither JSP 2.0 nor Jakarta JSTL available - cannot parse JSP EL expression \"" + attrValue + "\""); - } - } - - - /** - * Actual invocation of the Jakarta ExpressionEvaluatorManager. - * In separate inner class to avoid runtime dependency on Jakarta's - * JSTL implementation, for evaluation of non-EL expressions. - */ - private static class JakartaExpressionEvaluationHelper implements ExpressionEvaluationHelper { - - public Object evaluate(String attrName, String attrValue, Class resultClass, PageContext pageContext) - throws JspException { - - return ExpressionEvaluatorManager.evaluate(attrName, attrValue, resultClass, pageContext); - } - } - - - /** - * Actual invocation of the JSP 2.0 ExpressionEvaluator. - * In separate inner class to avoid runtime dependency on JSP 2.0, - * for evaluation of non-EL expressions. - */ - private static class Jsp20ExpressionEvaluationHelper implements ExpressionEvaluationHelper { - - private final ExpressionEvaluationHelper fallback; - - private boolean fallbackNecessary = false; - - public Jsp20ExpressionEvaluationHelper(ExpressionEvaluationHelper fallback) { - this.fallback = fallback; - } - - public Object evaluate(String attrName, String attrValue, Class resultClass, PageContext pageContext) - throws JspException { - - if (isFallbackNecessary()) { - return this.fallback.evaluate(attrName, attrValue, resultClass, pageContext); - } - - try { - Map expressionCache = getJspExpressionCache(pageContext); - if (expressionCache != null) { - // We are supposed to explicitly create and cache JSP Expression objects. - ExpressionCacheKey cacheKey = new ExpressionCacheKey(attrValue, resultClass); - Expression expr = (Expression) expressionCache.get(cacheKey); - if (expr == null) { - expr = pageContext.getExpressionEvaluator().parseExpression(attrValue, resultClass, null); - expressionCache.put(cacheKey, expr); - } - return expr.evaluate(pageContext.getVariableResolver()); - } - else { - // We're simply calling the JSP 2.0 evaluate method straight away. - return pageContext.getExpressionEvaluator().evaluate( - attrValue, resultClass, pageContext.getVariableResolver(), null); - } - } - catch (ELException ex) { - throw new JspException("Parsing of JSP EL expression \"" + attrValue + "\" failed", ex); - } - catch (LinkageError err) { - logger.debug("JSP 2.0 ExpressionEvaluator API present but not implemented - using fallback", err); - setFallbackNecessary(); - return this.fallback.evaluate(attrName, attrValue, resultClass, pageContext); - } - } - - private synchronized boolean isFallbackNecessary() { - return this.fallbackNecessary; - } - - private synchronized void setFallbackNecessary() { - this.fallbackNecessary = true; - } - } - - /** * Cache key class for JSP 2.0 Expression objects. */ diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.java b/org.springframework.web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.java index 5f1e4787354..75fac9a1d61 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.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. @@ -33,7 +33,7 @@ class HtmlCharacterEntityDecoder { private final String originalMessage; - private final StringBuffer decodedMessage; + private final StringBuilder decodedMessage; private int currentPosition = 0; @@ -45,7 +45,7 @@ class HtmlCharacterEntityDecoder { public HtmlCharacterEntityDecoder(HtmlCharacterEntityReferences characterEntityReferences, String original) { this.characterEntityReferences = characterEntityReferences; this.originalMessage = original; - this.decodedMessage = new StringBuffer(originalMessage.length()); + this.decodedMessage = new StringBuilder(originalMessage.length()); } public String decode() { diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/HtmlUtils.java b/org.springframework.web/src/main/java/org/springframework/web/util/HtmlUtils.java index 4a79aab9162..e28d503c8eb 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/HtmlUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/HtmlUtils.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,7 +60,7 @@ public abstract class HtmlUtils { if (input == null) { return null; } - StringBuffer escaped = new StringBuffer(input.length() * 2); + StringBuilder escaped = new StringBuilder(input.length() * 2); for (int i = 0; i < input.length(); i++) { char character = input.charAt(i); String reference = characterEntityReferences.convertToReference(character); @@ -90,7 +90,7 @@ public abstract class HtmlUtils { if (input == null) { return null; } - StringBuffer escaped = new StringBuffer(input.length() * 2); + StringBuilder escaped = new StringBuilder(input.length() * 2); for (int i = 0; i < input.length(); i++) { char character = input.charAt(i); if (characterEntityReferences.isMappedToReference(character)) { @@ -121,7 +121,7 @@ public abstract class HtmlUtils { if (input == null) { return null; } - StringBuffer escaped = new StringBuffer(input.length() * 2); + StringBuilder escaped = new StringBuilder(input.length() * 2); for (int i = 0; i < input.length(); i++) { char character = input.charAt(i); if (characterEntityReferences.isMappedToReference(character)) { diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/JavaScriptUtils.java b/org.springframework.web/src/main/java/org/springframework/web/util/JavaScriptUtils.java index 9b82db04056..b28d398687f 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/JavaScriptUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/JavaScriptUtils.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,7 +42,7 @@ public class JavaScriptUtils { return input; } - StringBuffer filtered = new StringBuffer(input.length()); + StringBuilder filtered = new StringBuilder(input.length()); char prevChar = '\u0000'; char c; for (int i = 0; i < input.length(); i++) { diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigListener.java b/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigListener.java index 95e501f89a2..40c50106740 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigListener.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigListener.java @@ -36,9 +36,7 @@ import javax.servlet.ServletContextListener; * @author Juergen Hoeller * @since 13.03.2003 * @see Log4jWebConfigurer - * @see Log4jConfigServlet * @see org.springframework.web.context.ContextLoaderListener - * @see org.springframework.web.context.ContextLoaderServlet * @see WebAppRootListener */ public class Log4jConfigListener implements ServletContextListener { diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigServlet.java b/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigServlet.java deleted file mode 100644 index 8494364b192..00000000000 --- a/org.springframework.web/src/main/java/org/springframework/web/util/Log4jConfigServlet.java +++ /dev/null @@ -1,86 +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.web.util; - -import java.io.IOException; - -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Bootstrap servlet for custom log4j initialization in a web environment. - * Delegates to {@link Log4jWebConfigurer} (see its javadoc for configuration details). - * - * WARNING: Assumes an expanded WAR file, both for loading the configuration - * file and for writing the log files. If you want to keep your WAR unexpanded or - * don't need application-specific log files within the WAR directory, don't use - * log4j setup within the application (thus, don't use Log4jConfigListener or - * Log4jConfigServlet). Instead, use a global, VM-wide log4j setup (for example, - * in JBoss) or JDK 1.4's java.util.logging (which is global too). - * - *

    Note: This servlet should have a lower load-on-startup value - * in web.xml than ContextLoaderServlet, when using custom log4j - * initialization. - * - *

    Note that this class has been deprecated for containers implementing - * Servlet API 2.4 or higher, in favor of {@link Log4jConfigListener}.
    - * According to Servlet 2.4, listeners must be initialized before load-on-startup - * servlets. Many Servlet 2.3 containers already enforce this behavior - * (see ContextLoaderServlet javadocs for details). If you use such a container, - * this servlet can be replaced with Log4jConfigListener. - * - * @author Juergen Hoeller - * @author Darren Davison - * @since 12.08.2003 - * @see Log4jWebConfigurer - * @see Log4jConfigListener - * @see org.springframework.web.context.ContextLoaderServlet - */ -public class Log4jConfigServlet extends HttpServlet { - - @Override - public void init() { - Log4jWebConfigurer.initLogging(getServletContext()); - } - - @Override - public void destroy() { - Log4jWebConfigurer.shutdownLogging(getServletContext()); - } - - - /** - * This should never even be called since no mapping to this servlet should - * ever be created in web.xml. That's why a correctly invoked Servlet 2.3 - * listener is much more appropriate for initialization work ;-) - */ - @Override - public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { - getServletContext().log( - "Attempt to call service method on Log4jConfigServlet as [" + - request.getRequestURI() + "] was ignored"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - } - - @Override - public String getServletInfo() { - return "Log4jConfigServlet for Servlet API 2.3 " + - "(deprecated in favor of Log4jConfigListener for Servlet API 2.4)"; - } - -} diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java b/org.springframework.web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java index ac37e6c0996..31906e970c8 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java @@ -93,7 +93,6 @@ import org.springframework.util.SystemPropertyUtils; * @since 12.08.2003 * @see org.springframework.util.Log4jConfigurer * @see Log4jConfigListener - * @see Log4jConfigServlet */ public abstract class Log4jWebConfigurer { diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/org.springframework.web/src/main/java/org/springframework/web/util/UrlPathHelper.java index 3bd71840154..52a11419bc1 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/UrlPathHelper.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/UrlPathHelper.java @@ -41,28 +41,6 @@ import org.springframework.util.StringUtils; */ public class UrlPathHelper { - /** - * @deprecated as of Spring 2.0, in favor of WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE - * @see org.springframework.web.util.WebUtils#INCLUDE_REQUEST_URI_ATTRIBUTE - */ - @Deprecated - public static final String INCLUDE_URI_REQUEST_ATTRIBUTE = WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE; - - /** - * @deprecated as of Spring 2.0, in favor of WebUtils.INCLUDE_CONTEXT_PATH_ATTRIBUTE - * @see org.springframework.web.util.WebUtils#INCLUDE_CONTEXT_PATH_ATTRIBUTE - */ - @Deprecated - public static final String INCLUDE_CONTEXT_PATH_REQUEST_ATTRIBUTE = WebUtils.INCLUDE_CONTEXT_PATH_ATTRIBUTE; - - /** - * @deprecated as of Spring 2.0, in favor of WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE - * @see org.springframework.web.util.WebUtils#INCLUDE_SERVLET_PATH_ATTRIBUTE - */ - @Deprecated - public static final String INCLUDE_SERVLET_PATH_REQUEST_ATTRIBUTE = WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE; - - private final Log logger = LogFactory.getLog(getClass()); private boolean alwaysUseFullPath = false; diff --git a/org.springframework.web/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java b/org.springframework.web/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java index c08b2ff6599..527f05c150a 100644 --- a/org.springframework.web/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java +++ b/org.springframework.web/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java @@ -106,7 +106,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private String contentType; - private final Map parameters = new LinkedHashMap(16); + private final Map parameters = new LinkedHashMap(16); private String protocol = DEFAULT_PROTOCOL; @@ -348,8 +348,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void setParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); - for (Iterator it = params.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + for (Object key : params.keySet()) { Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); @@ -360,8 +359,9 @@ public class MockHttpServletRequest implements HttpServletRequest { this.setParameter((String) key, (String[]) value); } else { - throw new IllegalArgumentException("Parameter map value must be single value " + - " or array of type [" + String.class.getName() + "]"); + throw new IllegalArgumentException( + "Parameter map value must be single value " + " or array of type [" + String.class.getName() + + "]"); } } } @@ -382,7 +382,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void addParameter(String name, String[] values) { Assert.notNull(name, "Parameter name must not be null"); - 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); @@ -401,8 +401,7 @@ public class MockHttpServletRequest implements HttpServletRequest { */ public void addParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); - for (Iterator it = params.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + for (Object key : params.keySet()) { Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); @@ -436,7 +435,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public String getParameter(String name) { Assert.notNull(name, "Parameter name must not be null"); - String[] arr = (String[]) this.parameters.get(name); + String[] arr = this.parameters.get(name); return (arr != null && arr.length > 0 ? arr[0] : null); } @@ -446,7 +445,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public String[] getParameterValues(String name) { Assert.notNull(name, "Parameter name must not be null"); - return (String[]) this.parameters.get(name); + return this.parameters.get(name); } public Map getParameterMap() { @@ -750,14 +749,6 @@ public class MockHttpServletRequest implements HttpServletRequest { return this.remoteUser; } - /** - * @deprecated in favor of addUserRole - * @see #addUserRole - */ - public void addRole(String role) { - addUserRole(role); - } - public void addUserRole(String role) { this.userRoles.add(role); } @@ -855,4 +846,4 @@ public class MockHttpServletRequest implements HttpServletRequest { return isRequestedSessionIdFromURL(); } -} \ No newline at end of file +} diff --git a/org.springframework.web/template.mf b/org.springframework.web/template.mf index b721cead376..ab7cd3cea48 100644 --- a/org.springframework.web/template.mf +++ b/org.springframework.web/template.mf @@ -19,7 +19,6 @@ Import-Template: org.apache.commons.httpclient.*;version="[3.1.0, 4.0.0)";resolution:=optional, org.apache.commons.logging.*;version="[1.1.1, 2.0.0)", org.apache.log4j.*;version="[1.2.15, 2.0.0)";resolution:=optional, - org.apache.taglibs.*;version="[1.1.2, 2.0.0)";resolution:=optional, org.springframework.aop.*;version="[3.0.0, 3.0.1)", org.springframework.beans.*;version="[3.0.0, 3.0.1)", org.springframework.context.*;version="[3.0.0, 3.0.1)", diff --git a/org.springframework.web/web.iml b/org.springframework.web/web.iml index 97db3eae7ff..d84e29124c2 100644 --- a/org.springframework.web/web.iml +++ b/org.springframework.web/web.iml @@ -1,177 +1,177 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-framework.ipr b/spring-framework.ipr index 91dc65e5e5e..ed58c0d9744 100644 --- a/spring-framework.ipr +++ b/spring-framework.ipr @@ -1,731 +1,731 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +