Java 5 code style

This commit is contained in:
Juergen Hoeller 2008-11-25 01:29:54 +00:00
parent 1f9e63af49
commit 29657105da
71 changed files with 726 additions and 877 deletions

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,6 @@
package org.springframework.aop.aspectj; package org.springframework.aop.aspectj;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.springframework.aop.Advisor; import org.springframework.aop.Advisor;
@ -40,12 +39,11 @@ public abstract class AspectJProxyUtils {
* @param advisors Advisors available * @param advisors Advisors available
* @return <code>true</code> if any special {@link Advisor Advisors} were added, otherwise <code>false</code>. * @return <code>true</code> if any special {@link Advisor Advisors} were added, otherwise <code>false</code>.
*/ */
public static boolean makeAdvisorChainAspectJCapableIfNecessary(List advisors) { public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) {
// Don't add advisors to an empty list; may indicate that proxying is just not required // Don't add advisors to an empty list; may indicate that proxying is just not required
if (!advisors.isEmpty()) { if (!advisors.isEmpty()) {
boolean foundAspectJAdvice = false; boolean foundAspectJAdvice = false;
for (Iterator it = advisors.iterator(); it.hasNext() && !foundAspectJAdvice; ) { for (Advisor advisor : advisors) {
Advisor advisor = (Advisor) it.next();
// Be careful not to get the Advice without a guard, as // Be careful not to get the Advice without a guard, as
// this might eagerly instantiate a non-singleton AspectJ aspect // this might eagerly instantiate a non-singleton AspectJ aspect
if (isAspectJAdvice(advisor)) { if (isAspectJAdvice(advisor)) {

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.aop.aspectj.annotation;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -138,8 +137,7 @@ public class BeanFactoryAspectJAdvisorsBuilder {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<Advisor> advisors = new LinkedList<Advisor>(); List<Advisor> advisors = new LinkedList<Advisor>();
for (Iterator it = aspectNames.iterator(); it.hasNext();) { for (String aspectName : aspectNames) {
String aspectName = (String) it.next();
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName); List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) { if (cachedAdvisors != null) {
advisors.addAll(cachedAdvisors); advisors.addAll(cachedAdvisors);

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.aop.aspectj.autoproxy; package org.springframework.aop.aspectj.autoproxy;
import java.util.Comparator; import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -65,27 +64,27 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx
* advisor should run last. * advisor should run last.
*/ */
@Override @Override
protected List sortAdvisors(List advisors) { @SuppressWarnings("unchecked")
protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
// build list for sorting // build list for sorting
List partiallyComparableAdvisors = new LinkedList(); List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors =
for (Iterator it = advisors.iterator(); it.hasNext();) { new LinkedList<PartiallyComparableAdvisorHolder>();
Advisor element = (Advisor) it.next(); for (Advisor element : advisors) {
PartiallyComparableAdvisorHolder advisor = partiallyComparableAdvisors.add(
new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR); new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR));
partiallyComparableAdvisors.add(advisor);
} }
// sort it // sort it
List sorted = PartialOrder.sort(partiallyComparableAdvisors); List<PartiallyComparableAdvisorHolder> sorted =
(List<PartiallyComparableAdvisorHolder>) PartialOrder.sort(partiallyComparableAdvisors);
if (sorted == null) { if (sorted == null) {
// TODO: work much harder to give a better error message here. // TODO: work harder to give a better error message here.
throw new IllegalArgumentException("Advice precedence circularity error"); throw new IllegalArgumentException("Advice precedence circularity error");
} }
// extract results again // extract results again
List result = new LinkedList(); List<Advisor> result = new LinkedList<Advisor>();
for (Iterator it = sorted.iterator(); it.hasNext();) { for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) {
PartiallyComparableAdvisorHolder pcAdvisor = (PartiallyComparableAdvisorHolder) it.next();
result.add(pcAdvisor.getAdvisor()); result.add(pcAdvisor.getAdvisor());
} }
@ -98,18 +97,17 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx
* and when using AspectJ-style advice. * and when using AspectJ-style advice.
*/ */
@Override @Override
protected void extendAdvisors(List candidateAdvisors) { protected void extendAdvisors(List<Advisor> candidateAdvisors) {
AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors); AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
} }
@Override @Override
protected boolean shouldSkip(Class beanClass, String beanName) { protected boolean shouldSkip(Class beanClass, String beanName) {
// TODO: Consider optimization by caching the list of the aspect names // TODO: Consider optimization by caching the list of the aspect names
List candidtate = findCandidateAdvisors(); List<Advisor> candidateAdvisors = findCandidateAdvisors();
for (Iterator it = candidtate.iterator(); it.hasNext();) { for (Advisor advisor : candidateAdvisors) {
Advisor advisor = (Advisor) it.next();
if (advisor instanceof AspectJPointcutAdvisor) { if (advisor instanceof AspectJPointcutAdvisor) {
if(((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) { if (((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) {
return true; return true;
} }
} }
@ -117,6 +115,7 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx
return super.shouldSkip(beanClass, beanName); return super.shouldSkip(beanClass, beanName);
} }
/** /**
* Implements AspectJ PartialComparable interface for defining partial orderings. * Implements AspectJ PartialComparable interface for defining partial orderings.
*/ */
@ -124,9 +123,9 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx
private final Advisor advisor; private final Advisor advisor;
private final Comparator comparator; private final Comparator<Advisor> comparator;
public PartiallyComparableAdvisorHolder(Advisor advisor, Comparator comparator) { public PartiallyComparableAdvisorHolder(Advisor advisor, Comparator<Advisor> comparator) {
this.advisor = advisor; this.advisor = advisor;
this.comparator = comparator; this.comparator = comparator;
} }
@ -151,7 +150,7 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx
sb.append(ClassUtils.getShortName(advice.getClass())); sb.append(ClassUtils.getShortName(advice.getClass()));
sb.append(": "); sb.append(": ");
if (this.advisor instanceof Ordered) { if (this.advisor instanceof Ordered) {
sb.append("order " + ((Ordered) this.advisor).getOrder() + ", "); sb.append("order ").append(((Ordered) this.advisor).getOrder()).append(", ");
} }
if (advice instanceof AbstractAspectJAdvice) { if (advice instanceof AbstractAspectJAdvice) {
AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice; AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice;

View File

@ -62,7 +62,8 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
private ConfigurableBeanFactory beanFactory; private ConfigurableBeanFactory beanFactory;
/** Internally used DefaultListableBeanFactory instances, keyed by bean name */ /** Internally used DefaultListableBeanFactory instances, keyed by bean name */
private final Map internalBeanFactories = new HashMap(); private final Map<String, DefaultListableBeanFactory> internalBeanFactories =
new HashMap<String, DefaultListableBeanFactory>();
public final void setBeanFactory(BeanFactory beanFactory) { public final void setBeanFactory(BeanFactory beanFactory) {
@ -121,15 +122,14 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
* @return the internal BeanFactory to be used * @return the internal BeanFactory to be used
*/ */
protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) { protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) {
DefaultListableBeanFactory internalBeanFactory = null;
synchronized (this.internalBeanFactories) { synchronized (this.internalBeanFactories) {
internalBeanFactory = (DefaultListableBeanFactory) this.internalBeanFactories.get(beanName); DefaultListableBeanFactory internalBeanFactory = this.internalBeanFactories.get(beanName);
if (internalBeanFactory == null) { if (internalBeanFactory == null) {
internalBeanFactory = buildInternalBeanFactory(this.beanFactory); internalBeanFactory = buildInternalBeanFactory(this.beanFactory);
this.internalBeanFactories.put(beanName, internalBeanFactory); this.internalBeanFactories.put(beanName, internalBeanFactory);
} }
return internalBeanFactory;
} }
return internalBeanFactory;
} }
/** /**
@ -146,9 +146,8 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
// Filter out BeanPostProcessors that are part of the AOP infrastructure, // Filter out BeanPostProcessors that are part of the AOP infrastructure,
// since those are only meant to apply to beans defined in the original factory. // since those are only meant to apply to beans defined in the original factory.
for (Iterator it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) { for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor postProcessor = (BeanPostProcessor) it.next(); if (it.next() instanceof AopInfrastructureBean) {
if (postProcessor instanceof AopInfrastructureBean) {
it.remove(); it.remove();
} }
} }
@ -162,8 +161,8 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
*/ */
public void destroy() { public void destroy() {
synchronized (this.internalBeanFactories) { synchronized (this.internalBeanFactories) {
for (Iterator it = this.internalBeanFactories.values().iterator(); it.hasNext();) { for (DefaultListableBeanFactory bf : this.internalBeanFactories.values()) {
((DefaultListableBeanFactory) it.next()).destroySingletons(); bf.destroySingletons();
} }
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.aop.support;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; import java.util.Set;
import org.aopalliance.aop.Advice; import org.aopalliance.aop.Advice;
@ -43,7 +42,7 @@ public class DefaultIntroductionAdvisor implements IntroductionAdvisor, ClassFil
private final Advice advice; private final Advice advice;
private final Set interfaces = new HashSet(); private final Set<Class> interfaces = new HashSet<Class>();
private int order = Integer.MAX_VALUE; private int order = Integer.MAX_VALUE;
@ -72,8 +71,8 @@ public class DefaultIntroductionAdvisor implements IntroductionAdvisor, ClassFil
if (introducedInterfaces.length == 0) { if (introducedInterfaces.length == 0) {
throw new IllegalArgumentException("IntroductionAdviceSupport implements no interfaces"); throw new IllegalArgumentException("IntroductionAdviceSupport implements no interfaces");
} }
for (int i = 0; i < introducedInterfaces.length; i++) { for (Class ifc : introducedInterfaces) {
addInterface(introducedInterfaces[i]); addInterface(ifc);
} }
} }
} }
@ -103,12 +102,11 @@ public class DefaultIntroductionAdvisor implements IntroductionAdvisor, ClassFil
} }
public Class[] getInterfaces() { public Class[] getInterfaces() {
return (Class[]) this.interfaces.toArray(new Class[this.interfaces.size()]); return this.interfaces.toArray(new Class[this.interfaces.size()]);
} }
public void validateInterfaces() throws IllegalArgumentException { public void validateInterfaces() throws IllegalArgumentException {
for (Iterator it = this.interfaces.iterator(); it.hasNext();) { for (Class ifc : this.interfaces) {
Class ifc = (Class) it.next();
if (this.advice instanceof DynamicIntroductionAdvice && if (this.advice instanceof DynamicIntroductionAdvice &&
!((DynamicIntroductionAdvice) this.advice).implementsInterface(ifc)) { !((DynamicIntroductionAdvice) this.advice).implementsInterface(ifc)) {
throw new IllegalArgumentException("DynamicIntroductionAdvice [" + this.advice + "] " + throw new IllegalArgumentException("DynamicIntroductionAdvice [" + this.advice + "] " +

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,9 +19,9 @@ package org.springframework.aop.support;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.Serializable; import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashSet; import java.util.HashSet;
import java.util.IdentityHashMap; import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -46,13 +46,9 @@ public class IntroductionInfoSupport implements IntroductionInfo, Serializable {
protected transient Log logger = LogFactory.getLog(getClass()); protected transient Log logger = LogFactory.getLog(getClass());
/** Set of interface Classes */ protected Set<Class> publishedInterfaces = new HashSet<Class>();
protected Set publishedInterfaces = new HashSet();
/** private transient Map<Method, Boolean> rememberedMethods = new IdentityHashMap<Method, Boolean>(32);
* Methods that we know we should implement here: key is Method, value is Boolean.
**/
private transient Map rememberedMethods = createRememberedMethodMap();
/** /**
@ -67,18 +63,17 @@ public class IntroductionInfoSupport implements IntroductionInfo, Serializable {
} }
public Class[] getInterfaces() { public Class[] getInterfaces() {
return (Class[]) this.publishedInterfaces.toArray(new Class[this.publishedInterfaces.size()]); return this.publishedInterfaces.toArray(new Class[this.publishedInterfaces.size()]);
} }
/** /**
* Check whether the specified interfaces is a published introduction interface. * Check whether the specified interfaces is a published introduction interface.
* @param intf the interface to check * @param ifc the interface to check
* @return whether the interface is part of this introduction * @return whether the interface is part of this introduction
*/ */
public boolean implementsInterface(Class intf) { public boolean implementsInterface(Class ifc) {
for (Iterator it = this.publishedInterfaces.iterator(); it.hasNext();) { for (Class pubIfc : this.publishedInterfaces) {
Class pubIntf = (Class) it.next(); if (ifc.isInterface() && ifc.isAssignableFrom(pubIfc)) {
if (intf.isInterface() && intf.isAssignableFrom(pubIntf)) {
return true; return true;
} }
} }
@ -93,24 +88,20 @@ public class IntroductionInfoSupport implements IntroductionInfo, Serializable {
this.publishedInterfaces.addAll(ClassUtils.getAllInterfacesAsSet(delegate)); this.publishedInterfaces.addAll(ClassUtils.getAllInterfacesAsSet(delegate));
} }
private Map createRememberedMethodMap() {
return new IdentityHashMap(32);
}
/** /**
* Is this method on an introduced interface? * Is this method on an introduced interface?
* @param mi the method invocation * @param mi the method invocation
* @return whether the invoked method is on an introduced interface * @return whether the invoked method is on an introduced interface
*/ */
protected final boolean isMethodOnIntroducedInterface(MethodInvocation mi) { protected final boolean isMethodOnIntroducedInterface(MethodInvocation mi) {
Boolean rememberedResult = (Boolean) this.rememberedMethods.get(mi.getMethod()); Boolean rememberedResult = this.rememberedMethods.get(mi.getMethod());
if (rememberedResult != null) { if (rememberedResult != null) {
return rememberedResult.booleanValue(); return rememberedResult;
} }
else { else {
// Work it out and cache it. // Work it out and cache it.
boolean result = implementsInterface(mi.getMethod().getDeclaringClass()); boolean result = implementsInterface(mi.getMethod().getDeclaringClass());
this.rememberedMethods.put(mi.getMethod(), (result ? Boolean.TRUE : Boolean.FALSE)); this.rememberedMethods.put(mi.getMethod(), result);
return result; return result;
} }
} }
@ -131,7 +122,7 @@ public class IntroductionInfoSupport implements IntroductionInfo, Serializable {
// Initialize transient fields. // Initialize transient fields.
this.logger = LogFactory.getLog(getClass()); this.logger = LogFactory.getLog(getClass());
this.rememberedMethods = createRememberedMethodMap(); this.rememberedMethods = new IdentityHashMap<Method, Boolean>(32);
} }
} }

View File

@ -103,16 +103,16 @@ public class CachedIntrospectionResults {
return; return;
} }
synchronized (classCache) { synchronized (classCache) {
for (Iterator it = classCache.keySet().iterator(); it.hasNext();) { for (Iterator<Class> it = classCache.keySet().iterator(); it.hasNext();) {
Class beanClass = (Class) it.next(); Class beanClass = it.next();
if (isUnderneathClassLoader(beanClass.getClassLoader(), classLoader)) { if (isUnderneathClassLoader(beanClass.getClassLoader(), classLoader)) {
it.remove(); it.remove();
} }
} }
} }
synchronized (acceptedClassLoaders) { synchronized (acceptedClassLoaders) {
for (Iterator it = acceptedClassLoaders.iterator(); it.hasNext();) { for (Iterator<ClassLoader> it = acceptedClassLoaders.iterator(); it.hasNext();) {
ClassLoader registeredLoader = (ClassLoader) it.next(); ClassLoader registeredLoader = it.next();
if (isUnderneathClassLoader(registeredLoader, classLoader)) { if (isUnderneathClassLoader(registeredLoader, classLoader)) {
it.remove(); it.remove();
} }

View File

@ -79,15 +79,15 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
private boolean configValueEditorsActive = false; private boolean configValueEditorsActive = false;
private boolean propertySpecificEditorsRegistered = false; private Map<Class, PropertyEditor> defaultEditors;
private Map defaultEditors; private Map<Class, PropertyEditor> customEditors;
private Map customEditors; private Map<String, CustomEditorHolder> customEditorsForPath;
private Set sharedEditors; private Set<PropertyEditor> sharedEditors;
private Map customEditorCache; private Map<Class, PropertyEditor> customEditorCache;
//--------------------------------------------------------------------- //---------------------------------------------------------------------
@ -127,7 +127,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
if (this.defaultEditors == null) { if (this.defaultEditors == null) {
doRegisterDefaultEditors(); doRegisterDefaultEditors();
} }
return (PropertyEditor) this.defaultEditors.get(requiredType); return this.defaultEditors.get(requiredType);
} }
/** /**
@ -152,7 +152,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* @see org.springframework.beans.propertyeditors.URLEditor * @see org.springframework.beans.propertyeditors.URLEditor
*/ */
private void doRegisterDefaultEditors() { private void doRegisterDefaultEditors() {
this.defaultEditors = new HashMap(64); this.defaultEditors = new HashMap<Class, PropertyEditor>(64);
// Simple editors, without parameterization capabilities. // Simple editors, without parameterization capabilities.
// The JDK does not contain a default editor for any of these target types. // The JDK does not contain a default editor for any of these target types.
@ -238,14 +238,16 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
if (requiredType == null && propertyPath == null) { if (requiredType == null && propertyPath == null) {
throw new IllegalArgumentException("Either requiredType or propertyPath is required"); throw new IllegalArgumentException("Either requiredType or propertyPath is required");
} }
if (this.customEditors == null) {
this.customEditors = new LinkedHashMap(16);
}
if (propertyPath != null) { if (propertyPath != null) {
this.customEditors.put(propertyPath, new CustomEditorHolder(propertyEditor, requiredType)); if (this.customEditorsForPath == null) {
this.propertySpecificEditorsRegistered = true; this.customEditorsForPath = new LinkedHashMap<String, CustomEditorHolder>(16);
}
this.customEditorsForPath.put(propertyPath, new CustomEditorHolder(propertyEditor, requiredType));
} }
else { else {
if (this.customEditors == null) {
this.customEditors = new LinkedHashMap<Class, PropertyEditor>(16);
}
this.customEditors.put(requiredType, propertyEditor); this.customEditors.put(requiredType, propertyEditor);
this.customEditorCache = null; this.customEditorCache = null;
} }
@ -261,7 +263,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
public void registerSharedEditor(Class requiredType, PropertyEditor propertyEditor) { public void registerSharedEditor(Class requiredType, PropertyEditor propertyEditor) {
registerCustomEditor(requiredType, null, propertyEditor); registerCustomEditor(requiredType, null, propertyEditor);
if (this.sharedEditors == null) { if (this.sharedEditors == null) {
this.sharedEditors = new HashSet(); this.sharedEditors = new HashSet<PropertyEditor>();
} }
this.sharedEditors.add(propertyEditor); this.sharedEditors.add(propertyEditor);
} }
@ -277,19 +279,16 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
} }
public PropertyEditor findCustomEditor(Class requiredType, String propertyPath) { public PropertyEditor findCustomEditor(Class requiredType, String propertyPath) {
if (this.customEditors == null) {
return null;
}
Class requiredTypeToUse = requiredType; Class requiredTypeToUse = requiredType;
if (propertyPath != null) { if (propertyPath != null) {
if (this.propertySpecificEditorsRegistered) { if (this.customEditorsForPath != null) {
// Check property-specific editor first. // Check property-specific editor first.
PropertyEditor editor = getCustomEditor(propertyPath, requiredType); PropertyEditor editor = getCustomEditor(propertyPath, requiredType);
if (editor == null) { if (editor == null) {
List strippedPaths = new LinkedList(); List<String> strippedPaths = new LinkedList<String>();
addStrippedPropertyPaths(strippedPaths, "", propertyPath); addStrippedPropertyPaths(strippedPaths, "", propertyPath);
for (Iterator it = strippedPaths.iterator(); it.hasNext() && editor == null;) { for (Iterator<String> it = strippedPaths.iterator(); it.hasNext() && editor == null;) {
String strippedPath = (String) it.next(); String strippedPath = it.next();
editor = getCustomEditor(strippedPath, requiredType); editor = getCustomEditor(strippedPath, requiredType);
} }
} }
@ -315,25 +314,17 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* @return whether a matching custom editor has been found * @return whether a matching custom editor has been found
*/ */
public boolean hasCustomEditorForElement(Class elementType, String propertyPath) { public boolean hasCustomEditorForElement(Class elementType, String propertyPath) {
if (this.customEditors == null) { if (propertyPath != null && this.customEditorsForPath != null) {
return false; for (Map.Entry<String, CustomEditorHolder> entry : this.customEditorsForPath.entrySet()) {
} if (PropertyAccessorUtils.matchesProperty(entry.getKey(), propertyPath)) {
if (propertyPath != null && this.propertySpecificEditorsRegistered) { if (entry.getValue().getPropertyEditor(elementType) != null) {
for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { return true;
Map.Entry entry = (Map.Entry) it.next();
if (entry.getKey() instanceof String) {
String regPath = (String) entry.getKey();
if (PropertyAccessorUtils.matchesProperty(regPath, propertyPath)) {
CustomEditorHolder editorHolder = (CustomEditorHolder) entry.getValue();
if (editorHolder.getPropertyEditor(elementType) != null) {
return true;
}
} }
} }
} }
} }
// No property-specific editor -> check type-specific editor. // No property-specific editor -> check type-specific editor.
return (elementType != null && this.customEditors.containsKey(elementType)); return (elementType != null && this.customEditors != null && this.customEditors.containsKey(elementType));
} }
/** /**
@ -358,7 +349,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* @return the custom editor, or <code>null</code> if none specific for this property * @return the custom editor, or <code>null</code> if none specific for this property
*/ */
private PropertyEditor getCustomEditor(String propertyName, Class requiredType) { private PropertyEditor getCustomEditor(String propertyName, Class requiredType) {
CustomEditorHolder holder = (CustomEditorHolder) this.customEditors.get(propertyName); CustomEditorHolder holder = this.customEditorsForPath.get(propertyName);
return (holder != null ? holder.getPropertyEditor(requiredType) : null); return (holder != null ? holder.getPropertyEditor(requiredType) : null);
} }
@ -371,26 +362,26 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* @see java.beans.PropertyEditor#getAsText() * @see java.beans.PropertyEditor#getAsText()
*/ */
private PropertyEditor getCustomEditor(Class requiredType) { private PropertyEditor getCustomEditor(Class requiredType) {
if (requiredType == null) { if (requiredType == null || this.customEditors == null) {
return null; return null;
} }
// Check directly registered editor for type. // Check directly registered editor for type.
PropertyEditor editor = (PropertyEditor) this.customEditors.get(requiredType); PropertyEditor editor = this.customEditors.get(requiredType);
if (editor == null) { if (editor == null) {
// Check cached editor for type, registered for superclass or interface. // Check cached editor for type, registered for superclass or interface.
if (this.customEditorCache != null) { if (this.customEditorCache != null) {
editor = (PropertyEditor) this.customEditorCache.get(requiredType); editor = this.customEditorCache.get(requiredType);
} }
if (editor == null) { if (editor == null) {
// Find editor for superclass or interface. // Find editor for superclass or interface.
for (Iterator it = this.customEditors.keySet().iterator(); it.hasNext() && editor == null;) { for (Iterator<Class> it = this.customEditors.keySet().iterator(); it.hasNext() && editor == null;) {
Object key = it.next(); Class key = it.next();
if (key instanceof Class && ((Class) key).isAssignableFrom(requiredType)) { if (key.isAssignableFrom(requiredType)) {
editor = (PropertyEditor) this.customEditors.get(key); editor = this.customEditors.get(key);
// Cache editor for search type, to avoid the overhead // Cache editor for search type, to avoid the overhead
// of repeated assignable-from checks. // of repeated assignable-from checks.
if (this.customEditorCache == null) { if (this.customEditorCache == null) {
this.customEditorCache = new HashMap(); this.customEditorCache = new HashMap<Class, PropertyEditor>();
} }
this.customEditorCache.put(requiredType, editor); this.customEditorCache.put(requiredType, editor);
} }
@ -407,14 +398,14 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* @return the property type, or <code>null</code> if not determinable * @return the property type, or <code>null</code> if not determinable
*/ */
protected Class guessPropertyTypeFromEditors(String propertyName) { protected Class guessPropertyTypeFromEditors(String propertyName) {
if (this.customEditors != null) { if (this.customEditorsForPath != null) {
CustomEditorHolder editorHolder = (CustomEditorHolder) this.customEditors.get(propertyName); CustomEditorHolder editorHolder = this.customEditorsForPath.get(propertyName);
if (editorHolder == null) { if (editorHolder == null) {
List strippedPaths = new LinkedList(); List<String> strippedPaths = new LinkedList<String>();
addStrippedPropertyPaths(strippedPaths, "", propertyName); addStrippedPropertyPaths(strippedPaths, "", propertyName);
for (Iterator it = strippedPaths.iterator(); it.hasNext() && editorHolder == null;) { for (Iterator<String> it = strippedPaths.iterator(); it.hasNext() && editorHolder == null;) {
String strippedName = (String) it.next(); String strippedName = it.next();
editorHolder = (CustomEditorHolder) this.customEditors.get(strippedName); editorHolder = this.customEditorsForPath.get(strippedName);
} }
} }
if (editorHolder != null) { if (editorHolder != null) {
@ -435,31 +426,28 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
String actualPropertyName = String actualPropertyName =
(nestedProperty != null ? PropertyAccessorUtils.getPropertyName(nestedProperty) : null); (nestedProperty != null ? PropertyAccessorUtils.getPropertyName(nestedProperty) : null);
if (this.customEditors != null) { if (this.customEditors != null) {
for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { for (Map.Entry<Class, PropertyEditor> entry : this.customEditors.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); target.registerCustomEditor(entry.getKey(), entry.getValue());
if (entry.getKey() instanceof Class) { }
Class requiredType = (Class) entry.getKey(); }
PropertyEditor editor = (PropertyEditor) entry.getValue(); if (this.customEditorsForPath != null) {
target.registerCustomEditor(requiredType, editor); for (Map.Entry<String, CustomEditorHolder> entry : this.customEditorsForPath.entrySet()) {
} String editorPath = entry.getKey();
else if (entry.getKey() instanceof String) { CustomEditorHolder editorHolder = entry.getValue();
String editorPath = (String) entry.getKey(); if (nestedProperty != null) {
CustomEditorHolder editorHolder = (CustomEditorHolder) entry.getValue(); int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(editorPath);
if (nestedProperty != null) { if (pos != -1) {
int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(editorPath); String editorNestedProperty = editorPath.substring(0, pos);
if (pos != -1) { String editorNestedPath = editorPath.substring(pos + 1);
String editorNestedProperty = editorPath.substring(0, pos); if (editorNestedProperty.equals(nestedProperty) || editorNestedProperty.equals(actualPropertyName)) {
String editorNestedPath = editorPath.substring(pos + 1); target.registerCustomEditor(
if (editorNestedProperty.equals(nestedProperty) || editorNestedProperty.equals(actualPropertyName)) { editorHolder.getRegisteredType(), editorNestedPath, editorHolder.getPropertyEditor());
target.registerCustomEditor(
editorHolder.getRegisteredType(), editorNestedPath, editorHolder.getPropertyEditor());
}
} }
} }
else { }
target.registerCustomEditor( else {
editorHolder.getRegisteredType(), editorPath, editorHolder.getPropertyEditor()); target.registerCustomEditor(
} editorHolder.getRegisteredType(), editorPath, editorHolder.getPropertyEditor());
} }
} }
} }
@ -473,7 +461,7 @@ public class PropertyEditorRegistrySupport implements PropertyEditorRegistry {
* @param nestedPath the current nested path * @param nestedPath the current nested path
* @param propertyPath the property path to check for keys/indexes to strip * @param propertyPath the property path to check for keys/indexes to strip
*/ */
private void addStrippedPropertyPaths(List strippedPaths, String nestedPath, String propertyPath) { private void addStrippedPropertyPaths(List<String> strippedPaths, String nestedPath, String propertyPath) {
int startIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR); int startIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
if (startIndex != -1) { if (startIndex != -1) {
int endIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR); int endIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);

View File

@ -214,10 +214,11 @@ class TypeConverterDelegate {
msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
if (propertyName != null) { if (propertyName != null) {
msg.append(" for property '" + propertyName + "'"); msg.append(" for property '").append(propertyName).append("'");
} }
if (editor != null) { if (editor != null) {
msg.append(": PropertyEditor [" + editor.getClass().getName() + "] returned inappropriate value"); msg.append(": PropertyEditor [").append(editor.getClass().getName()).append(
"] returned inappropriate value");
} }
else { else {
msg.append(": no matching editors or conversion strategy found"); msg.append(": no matching editors or conversion strategy found");
@ -242,7 +243,7 @@ class TypeConverterDelegate {
} }
if (editor == null && requiredType != null) { if (editor == null && requiredType != null) {
// No custom editor -> check BeanWrapperImpl's default editors. // No custom editor -> check BeanWrapperImpl's default editors.
editor = (PropertyEditor) this.propertyEditorRegistry.getDefaultEditor(requiredType); editor = this.propertyEditorRegistry.getDefaultEditor(requiredType);
if (editor == null && !String.class.equals(requiredType)) { if (editor == null && !String.class.equals(requiredType)) {
// No BeanWrapper default editor -> check standard JavaBean editor. // No BeanWrapper default editor -> check standard JavaBean editor.
editor = BeanUtils.findEditorByConvention(requiredType); editor = BeanUtils.findEditorByConvention(requiredType);
@ -394,6 +395,7 @@ class TypeConverterDelegate {
} }
} }
@SuppressWarnings("unchecked")
protected Collection convertToTypedCollection( protected Collection convertToTypedCollection(
Collection original, String propertyName, MethodParameter methodParam) { Collection original, String propertyName, MethodParameter methodParam) {
@ -445,6 +447,7 @@ class TypeConverterDelegate {
return (actuallyConverted ? convertedCopy : original); return (actuallyConverted ? convertedCopy : original);
} }
@SuppressWarnings("unchecked")
protected Map convertToTypedMap(Map original, String propertyName, MethodParameter methodParam) { protected Map convertToTypedMap(Map original, String propertyName, MethodParameter methodParam) {
Class keyType = null; Class keyType = null;
Class valueType = null; Class valueType = null;
@ -466,6 +469,7 @@ class TypeConverterDelegate {
logger.debug("Map of type [" + original.getClass().getName() + logger.debug("Map of type [" + original.getClass().getName() +
"] returned null Iterator - injecting original Map as-is"); "] returned null Iterator - injecting original Map as-is");
} }
return original;
} }
convertedCopy = CollectionFactory.createApproximateMap(original, original.size()); convertedCopy = CollectionFactory.createApproximateMap(original, original.size());
} }

View File

@ -85,7 +85,7 @@ public abstract class BeanFactoryUtils {
* @see org.springframework.beans.factory.support.DefaultBeanNameGenerator * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator
*/ */
public static boolean isGeneratedBeanName(String name) { public static boolean isGeneratedBeanName(String name) {
return (name != null && name.indexOf(GENERATED_BEAN_NAME_SEPARATOR) != -1); return (name != null && name.contains(GENERATED_BEAN_NAME_SEPARATOR));
} }
/** /**
@ -298,10 +298,10 @@ public abstract class BeanFactoryUtils {
* if 0 or more than 1 beans of the given type were found * if 0 or more than 1 beans of the given type were found
* @throws BeansException if the bean could not be created * @throws BeansException if the bean could not be created
*/ */
public static Object beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) public static <T> T beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
throws BeansException { throws BeansException {
Map beansOfType = beansOfTypeIncludingAncestors(lbf, type); Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type);
if (beansOfType.size() == 1) { if (beansOfType.size() == 1) {
return beansOfType.values().iterator().next(); return beansOfType.values().iterator().next();
} }
@ -335,11 +335,11 @@ public abstract class BeanFactoryUtils {
* if 0 or more than 1 beans of the given type were found * if 0 or more than 1 beans of the given type were found
* @throws BeansException if the bean could not be created * @throws BeansException if the bean could not be created
*/ */
public static Object beanOfTypeIncludingAncestors( public static <T> T beanOfTypeIncludingAncestors(
ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException { throws BeansException {
Map beansOfType = beansOfTypeIncludingAncestors(lbf, type, includeNonSingletons, allowEagerInit); Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type, includeNonSingletons, allowEagerInit);
if (beansOfType.size() == 1) { if (beansOfType.size() == 1) {
return beansOfType.values().iterator().next(); return beansOfType.values().iterator().next();
} }
@ -364,9 +364,9 @@ public abstract class BeanFactoryUtils {
* if 0 or more than 1 beans of the given type were found * if 0 or more than 1 beans of the given type were found
* @throws BeansException if the bean could not be created * @throws BeansException if the bean could not be created
*/ */
public static Object beanOfType(ListableBeanFactory lbf, Class type) throws BeansException { public static <T> T beanOfType(ListableBeanFactory lbf, Class<T> type) throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null"); Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map beansOfType = lbf.getBeansOfType(type); Map<String, T> beansOfType = lbf.getBeansOfType(type);
if (beansOfType.size() == 1) { if (beansOfType.size() == 1) {
return beansOfType.values().iterator().next(); return beansOfType.values().iterator().next();
} }
@ -399,12 +399,12 @@ public abstract class BeanFactoryUtils {
* if 0 or more than 1 beans of the given type were found * if 0 or more than 1 beans of the given type were found
* @throws BeansException if the bean could not be created * @throws BeansException if the bean could not be created
*/ */
public static Object beanOfType( public static <T> T beanOfType(
ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException { throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null"); Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map beansOfType = lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit); Map<String, T> beansOfType = lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit);
if (beansOfType.size() == 1) { if (beansOfType.size() == 1) {
return beansOfType.values().iterator().next(); return beansOfType.values().iterator().next();
} }

View File

@ -16,7 +16,6 @@
package org.springframework.beans.factory.config; package org.springframework.beans.factory.config;
import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
@ -137,8 +136,7 @@ public class BeanDefinitionVisitor {
protected void visitPropertyValues(MutablePropertyValues pvs) { protected void visitPropertyValues(MutablePropertyValues pvs) {
PropertyValue[] pvArray = pvs.getPropertyValues(); PropertyValue[] pvArray = pvs.getPropertyValues();
for (int i = 0; i < pvArray.length; i++) { for (PropertyValue pv : pvArray) {
PropertyValue pv = pvArray[i];
Object newVal = resolveValue(pv.getValue()); Object newVal = resolveValue(pv.getValue());
if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) { if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) {
pvs.addPropertyValue(pv.getName(), newVal); pvs.addPropertyValue(pv.getName(), newVal);
@ -146,10 +144,8 @@ public class BeanDefinitionVisitor {
} }
} }
protected void visitIndexedArgumentValues(Map ias) { protected void visitIndexedArgumentValues(Map<Integer, ConstructorArgumentValues.ValueHolder> ias) {
for (Iterator it = ias.values().iterator(); it.hasNext();) { for (ConstructorArgumentValues.ValueHolder valueHolder : ias.values()) {
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder) it.next();
Object newVal = resolveValue(valueHolder.getValue()); Object newVal = resolveValue(valueHolder.getValue());
if (!ObjectUtils.nullSafeEquals(newVal, valueHolder.getValue())) { if (!ObjectUtils.nullSafeEquals(newVal, valueHolder.getValue())) {
valueHolder.setValue(newVal); valueHolder.setValue(newVal);
@ -157,10 +153,8 @@ public class BeanDefinitionVisitor {
} }
} }
protected void visitGenericArgumentValues(List gas) { protected void visitGenericArgumentValues(List<ConstructorArgumentValues.ValueHolder> gas) {
for (Iterator it = gas.iterator(); it.hasNext();) { for (ConstructorArgumentValues.ValueHolder valueHolder : gas) {
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder) it.next();
Object newVal = resolveValue(valueHolder.getValue()); Object newVal = resolveValue(valueHolder.getValue());
if (!ObjectUtils.nullSafeEquals(newVal, valueHolder.getValue())) { if (!ObjectUtils.nullSafeEquals(newVal, valueHolder.getValue())) {
valueHolder.setValue(newVal); valueHolder.setValue(newVal);
@ -212,6 +206,7 @@ public class BeanDefinitionVisitor {
return value; return value;
} }
@SuppressWarnings("unchecked")
protected void visitList(List listVal) { protected void visitList(List listVal) {
for (int i = 0; i < listVal.size(); i++) { for (int i = 0; i < listVal.size(); i++) {
Object elem = listVal.get(i); Object elem = listVal.get(i);
@ -222,11 +217,11 @@ public class BeanDefinitionVisitor {
} }
} }
@SuppressWarnings("unchecked")
protected void visitSet(Set setVal) { protected void visitSet(Set setVal) {
Set newContent = new LinkedHashSet(); Set newContent = new LinkedHashSet();
boolean entriesModified = false; boolean entriesModified = false;
for (Iterator it = setVal.iterator(); it.hasNext();) { for (Object elem : setVal) {
Object elem = it.next();
int elemHash = (elem != null ? elem.hashCode() : 0); int elemHash = (elem != null ? elem.hashCode() : 0);
Object newVal = resolveValue(elem); Object newVal = resolveValue(elem);
int newValHash = (newVal != null ? newVal.hashCode() : 0); int newValHash = (newVal != null ? newVal.hashCode() : 0);
@ -239,11 +234,11 @@ public class BeanDefinitionVisitor {
} }
} }
protected void visitMap(Map mapVal) { @SuppressWarnings("unchecked")
protected void visitMap(Map<?, ?> mapVal) {
Map newContent = new LinkedHashMap(); Map newContent = new LinkedHashMap();
boolean entriesModified = false; boolean entriesModified = false;
for (Iterator it = mapVal.entrySet().iterator(); it.hasNext();) { for (Map.Entry entry : mapVal.entrySet()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey(); Object key = entry.getKey();
int keyHash = (key != null ? key.hashCode() : 0); int keyHash = (key != null ? key.hashCode() : 0);
Object newKey = resolveValue(key); Object newKey = resolveValue(key);

View File

@ -322,11 +322,11 @@ public class ConstructorArgumentValues {
this.indexedArgumentValues.size() != that.indexedArgumentValues.size()) { this.indexedArgumentValues.size() != that.indexedArgumentValues.size()) {
return false; return false;
} }
Iterator it1 = this.genericArgumentValues.iterator(); Iterator<ValueHolder> it1 = this.genericArgumentValues.iterator();
Iterator it2 = that.genericArgumentValues.iterator(); Iterator<ValueHolder> it2 = that.genericArgumentValues.iterator();
while (it1.hasNext() && it2.hasNext()) { while (it1.hasNext() && it2.hasNext()) {
ValueHolder vh1 = (ValueHolder) it1.next(); ValueHolder vh1 = it1.next();
ValueHolder vh2 = (ValueHolder) it2.next(); ValueHolder vh2 = it2.next();
if (!vh1.contentEquals(vh2)) { if (!vh1.contentEquals(vh2)) {
return false; return false;
} }

View File

@ -16,7 +16,6 @@
package org.springframework.beans.factory.config; package org.springframework.beans.factory.config;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
@ -45,7 +44,7 @@ import org.springframework.util.ClassUtils;
*/ */
public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered { public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered {
private Map scopes; private Map<String, Object> scopes;
private int order = Ordered.LOWEST_PRECEDENCE; private int order = Ordered.LOWEST_PRECEDENCE;
@ -58,7 +57,7 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas
* is expected to be the corresponding custom {@link Scope} instance * is expected to be the corresponding custom {@link Scope} instance
* or class name. * or class name.
*/ */
public void setScopes(Map scopes) { public void setScopes(Map<String, Object> scopes) {
this.scopes = scopes; this.scopes = scopes;
} }
@ -77,31 +76,25 @@ public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClas
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.scopes != null) { if (this.scopes != null) {
for (Iterator it = this.scopes.entrySet().iterator(); it.hasNext();) { for (Map.Entry<String, Object> entry : this.scopes.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); String scopeKey = entry.getKey();
Object key = entry.getKey();
if (!(key instanceof String)) {
throw new IllegalArgumentException(
"Invalid scope key [" + key + "]: only Strings allowed");
}
String scopeName = (String) key;
Object value = entry.getValue(); Object value = entry.getValue();
if (value instanceof Scope) { if (value instanceof Scope) {
beanFactory.registerScope(scopeName, (Scope) value); beanFactory.registerScope(scopeKey, (Scope) value);
} }
else if (value instanceof Class) { else if (value instanceof Class) {
Class scopeClass = (Class) value; Class scopeClass = (Class) value;
Assert.isAssignable(Scope.class, scopeClass); Assert.isAssignable(Scope.class, scopeClass);
beanFactory.registerScope(scopeName, (Scope) BeanUtils.instantiateClass(scopeClass)); beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass));
} }
else if (value instanceof String) { else if (value instanceof String) {
Class scopeClass = ClassUtils.resolveClassName((String) value, this.beanClassLoader); Class scopeClass = ClassUtils.resolveClassName((String) value, this.beanClassLoader);
Assert.isAssignable(Scope.class, scopeClass); Assert.isAssignable(Scope.class, scopeClass);
beanFactory.registerScope(scopeName, (Scope) BeanUtils.instantiateClass(scopeClass)); beanFactory.registerScope(scopeKey, (Scope) BeanUtils.instantiateClass(scopeClass));
} }
else { else {
throw new IllegalArgumentException("Mapped value [" + value + "] for scope key [" + throw new IllegalArgumentException("Mapped value [" + value + "] for scope key [" +
key + "] is not an instance of required type [" + Scope.class.getName() + scopeKey + "] is not an instance of required type [" + Scope.class.getName() +
"] or a corresponding Class or String value indicating a Scope implementation"); "] or a corresponding Class or String value indicating a Scope implementation");
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,13 +17,11 @@
package org.springframework.beans.factory.config; package org.springframework.beans.factory.config;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.TypeConverter; import org.springframework.beans.TypeConverter;
import org.springframework.core.GenericCollectionTypeResolver; import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.JdkVersion;
/** /**
* Simple factory for shared List instances. Allows for central setup * Simple factory for shared List instances. Allows for central setup
@ -71,6 +69,7 @@ public class ListFactoryBean extends AbstractFactoryBean {
} }
@Override @Override
@SuppressWarnings("unchecked")
protected Object createInstance() { protected Object createInstance() {
if (this.sourceList == null) { if (this.sourceList == null) {
throw new IllegalArgumentException("'sourceList' is required"); throw new IllegalArgumentException("'sourceList' is required");
@ -88,8 +87,8 @@ public class ListFactoryBean extends AbstractFactoryBean {
} }
if (valueType != null) { if (valueType != null) {
TypeConverter converter = getBeanTypeConverter(); TypeConverter converter = getBeanTypeConverter();
for (Iterator it = this.sourceList.iterator(); it.hasNext();) { for (Object elem : this.sourceList) {
result.add(converter.convertIfNecessary(it.next(), valueType)); result.add(converter.convertIfNecessary(elem, valueType));
} }
} }
else { else {

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,14 +16,12 @@
package org.springframework.beans.factory.config; package org.springframework.beans.factory.config;
import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.TypeConverter; import org.springframework.beans.TypeConverter;
import org.springframework.core.GenericCollectionTypeResolver; import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.JdkVersion;
/** /**
* Simple factory for shared Map instances. Allows for central setup * Simple factory for shared Map instances. Allows for central setup
@ -36,7 +34,7 @@ import org.springframework.core.JdkVersion;
*/ */
public class MapFactoryBean extends AbstractFactoryBean { public class MapFactoryBean extends AbstractFactoryBean {
private Map sourceMap; private Map<?, ?> sourceMap;
private Class targetMapClass; private Class targetMapClass;
@ -71,6 +69,7 @@ public class MapFactoryBean extends AbstractFactoryBean {
} }
@Override @Override
@SuppressWarnings("unchecked")
protected Object createInstance() { protected Object createInstance() {
if (this.sourceMap == null) { if (this.sourceMap == null) {
throw new IllegalArgumentException("'sourceMap' is required"); throw new IllegalArgumentException("'sourceMap' is required");
@ -90,8 +89,7 @@ public class MapFactoryBean extends AbstractFactoryBean {
} }
if (keyType != null || valueType != null) { if (keyType != null || valueType != null) {
TypeConverter converter = getBeanTypeConverter(); TypeConverter converter = getBeanTypeConverter();
for (Iterator it = this.sourceMap.entrySet().iterator(); it.hasNext();) { for (Map.Entry entry : this.sourceMap.entrySet()) {
Map.Entry entry = (Map.Entry) it.next();
Object convertedKey = converter.convertIfNecessary(entry.getKey(), keyType); Object convertedKey = converter.convertIfNecessary(entry.getKey(), keyType);
Object convertedValue = converter.convertIfNecessary(entry.getValue(), valueType); Object convertedValue = converter.convertIfNecessary(entry.getValue(), valueType);
result.put(convertedKey, convertedValue); result.put(convertedKey, convertedValue);

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,6 @@
package org.springframework.beans.factory.config; package org.springframework.beans.factory.config;
import java.util.Iterator;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
@ -70,6 +69,7 @@ public class SetFactoryBean extends AbstractFactoryBean {
} }
@Override @Override
@SuppressWarnings("unchecked")
protected Object createInstance() { protected Object createInstance() {
if (this.sourceSet == null) { if (this.sourceSet == null) {
throw new IllegalArgumentException("'sourceSet' is required"); throw new IllegalArgumentException("'sourceSet' is required");
@ -87,8 +87,8 @@ public class SetFactoryBean extends AbstractFactoryBean {
} }
if (valueType != null) { if (valueType != null) {
TypeConverter converter = getBeanTypeConverter(); TypeConverter converter = getBeanTypeConverter();
for (Iterator it = this.sourceSet.iterator(); it.hasNext();) { for (Object elem : this.sourceSet) {
result.add(converter.convertIfNecessary(it.next(), valueType)); result.add(converter.convertIfNecessary(elem, valueType));
} }
} }
else { else {

View File

@ -1124,8 +1124,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
if (filtered == null) { if (filtered == null) {
List<PropertyDescriptor> pds = List<PropertyDescriptor> pds =
new LinkedList<PropertyDescriptor>(Arrays.asList(bw.getPropertyDescriptors())); new LinkedList<PropertyDescriptor>(Arrays.asList(bw.getPropertyDescriptors()));
for (Iterator it = pds.iterator(); it.hasNext();) { for (Iterator<PropertyDescriptor> it = pds.iterator(); it.hasNext();) {
PropertyDescriptor pd = (PropertyDescriptor) it.next(); PropertyDescriptor pd = it.next();
if (isExcludedFromDependencyCheck(pd)) { if (isExcludedFromDependencyCheck(pd)) {
it.remove(); it.remove();
} }

View File

@ -500,9 +500,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
// Remove destroyed bean from other beans' dependencies. // Remove destroyed bean from other beans' dependencies.
synchronized (this.dependentBeanMap) { synchronized (this.dependentBeanMap) {
for (Iterator it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) { for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next(); Map.Entry<String, Set<String>> entry = it.next();
Set dependenciesToClean = (Set) entry.getValue(); Set<String> dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName); dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) { if (dependenciesToClean.isEmpty()) {
it.remove(); it.remove();

View File

@ -20,7 +20,6 @@ import java.io.Serializable;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -28,6 +27,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
@ -62,7 +62,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
private final boolean enforceDestroyMethod; private final boolean enforceDestroyMethod;
private List beanPostProcessors; private List<DestructionAwareBeanPostProcessor> beanPostProcessors;
/** /**
@ -73,8 +73,8 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
* @param postProcessors the List of BeanPostProcessors * @param postProcessors the List of BeanPostProcessors
* (potentially DestructionAwareBeanPostProcessor), if any * (potentially DestructionAwareBeanPostProcessor), if any
*/ */
public DisposableBeanAdapter( public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition,
Object bean, String beanName, RootBeanDefinition beanDefinition, List postProcessors) { List<BeanPostProcessor> postProcessors) {
Assert.notNull(bean, "Bean must not be null"); Assert.notNull(bean, "Bean must not be null");
this.bean = bean; this.bean = bean;
@ -100,7 +100,8 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
* @param postProcessors the List of DestructionAwareBeanPostProcessors, if any * @param postProcessors the List of DestructionAwareBeanPostProcessors, if any
*/ */
private DisposableBeanAdapter(Object bean, String beanName, boolean invokeDisposableBean, private DisposableBeanAdapter(Object bean, String beanName, boolean invokeDisposableBean,
String destroyMethodName, boolean enforceDestroyMethod, List postProcessors) { String destroyMethodName, boolean enforceDestroyMethod,
List<DestructionAwareBeanPostProcessor> postProcessors) {
this.bean = bean; this.bean = bean;
this.beanName = beanName; this.beanName = beanName;
@ -110,19 +111,19 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
this.beanPostProcessors = postProcessors; this.beanPostProcessors = postProcessors;
} }
/** /**
* Search for all DestructionAwareBeanPostProcessors in the List. * Search for all DestructionAwareBeanPostProcessors in the List.
* @param postProcessors the List to search * @param postProcessors the List to search
* @return the filtered List of DestructionAwareBeanPostProcessors * @return the filtered List of DestructionAwareBeanPostProcessors
*/ */
private List filterPostProcessors(List postProcessors) { private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> postProcessors) {
List filteredPostProcessors = null; List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
if (postProcessors != null && !postProcessors.isEmpty()) { if (postProcessors != null && !postProcessors.isEmpty()) {
filteredPostProcessors = new ArrayList(postProcessors.size()); filteredPostProcessors = new ArrayList<DestructionAwareBeanPostProcessor>(postProcessors.size());
for (Iterator it = postProcessors.iterator(); it.hasNext();) { for (BeanPostProcessor postProcessor : postProcessors) {
Object postProcessor = it.next();
if (postProcessor instanceof DestructionAwareBeanPostProcessor) { if (postProcessor instanceof DestructionAwareBeanPostProcessor) {
filteredPostProcessors.add(postProcessor); filteredPostProcessors.add((DestructionAwareBeanPostProcessor) postProcessor);
} }
} }
} }
@ -137,8 +138,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
public void destroy() { public void destroy() {
if (this.beanPostProcessors != null && !this.beanPostProcessors.isEmpty()) { if (this.beanPostProcessors != null && !this.beanPostProcessors.isEmpty()) {
for (int i = this.beanPostProcessors.size() - 1; i >= 0; i--) { for (int i = this.beanPostProcessors.size() - 1; i >= 0; i--) {
((DestructionAwareBeanPostProcessor) this.beanPostProcessors.get(i)).postProcessBeforeDestruction( this.beanPostProcessors.get(i).postProcessBeforeDestruction(this.bean, this.beanName);
this.bean, this.beanName);
} }
} }
@ -237,11 +237,10 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
* filtering out non-serializable BeanPostProcessors. * filtering out non-serializable BeanPostProcessors.
*/ */
protected Object writeReplace() { protected Object writeReplace() {
List serializablePostProcessors = null; List<DestructionAwareBeanPostProcessor> serializablePostProcessors = null;
if (this.beanPostProcessors != null) { if (this.beanPostProcessors != null) {
serializablePostProcessors = new ArrayList(); serializablePostProcessors = new ArrayList<DestructionAwareBeanPostProcessor>();
for (Iterator it = this.beanPostProcessors.iterator(); it.hasNext();) { for (DestructionAwareBeanPostProcessor postProcessor : this.beanPostProcessors) {
Object postProcessor = it.next();
if (postProcessor instanceof Serializable) { if (postProcessor instanceof Serializable) {
serializablePostProcessors.add(postProcessor); serializablePostProcessors.add(postProcessor);
} }

View File

@ -18,10 +18,8 @@ package org.springframework.beans.factory.support;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
@ -56,7 +54,7 @@ import org.springframework.util.StringUtils;
public class StaticListableBeanFactory implements ListableBeanFactory { public class StaticListableBeanFactory implements ListableBeanFactory {
/** Map from bean name to bean instance */ /** Map from bean name to bean instance */
private final Map beans = new HashMap(); private final Map<String, Object> beans = new HashMap<String, Object>();
/** /**
@ -99,13 +97,13 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
} }
return bean; return bean;
} }
public Object getBean(String name, Class requiredType) throws BeansException { public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
Object bean = getBean(name); Object bean = getBean(name);
if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) { if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
} }
return bean; return (T) bean;
} }
public Object getBean(String name, Object[] args) throws BeansException { public Object getBean(String name, Object[] args) throws BeansException {
@ -181,22 +179,19 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) { public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) {
boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type)); boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
List matches = new ArrayList(); List<String> matches = new ArrayList<String>();
Set keys = this.beans.keySet(); for (String name : this.beans.keySet()) {
Iterator it = keys.iterator();
while (it.hasNext()) {
String name = (String) it.next();
Object beanInstance = this.beans.get(name); Object beanInstance = this.beans.get(name);
if (beanInstance instanceof FactoryBean && !isFactoryType) { if (beanInstance instanceof FactoryBean && !isFactoryType) {
if (includeFactoryBeans) { if (includeFactoryBeans) {
Class objectType = ((FactoryBean) beanInstance).getObjectType(); Class objectType = ((FactoryBean) beanInstance).getObjectType();
if (objectType != null && type.isAssignableFrom(objectType)) { if (objectType != null && (type == null || type.isAssignableFrom(objectType))) {
matches.add(name); matches.add(name);
} }
} }
} }
else { else {
if (type.isInstance(beanInstance)) { if (type == null || type.isInstance(beanInstance)) {
matches.add(name); matches.add(name);
} }
} }
@ -204,22 +199,19 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
return StringUtils.toStringArray(matches); return StringUtils.toStringArray(matches);
} }
public Map getBeansOfType(Class type) throws BeansException { public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
return getBeansOfType(type, true, true); return getBeansOfType(type, true, true);
} }
public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean includeFactoryBeans)
throws BeansException { throws BeansException {
boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type)); boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type));
Map matches = new HashMap(); Map<String, T> matches = new HashMap<String, T>();
Iterator it = this.beans.entrySet().iterator(); for (Map.Entry<String, Object> entry : beans.entrySet()) {
while (it.hasNext()) { String beanName = entry.getKey();
Map.Entry entry = (Map.Entry) it.next();
String beanName = (String) entry.getKey();
Object beanInstance = entry.getValue(); Object beanInstance = entry.getValue();
// Is bean a FactoryBean? // Is bean a FactoryBean?
if (beanInstance instanceof FactoryBean && !isFactoryType) { if (beanInstance instanceof FactoryBean && !isFactoryType) {
if (includeFactoryBeans) { if (includeFactoryBeans) {
@ -227,19 +219,19 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
FactoryBean factory = (FactoryBean) beanInstance; FactoryBean factory = (FactoryBean) beanInstance;
Class objectType = factory.getObjectType(); Class objectType = factory.getObjectType();
if ((includeNonSingletons || factory.isSingleton()) && if ((includeNonSingletons || factory.isSingleton()) &&
objectType != null && type.isAssignableFrom(objectType)) { objectType != null && (type == null || type.isAssignableFrom(objectType))) {
matches.put(beanName, getBean(beanName)); matches.put(beanName, getBean(beanName, type));
} }
} }
} }
else { else {
if (type.isInstance(beanInstance)) { if (type == null || type.isInstance(beanInstance)) {
// If type to match is FactoryBean, return FactoryBean itself. // If type to match is FactoryBean, return FactoryBean itself.
// Else, return bean instance. // Else, return bean instance.
if (isFactoryType) { if (isFactoryType) {
beanName = FACTORY_BEAN_PREFIX + beanName; beanName = FACTORY_BEAN_PREFIX + beanName;
} }
matches.put(beanName, beanInstance); matches.put(beanName, (T) beanInstance);
} }
} }
} }

View File

@ -19,7 +19,6 @@ package org.springframework.beans.factory.xml;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
@ -737,9 +736,8 @@ public class BeanDefinitionParserDelegate {
String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE); String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE);
ReplaceOverride replaceOverride = new ReplaceOverride(name, callback); ReplaceOverride replaceOverride = new ReplaceOverride(name, callback);
// Look for arg-type match elements. // Look for arg-type match elements.
List argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT); List<Element> argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT);
for (Iterator it = argTypeEles.iterator(); it.hasNext();) { for (Element argTypeEle : argTypeEles) {
Element argTypeEle = (Element) it.next();
replaceOverride.addTypeIdentifier(argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE)); replaceOverride.addTypeIdentifier(argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE));
} }
replaceOverride.setSource(extractSource(replacedMethodEle)); replaceOverride.setSource(extractSource(replacedMethodEle));
@ -1109,17 +1107,15 @@ public class BeanDefinitionParserDelegate {
String defaultKeyTypeClassName = mapEle.getAttribute(KEY_TYPE_ATTRIBUTE); String defaultKeyTypeClassName = mapEle.getAttribute(KEY_TYPE_ATTRIBUTE);
String defaultValueTypeClassName = mapEle.getAttribute(VALUE_TYPE_ATTRIBUTE); String defaultValueTypeClassName = mapEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
List entryEles = DomUtils.getChildElementsByTagName(mapEle, ENTRY_ELEMENT); List<Element> entryEles = DomUtils.getChildElementsByTagName(mapEle, ENTRY_ELEMENT);
ManagedMap map = new ManagedMap(entryEles.size()); ManagedMap map = new ManagedMap(entryEles.size());
map.setMergeEnabled(parseMergeAttribute(mapEle)); map.setMergeEnabled(parseMergeAttribute(mapEle));
map.setSource(extractSource(mapEle)); map.setSource(extractSource(mapEle));
for (Iterator it = entryEles.iterator(); it.hasNext();) { for (Element entryEle : entryEles) {
Element entryEle = (Element) it.next();
// Should only have one value child element: ref, value, list, etc. // Should only have one value child element: ref, value, list, etc.
// Optionally, there might be a key child element. // Optionally, there might be a key child element.
NodeList entrySubNodes = entryEle.getChildNodes(); NodeList entrySubNodes = entryEle.getChildNodes();
Element keyEle = null; Element keyEle = null;
Element valueEle = null; Element valueEle = null;
for (int j = 0; j < entrySubNodes.getLength(); j++) { for (int j = 0; j < entrySubNodes.getLength(); j++) {
@ -1254,14 +1250,12 @@ public class BeanDefinitionParserDelegate {
props.setSource(extractSource(propsEle)); props.setSource(extractSource(propsEle));
props.setMergeEnabled(parseMergeAttribute(propsEle)); props.setMergeEnabled(parseMergeAttribute(propsEle));
List propEles = DomUtils.getChildElementsByTagName(propsEle, PROP_ELEMENT); List<Element> propEles = DomUtils.getChildElementsByTagName(propsEle, PROP_ELEMENT);
for (Iterator it = propEles.iterator(); it.hasNext();) { for (Element propEle : propEles) {
Element propEle = (Element) it.next();
String key = propEle.getAttribute(KEY_ATTRIBUTE); String key = propEle.getAttribute(KEY_ATTRIBUTE);
// Trim the text value to avoid unwanted whitespace // Trim the text value to avoid unwanted whitespace
// caused by typical XML formatting. // caused by typical XML formatting.
String value = DomUtils.getTextValue(propEle).trim(); String value = DomUtils.getTextValue(propEle).trim();
TypedStringValue keyHolder = new TypedStringValue(key); TypedStringValue keyHolder = new TypedStringValue(key);
keyHolder.setSource(extractSource(propEle)); keyHolder.setSource(extractSource(propEle));
TypedStringValue valueHolder = new TypedStringValue(value); TypedStringValue valueHolder = new TypedStringValue(value);

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -117,8 +117,8 @@ public class CustomCollectionEditor extends PropertyEditorSupport {
// Convert Collection elements. // Convert Collection elements.
Collection source = (Collection) value; Collection source = (Collection) value;
Collection target = createCollection(this.collectionType, source.size()); Collection target = createCollection(this.collectionType, source.size());
for (Iterator it = source.iterator(); it.hasNext();) { for (Object elem : source) {
target.add(convertElement(it.next())); target.add(convertElement(elem));
} }
super.setValue(target); super.setValue(target);
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.beans.propertyeditors; package org.springframework.beans.propertyeditors;
import java.beans.PropertyEditorSupport; import java.beans.PropertyEditorSupport;
import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.SortedMap; import java.util.SortedMap;
@ -105,10 +104,9 @@ public class CustomMapEditor extends PropertyEditorSupport {
} }
else if (value instanceof Map) { else if (value instanceof Map) {
// Convert Map elements. // Convert Map elements.
Map source = (Map) value; Map<?, ?> source = (Map) value;
Map target = createMap(this.mapType, source.size()); Map target = createMap(this.mapType, source.size());
for (Iterator it = source.entrySet().iterator(); it.hasNext();) { for (Map.Entry entry : source.entrySet()) {
Map.Entry entry = (Map.Entry) it.next();
target.put(convertKey(entry.getKey()), convertValue(entry.getValue())); target.put(convertKey(entry.getKey()), convertValue(entry.getValue()));
} }
super.setValue(target); super.setValue(target);

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -65,7 +65,7 @@ public class TimerManagerFactoryBean extends JndiLocatorSupport
private ScheduledTimerListener[] scheduledTimerListeners; private ScheduledTimerListener[] scheduledTimerListeners;
private final List timers = new LinkedList(); private final List<Timer> timers = new LinkedList<Timer>();
/** /**
@ -145,20 +145,20 @@ public class TimerManagerFactoryBean extends JndiLocatorSupport
} }
if (this.scheduledTimerListeners != null) { if (this.scheduledTimerListeners != null) {
for (int i = 0; i < this.scheduledTimerListeners.length; i++) { for (ScheduledTimerListener scheduledTask : this.scheduledTimerListeners) {
ScheduledTimerListener scheduledTask = this.scheduledTimerListeners[i];
Timer timer = null; Timer timer = null;
if (scheduledTask.isOneTimeTask()) { if (scheduledTask.isOneTimeTask()) {
timer = this.timerManager.schedule(scheduledTask.getTimerListener(), scheduledTask.getDelay()); timer = this.timerManager.schedule(scheduledTask.getTimerListener(), scheduledTask.getDelay());
} }
else { else {
if (scheduledTask.isFixedRate()) { if (scheduledTask.isFixedRate()) {
timer = this.timerManager.scheduleAtFixedRate( timer = this.timerManager
scheduledTask.getTimerListener(), scheduledTask.getDelay(), scheduledTask.getPeriod()); .scheduleAtFixedRate(scheduledTask.getTimerListener(), scheduledTask.getDelay(),
scheduledTask.getPeriod());
} }
else { else {
timer = this.timerManager.schedule( timer = this.timerManager.schedule(scheduledTask.getTimerListener(), scheduledTask.getDelay(),
scheduledTask.getTimerListener(), scheduledTask.getDelay(), scheduledTask.getPeriod()); scheduledTask.getPeriod());
} }
} }
this.timers.add(timer); this.timers.add(timer);
@ -231,8 +231,7 @@ public class TimerManagerFactoryBean extends JndiLocatorSupport
*/ */
public void destroy() { public void destroy() {
// Cancel all registered timers. // Cancel all registered timers.
for (Iterator it = this.timers.iterator(); it.hasNext();) { for (Timer timer : this.timers) {
Timer timer = (Timer) it.next();
try { try {
timer.cancel(); timer.cancel();
} }

View File

@ -18,7 +18,6 @@ package org.springframework.scheduling.quartz;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -63,11 +62,11 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
private String[] jobSchedulingDataLocations; private String[] jobSchedulingDataLocations;
private List jobDetails; private List<JobDetail> jobDetails;
private Map calendars; private Map<String, Calendar> calendars;
private List triggers; private List<Trigger> triggers;
private SchedulerListener[] schedulerListeners; private SchedulerListener[] schedulerListeners;
@ -132,7 +131,7 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
public void setJobDetails(JobDetail[] jobDetails) { public void setJobDetails(JobDetail[] jobDetails) {
// Use modifiable ArrayList here, to allow for further adding of // Use modifiable ArrayList here, to allow for further adding of
// JobDetail objects during autodetection of JobDetailAwareTriggers. // JobDetail objects during autodetection of JobDetailAwareTriggers.
this.jobDetails = new ArrayList(Arrays.asList(jobDetails)); this.jobDetails = new ArrayList<JobDetail>(Arrays.asList(jobDetails));
} }
/** /**
@ -143,7 +142,7 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
* @see org.quartz.Calendar * @see org.quartz.Calendar
* @see org.quartz.Trigger#setCalendarName * @see org.quartz.Trigger#setCalendarName
*/ */
public void setCalendars(Map calendars) { public void setCalendars(Map<String, Calendar> calendars) {
this.calendars = calendars; this.calendars = calendars;
} }
@ -242,37 +241,33 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader); ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader);
clh.initialize(); clh.initialize();
JobSchedulingDataProcessor dataProcessor = new JobSchedulingDataProcessor(clh, true, true); JobSchedulingDataProcessor dataProcessor = new JobSchedulingDataProcessor(clh, true, true);
for (int i = 0; i < this.jobSchedulingDataLocations.length; i++) { for (String location : this.jobSchedulingDataLocations) {
dataProcessor.processFileAndScheduleJobs( dataProcessor.processFileAndScheduleJobs(location, getScheduler(), this.overwriteExistingJobs);
this.jobSchedulingDataLocations[i], getScheduler(), this.overwriteExistingJobs);
} }
} }
// Register JobDetails. // Register JobDetails.
if (this.jobDetails != null) { if (this.jobDetails != null) {
for (Iterator it = this.jobDetails.iterator(); it.hasNext();) { for (JobDetail jobDetail : this.jobDetails) {
JobDetail jobDetail = (JobDetail) it.next();
addJobToScheduler(jobDetail); addJobToScheduler(jobDetail);
} }
} }
else { else {
// Create empty list for easier checks when registering triggers. // Create empty list for easier checks when registering triggers.
this.jobDetails = new LinkedList(); this.jobDetails = new LinkedList<JobDetail>();
} }
// Register Calendars. // Register Calendars.
if (this.calendars != null) { if (this.calendars != null) {
for (Iterator it = this.calendars.keySet().iterator(); it.hasNext();) { for (String calendarName : this.calendars.keySet()) {
String calendarName = (String) it.next(); Calendar calendar = this.calendars.get(calendarName);
Calendar calendar = (Calendar) this.calendars.get(calendarName);
getScheduler().addCalendar(calendarName, calendar, true, true); getScheduler().addCalendar(calendarName, calendar, true, true);
} }
} }
// Register Triggers. // Register Triggers.
if (this.triggers != null) { if (this.triggers != null) {
for (Iterator it = this.triggers.iterator(); it.hasNext();) { for (Trigger trigger : this.triggers) {
Trigger trigger = (Trigger) it.next();
addTriggerToScheduler(trigger); addTriggerToScheduler(trigger);
} }
} }
@ -292,8 +287,7 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
throw (SchedulerException) ex; throw (SchedulerException) ex;
} }
if (ex instanceof Exception) { if (ex instanceof Exception) {
throw new SchedulerException( throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage(), ex);
"Registration of jobs and triggers failed: " + ex.getMessage(), (Exception) ex);
} }
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage()); throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage());
} }
@ -371,28 +365,28 @@ public abstract class SchedulerAccessor implements ResourceLoaderAware {
*/ */
protected void registerListeners() throws SchedulerException { protected void registerListeners() throws SchedulerException {
if (this.schedulerListeners != null) { if (this.schedulerListeners != null) {
for (int i = 0; i < this.schedulerListeners.length; i++) { for (SchedulerListener listener : this.schedulerListeners) {
getScheduler().addSchedulerListener(this.schedulerListeners[i]); getScheduler().addSchedulerListener(listener);
} }
} }
if (this.globalJobListeners != null) { if (this.globalJobListeners != null) {
for (int i = 0; i < this.globalJobListeners.length; i++) { for (JobListener listener : this.globalJobListeners) {
getScheduler().addGlobalJobListener(this.globalJobListeners[i]); getScheduler().addGlobalJobListener(listener);
} }
} }
if (this.jobListeners != null) { if (this.jobListeners != null) {
for (int i = 0; i < this.jobListeners.length; i++) { for (JobListener listener : this.jobListeners) {
getScheduler().addJobListener(this.jobListeners[i]); getScheduler().addJobListener(listener);
} }
} }
if (this.globalTriggerListeners != null) { if (this.globalTriggerListeners != null) {
for (int i = 0; i < this.globalTriggerListeners.length; i++) { for (TriggerListener listener : this.globalTriggerListeners) {
getScheduler().addGlobalTriggerListener(this.globalTriggerListeners[i]); getScheduler().addGlobalTriggerListener(listener);
} }
} }
if (this.triggerListeners != null) { if (this.triggerListeners != null) {
for (int i = 0; i < this.triggerListeners.length; i++) { for (TriggerListener listener : this.triggerListeners) {
getScheduler().addTriggerListener(this.triggerListeners[i]); getScheduler().addTriggerListener(listener);
} }
} }
} }

View File

@ -17,7 +17,6 @@
package org.springframework.context.annotation; package org.springframework.context.annotation;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -134,8 +133,7 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
Object source = readerContext.extractSource(element); Object source = readerContext.extractSource(element);
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source); CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);
for (Iterator it = beanDefinitions.iterator(); it.hasNext();) { for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
BeanDefinitionHolder beanDefHolder = (BeanDefinitionHolder) it.next();
compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder)); compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
} }

View File

@ -108,7 +108,7 @@ public abstract class AbstractApplicationEventMulticaster implements Application
* @return a Collection of ApplicationListeners * @return a Collection of ApplicationListeners
* @see org.springframework.context.ApplicationListener * @see org.springframework.context.ApplicationListener
*/ */
protected Collection getApplicationListeners() { protected Collection<ApplicationListener> getApplicationListeners() {
return this.applicationListeners; return this.applicationListeners;
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,8 +16,6 @@
package org.springframework.context.event; package org.springframework.context.event;
import java.util.Iterator;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.core.task.SyncTaskExecutor; import org.springframework.core.task.SyncTaskExecutor;
@ -71,8 +69,7 @@ public class SimpleApplicationEventMulticaster extends AbstractApplicationEventM
public void multicastEvent(final ApplicationEvent event) { public void multicastEvent(final ApplicationEvent event) {
for (Iterator it = getApplicationListeners().iterator(); it.hasNext();) { for (final ApplicationListener listener : getApplicationListeners()) {
final ApplicationListener listener = (ApplicationListener) it.next();
getTaskExecutor().execute(new Runnable() { getTaskExecutor().execute(new Runnable() {
public void run() { public void run() {
listener.onApplicationEvent(event); listener.onApplicationEvent(event);

View File

@ -22,7 +22,6 @@ import java.io.InputStreamReader;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -112,10 +111,11 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
private ResourceLoader resourceLoader = new DefaultResourceLoader(); private ResourceLoader resourceLoader = new DefaultResourceLoader();
/** Cache to hold filename lists per Locale */ /** Cache to hold filename lists per Locale */
private final Map cachedFilenames = new HashMap(); private final Map<String, Map<Locale, List<String>>> cachedFilenames =
new HashMap<String, Map<Locale, List<String>>>();
/** Cache to hold already loaded properties per filename */ /** Cache to hold already loaded properties per filename */
private final Map cachedProperties = new HashMap(); private final Map<String, PropertiesHolder> cachedProperties = new HashMap<String, PropertiesHolder>();
/** Cache to hold merged loaded properties per basename */ /** Cache to hold merged loaded properties per basename */
private final Map cachedMergedProperties = new HashMap(); private final Map cachedMergedProperties = new HashMap();
@ -271,10 +271,9 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
} }
} }
else { else {
for (int i = 0; i < this.basenames.length; i++) { for (String basename : this.basenames) {
List filenames = calculateAllFilenames(this.basenames[i], locale); List<String> filenames = calculateAllFilenames(basename, locale);
for (int j = 0; j < filenames.size(); j++) { for (String filename : filenames) {
String filename = (String) filenames.get(j);
PropertiesHolder propHolder = getProperties(filename); PropertiesHolder propHolder = getProperties(filename);
String result = propHolder.getProperty(code); String result = propHolder.getProperty(code);
if (result != null) { if (result != null) {
@ -300,8 +299,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
} }
} }
else { else {
for (int i = 0; i < this.basenames.length; i++) { for (String basename : this.basenames) {
List filenames = calculateAllFilenames(this.basenames[i], locale); List filenames = calculateAllFilenames(basename, locale);
for (int j = 0; j < filenames.size(); j++) { for (int j = 0; j < filenames.size(); j++) {
String filename = (String) filenames.get(j); String filename = (String) filenames.get(j);
PropertiesHolder propHolder = getProperties(filename); PropertiesHolder propHolder = getProperties(filename);
@ -357,21 +356,20 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
* @see #setFallbackToSystemLocale * @see #setFallbackToSystemLocale
* @see #calculateFilenamesForLocale * @see #calculateFilenamesForLocale
*/ */
protected List calculateAllFilenames(String basename, Locale locale) { protected List<String> calculateAllFilenames(String basename, Locale locale) {
synchronized (this.cachedFilenames) { synchronized (this.cachedFilenames) {
Map localeMap = (Map) this.cachedFilenames.get(basename); Map<Locale, List<String>> localeMap = this.cachedFilenames.get(basename);
if (localeMap != null) { if (localeMap != null) {
List filenames = (List) localeMap.get(locale); List<String> filenames = localeMap.get(locale);
if (filenames != null) { if (filenames != null) {
return filenames; return filenames;
} }
} }
List filenames = new ArrayList(7); List<String> filenames = new ArrayList<String>(7);
filenames.addAll(calculateFilenamesForLocale(basename, locale)); filenames.addAll(calculateFilenamesForLocale(basename, locale));
if (this.fallbackToSystemLocale && !locale.equals(Locale.getDefault())) { if (this.fallbackToSystemLocale && !locale.equals(Locale.getDefault())) {
List fallbackFilenames = calculateFilenamesForLocale(basename, Locale.getDefault()); List<String> fallbackFilenames = calculateFilenamesForLocale(basename, Locale.getDefault());
for (Iterator it = fallbackFilenames.iterator(); it.hasNext();) { for (String fallbackFilename : fallbackFilenames) {
String fallbackFilename = (String) it.next();
if (!filenames.contains(fallbackFilename)) { if (!filenames.contains(fallbackFilename)) {
// Entry for fallback locale that isn't already in filenames list. // Entry for fallback locale that isn't already in filenames list.
filenames.add(fallbackFilename); filenames.add(fallbackFilename);
@ -383,7 +381,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
localeMap.put(locale, filenames); localeMap.put(locale, filenames);
} }
else { else {
localeMap = new HashMap(); localeMap = new HashMap<Locale, List<String>>();
localeMap.put(locale, filenames); localeMap.put(locale, filenames);
this.cachedFilenames.put(basename, localeMap); this.cachedFilenames.put(basename, localeMap);
} }
@ -400,8 +398,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
* @param locale the locale * @param locale the locale
* @return the List of filenames to check * @return the List of filenames to check
*/ */
protected List calculateFilenamesForLocale(String basename, Locale locale) { protected List<String> calculateFilenamesForLocale(String basename, Locale locale) {
List result = new ArrayList(3); List<String> result = new ArrayList<String>(3);
String language = locale.getLanguage(); String language = locale.getLanguage();
String country = locale.getCountry(); String country = locale.getCountry();
String variant = locale.getVariant(); String variant = locale.getVariant();
@ -434,7 +432,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
*/ */
protected PropertiesHolder getProperties(String filename) { protected PropertiesHolder getProperties(String filename) {
synchronized (this.cachedProperties) { synchronized (this.cachedProperties) {
PropertiesHolder propHolder = (PropertiesHolder) this.cachedProperties.get(filename); PropertiesHolder propHolder = this.cachedProperties.get(filename);
if (propHolder != null && if (propHolder != null &&
(propHolder.getRefreshTimestamp() < 0 || (propHolder.getRefreshTimestamp() < 0 ||
propHolder.getRefreshTimestamp() > System.currentTimeMillis() - this.cacheMillis)) { propHolder.getRefreshTimestamp() > System.currentTimeMillis() - this.cacheMillis)) {
@ -603,7 +601,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
private long refreshTimestamp = -1; private long refreshTimestamp = -1;
/** Cache to hold already generated MessageFormats per message code */ /** Cache to hold already generated MessageFormats per message code */
private final Map cachedMessageFormats = new HashMap(); private final Map<String, Map<Locale, MessageFormat>> cachedMessageFormats =
new HashMap<String, Map<Locale, MessageFormat>>();
public PropertiesHolder(Properties properties, long fileTimestamp) { public PropertiesHolder(Properties properties, long fileTimestamp) {
this.properties = properties; this.properties = properties;
@ -641,9 +640,9 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
return null; return null;
} }
synchronized (this.cachedMessageFormats) { synchronized (this.cachedMessageFormats) {
Map localeMap = (Map) this.cachedMessageFormats.get(code); Map<Locale, MessageFormat> localeMap = this.cachedMessageFormats.get(code);
if (localeMap != null) { if (localeMap != null) {
MessageFormat result = (MessageFormat) localeMap.get(locale); MessageFormat result = localeMap.get(locale);
if (result != null) { if (result != null) {
return result; return result;
} }
@ -651,7 +650,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
String msg = this.properties.getProperty(code); String msg = this.properties.getProperty(code);
if (msg != null) { if (msg != null) {
if (localeMap == null) { if (localeMap == null) {
localeMap = new HashMap(); localeMap = new HashMap<Locale, MessageFormat>();
this.cachedMessageFormats.put(code, localeMap); this.cachedMessageFormats.put(code, localeMap);
} }
MessageFormat result = createMessageFormat(msg, locale); MessageFormat result = createMessageFormat(msg, locale);

View File

@ -18,7 +18,6 @@ package org.springframework.context.support;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -37,12 +36,12 @@ import org.springframework.util.Assert;
public class StaticMessageSource extends AbstractMessageSource { public class StaticMessageSource extends AbstractMessageSource {
/** Map from 'code + locale' keys to message Strings */ /** Map from 'code + locale' keys to message Strings */
private final Map messages = new HashMap(); private final Map<String, MessageFormat> messages = new HashMap<String, MessageFormat>();
@Override @Override
protected MessageFormat resolveCode(String code, Locale locale) { protected MessageFormat resolveCode(String code, Locale locale) {
return (MessageFormat) this.messages.get(code + "_" + locale.toString()); return this.messages.get(code + "_" + locale.toString());
} }
/** /**
@ -65,13 +64,12 @@ public class StaticMessageSource extends AbstractMessageSource {
* Associate the given message values with the given keys as codes. * Associate the given message values with the given keys as codes.
* @param messages the messages to register, with messages codes * @param messages the messages to register, with messages codes
* as keys and message texts as values * as keys and message texts as values
* @param locale the locale that the messages should be found within * @param locale the locale that the messages should be found within
*/ */
public void addMessages(Map messages, Locale locale) { public void addMessages(Map<String, String> messages, Locale locale) {
Assert.notNull(messages, "Messages Map must not be null"); Assert.notNull(messages, "Messages Map must not be null");
for (Iterator it = messages.entrySet().iterator(); it.hasNext();) { for (Map.Entry<String, String> entry : messages.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); addMessage(entry.getKey(), locale, entry.getValue());
addMessage(entry.getKey().toString(), locale, entry.getValue().toString());
} }
} }

View File

@ -16,10 +16,8 @@
package org.springframework.jmx.support; package org.springframework.jmx.support;
import java.util.Iterator;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException; import javax.management.InstanceNotFoundException;
import javax.management.JMException; import javax.management.JMException;
@ -106,7 +104,7 @@ public class MBeanRegistrationSupport {
/** /**
* The beans that have been registered by this exporter. * The beans that have been registered by this exporter.
*/ */
protected final Set registeredBeans = new LinkedHashSet(); protected final Set<ObjectName> registeredBeans = new LinkedHashSet<ObjectName>();
/** /**
* The action take when registering an MBean and finding that it already exists. * The action take when registering an MBean and finding that it already exists.
@ -207,8 +205,8 @@ public class MBeanRegistrationSupport {
* Unregisters all beans that have been registered by an instance of this class. * Unregisters all beans that have been registered by an instance of this class.
*/ */
protected void unregisterBeans() { protected void unregisterBeans() {
for (Iterator it = this.registeredBeans.iterator(); it.hasNext();) { for (ObjectName objectName : this.registeredBeans) {
doUnregister((ObjectName) it.next()); doUnregister(objectName);
} }
this.registeredBeans.clear(); this.registeredBeans.clear();
} }
@ -242,7 +240,7 @@ public class MBeanRegistrationSupport {
* Return the {@link ObjectName ObjectNames} of all registered beans. * Return the {@link ObjectName ObjectNames} of all registered beans.
*/ */
protected final ObjectName[] getRegisteredObjectNames() { protected final ObjectName[] getRegisteredObjectNames() {
return (ObjectName[]) this.registeredBeans.toArray(new ObjectName[this.registeredBeans.size()]); return this.registeredBeans.toArray(new ObjectName[this.registeredBeans.size()]);
} }

View File

@ -168,7 +168,7 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
final DefaultListableBeanFactory scriptBeanFactory = new DefaultListableBeanFactory(); final DefaultListableBeanFactory scriptBeanFactory = new DefaultListableBeanFactory();
/** Map from bean name String to ScriptSource object */ /** Map from bean name String to ScriptSource object */
private final Map scriptSourceCache = new HashMap(); private final Map<String, ScriptSource> scriptSourceCache = new HashMap<String, ScriptSource>();
/** /**
@ -202,9 +202,8 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
// Filter out BeanPostProcessors that are part of the AOP infrastructure, // Filter out BeanPostProcessors that are part of the AOP infrastructure,
// since those are only meant to apply to beans defined in the original factory. // since those are only meant to apply to beans defined in the original factory.
for (Iterator it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) { for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor postProcessor = (BeanPostProcessor) it.next(); if (it.next() instanceof AopInfrastructureBean) {
if (postProcessor instanceof AopInfrastructureBean) {
it.remove(); it.remove();
} }
} }
@ -233,8 +232,7 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName; String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName); prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);
ScriptFactory scriptFactory = ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
(ScriptFactory) this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
ScriptSource scriptSource = ScriptSource scriptSource =
getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator()); getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
Class[] interfaces = scriptFactory.getScriptInterfaces(); Class[] interfaces = scriptFactory.getScriptInterfaces();
@ -284,8 +282,7 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName; String scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName); prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);
ScriptFactory scriptFactory = ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
(ScriptFactory) this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
ScriptSource scriptSource = ScriptSource scriptSource =
getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator()); getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
boolean isFactoryBean = false; boolean isFactoryBean = false;
@ -334,8 +331,7 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
this.scriptBeanFactory.registerBeanDefinition( this.scriptBeanFactory.registerBeanDefinition(
scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd)); scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
ScriptFactory scriptFactory = ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
(ScriptFactory) this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
ScriptSource scriptSource = ScriptSource scriptSource =
getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator()); getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
Class[] interfaces = scriptFactory.getScriptInterfaces(); Class[] interfaces = scriptFactory.getScriptInterfaces();
@ -410,7 +406,7 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
*/ */
protected ScriptSource getScriptSource(String beanName, String scriptSourceLocator) { protected ScriptSource getScriptSource(String beanName, String scriptSourceLocator) {
synchronized (this.scriptSourceCache) { synchronized (this.scriptSourceCache) {
ScriptSource scriptSource = (ScriptSource) this.scriptSourceCache.get(beanName); ScriptSource scriptSource = this.scriptSourceCache.get(beanName);
if (scriptSource == null) { if (scriptSource == null) {
scriptSource = convertToScriptSource(beanName, scriptSourceLocator, this.resourceLoader); scriptSource = convertToScriptSource(beanName, scriptSourceLocator, this.resourceLoader);
this.scriptSourceCache.put(beanName, scriptSource); this.scriptSourceCache.put(beanName, scriptSource);
@ -457,8 +453,8 @@ public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProces
protected Class createConfigInterface(BeanDefinition bd, Class[] interfaces) { protected Class createConfigInterface(BeanDefinition bd, Class[] interfaces) {
InterfaceMaker maker = new InterfaceMaker(); InterfaceMaker maker = new InterfaceMaker();
PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues(); PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues();
for (int i = 0; i < pvs.length; i++) { for (PropertyValue pv : pvs) {
String propertyName = pvs[i].getName(); String propertyName = pv.getName();
Class propertyType = BeanUtils.findPropertyType(propertyName, interfaces); Class propertyType = BeanUtils.findPropertyType(propertyName, interfaces);
String setterName = "set" + StringUtils.capitalize(propertyName); String setterName = "set" + StringUtils.capitalize(propertyName);
Signature signature = new Signature(setterName, Type.VOID_TYPE, new Type[] {Type.getType(propertyType)}); Signature signature = new Signature(setterName, Type.VOID_TYPE, new Type[] {Type.getType(propertyType)});

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.ui.context.support; package org.springframework.ui.context.support;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -51,7 +50,7 @@ public class ResourceBundleThemeSource implements HierarchicalThemeSource {
private String basenamePrefix = ""; private String basenamePrefix = "";
/** Map from theme name to Theme instance */ /** Map from theme name to Theme instance */
private final Map themeCache = new HashMap(); private final Map<String, Theme> themeCache = new HashMap<String, Theme>();
public void setParentThemeSource(ThemeSource parent) { public void setParentThemeSource(ThemeSource parent) {
@ -60,9 +59,8 @@ public class ResourceBundleThemeSource implements HierarchicalThemeSource {
// Update existing Theme objects. // Update existing Theme objects.
// Usually there shouldn't be any at the time of this call. // Usually there shouldn't be any at the time of this call.
synchronized (this.themeCache) { synchronized (this.themeCache) {
Iterator it = this.themeCache.values().iterator(); for (Theme theme : this.themeCache.values()) {
while (it.hasNext()) { initParent(theme);
initParent((Theme) it.next());
} }
} }
} }
@ -100,7 +98,7 @@ public class ResourceBundleThemeSource implements HierarchicalThemeSource {
return null; return null;
} }
synchronized (this.themeCache) { synchronized (this.themeCache) {
Theme theme = (Theme) this.themeCache.get(themeName); Theme theme = this.themeCache.get(themeName);
if (theme == null) { if (theme == null) {
String basename = this.basenamePrefix + themeName; String basename = this.basenamePrefix + themeName;
MessageSource messageSource = createMessageSource(basename); MessageSource messageSource = createMessageSource(basename);

View File

@ -21,7 +21,6 @@ import java.io.Serializable;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -46,9 +45,9 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
private MessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver(); private MessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver();
private final List errors = new LinkedList(); private final List<ObjectError> errors = new LinkedList<ObjectError>();
private final Set suppressedFields = new HashSet(); private final Set<String> suppressedFields = new HashSet<String>();
/** /**
@ -146,16 +145,15 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
} }
@Override @Override
public List getAllErrors() { public List<ObjectError> getAllErrors() {
return Collections.unmodifiableList(this.errors); return Collections.unmodifiableList(this.errors);
} }
public List getGlobalErrors() { public List<ObjectError> getGlobalErrors() {
List result = new LinkedList(); List<ObjectError> result = new LinkedList<ObjectError>();
for (Iterator it = this.errors.iterator(); it.hasNext();) { for (ObjectError objectError : this.errors) {
Object error = it.next(); if (!(objectError instanceof FieldError)) {
if (!(error instanceof FieldError)) { result.add(objectError);
result.add(error);
} }
} }
return Collections.unmodifiableList(result); return Collections.unmodifiableList(result);
@ -163,8 +161,7 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
@Override @Override
public ObjectError getGlobalError() { public ObjectError getGlobalError() {
for (Iterator it = this.errors.iterator(); it.hasNext();) { for (ObjectError objectError : this.errors) {
ObjectError objectError = (ObjectError) it.next();
if (!(objectError instanceof FieldError)) { if (!(objectError instanceof FieldError)) {
return objectError; return objectError;
} }
@ -172,12 +169,11 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
return null; return null;
} }
public List getFieldErrors() { public List<FieldError> getFieldErrors() {
List result = new LinkedList(); List<FieldError> result = new LinkedList<FieldError>();
for (Iterator it = this.errors.iterator(); it.hasNext();) { for (ObjectError objectError : this.errors) {
Object error = it.next(); if (objectError instanceof FieldError) {
if (error instanceof FieldError) { result.add((FieldError) objectError);
result.add(error);
} }
} }
return Collections.unmodifiableList(result); return Collections.unmodifiableList(result);
@ -185,23 +181,21 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
@Override @Override
public FieldError getFieldError() { public FieldError getFieldError() {
for (Iterator it = this.errors.iterator(); it.hasNext();) { for (ObjectError objectError : this.errors) {
Object error = it.next(); if (objectError instanceof FieldError) {
if (error instanceof FieldError) { return (FieldError) objectError;
return (FieldError) error;
} }
} }
return null; return null;
} }
@Override @Override
public List getFieldErrors(String field) { public List<FieldError> getFieldErrors(String field) {
List result = new LinkedList(); List<FieldError> result = new LinkedList<FieldError>();
String fixedField = fixedField(field); String fixedField = fixedField(field);
for (Iterator it = this.errors.iterator(); it.hasNext();) { for (ObjectError objectError : this.errors) {
Object error = it.next(); if (objectError instanceof FieldError && isMatchingFieldError(fixedField, (FieldError) objectError)) {
if (error instanceof FieldError && isMatchingFieldError(fixedField, (FieldError) error)) { result.add((FieldError) objectError);
result.add(error);
} }
} }
return Collections.unmodifiableList(result); return Collections.unmodifiableList(result);
@ -210,12 +204,11 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
@Override @Override
public FieldError getFieldError(String field) { public FieldError getFieldError(String field) {
String fixedField = fixedField(field); String fixedField = fixedField(field);
for (Iterator it = this.errors.iterator(); it.hasNext();) { for (ObjectError objectError : this.errors) {
Object error = it.next(); if (objectError instanceof FieldError) {
if (error instanceof FieldError) { FieldError fieldError = (FieldError) objectError;
FieldError fe = (FieldError) error; if (isMatchingFieldError(fixedField, fieldError)) {
if (isMatchingFieldError(fixedField, fe)) { return fieldError;
return fe;
} }
} }
} }
@ -223,17 +216,12 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
} }
public Object getFieldValue(String field) { public Object getFieldValue(String field) {
FieldError fe = getFieldError(field); FieldError fieldError = getFieldError(field);
// Use rejected value in case of error, current bean property value else. // Use rejected value in case of error, current bean property value else.
Object value = null; Object value = (fieldError != null ? fieldError.getRejectedValue() :
if (fe != null) { getActualFieldValue(fixedField(field)));
value = fe.getRejectedValue();
}
else {
value = getActualFieldValue(fixedField(field));
}
// Apply formatting, but not on binding failures like type mismatches. // Apply formatting, but not on binding failures like type mismatches.
if (fe == null || !fe.isBindingFailure()) { if (fieldError == null || !fieldError.isBindingFailure()) {
value = formatFieldValue(field, value); value = formatFieldValue(field, value);
} }
return value; return value;
@ -277,8 +265,8 @@ public abstract class AbstractBindingResult extends AbstractErrors implements Bi
* @see org.springframework.web.servlet.tags.BindTag * @see org.springframework.web.servlet.tags.BindTag
* @see org.springframework.web.servlet.mvc.SimpleFormController * @see org.springframework.web.servlet.mvc.SimpleFormController
*/ */
public Map getModel() { public Map<String, Object> getModel() {
Map model = new HashMap(2); Map<String, Object> model = new HashMap<String, Object>(2);
// Errors instance, even if no errors. // Errors instance, even if no errors.
model.put(MODEL_KEY_PREFIX + getObjectName(), this); model.put(MODEL_KEY_PREFIX + getObjectName(), this);
// Mapping from name to target object. // Mapping from name to target object.

View File

@ -75,7 +75,7 @@ public interface BindingResult extends Errors {
* @see org.springframework.web.servlet.tags.BindTag * @see org.springframework.web.servlet.tags.BindTag
* @see org.springframework.web.servlet.mvc.SimpleFormController * @see org.springframework.web.servlet.mvc.SimpleFormController
*/ */
Map getModel(); Map<String, Object> getModel();
/** /**
* Extract the raw field value for the given field. * Extract the raw field value for the given field.

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.validation;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -121,19 +120,17 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial
* @return the list of codes * @return the list of codes
*/ */
public String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) { public String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) {
List codeList = new ArrayList(); List<String> codeList = new ArrayList<String>();
List fieldList = new ArrayList(); List<String> fieldList = new ArrayList<String>();
buildFieldList(field, fieldList); buildFieldList(field, fieldList);
for (Iterator it = fieldList.iterator(); it.hasNext();) { for (String fieldInList : fieldList) {
String fieldInList = (String) it.next();
codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + objectName + CODE_SEPARATOR + fieldInList)); codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + objectName + CODE_SEPARATOR + fieldInList));
} }
int dotIndex = field.lastIndexOf('.'); int dotIndex = field.lastIndexOf('.');
if (dotIndex != -1) { if (dotIndex != -1) {
buildFieldList(field.substring(dotIndex + 1), fieldList); buildFieldList(field.substring(dotIndex + 1), fieldList);
} }
for (Iterator it = fieldList.iterator(); it.hasNext();) { for (String fieldInList : fieldList) {
String fieldInList = (String) it.next();
codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + fieldInList)); codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + fieldInList));
} }
if (fieldType != null) { if (fieldType != null) {
@ -147,7 +144,7 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial
* Add both keyed and non-keyed entries for the supplied <code>field</code> * Add both keyed and non-keyed entries for the supplied <code>field</code>
* to the supplied field list. * to the supplied field list.
*/ */
protected void buildFieldList(String field, List fieldList) { protected void buildFieldList(String field, List<String> fieldList) {
fieldList.add(field); fieldList.add(field);
String plainField = field; String plainField = field;
int keyIndex = plainField.lastIndexOf('['); int keyIndex = plainField.lastIndexOf('[');

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -194,7 +194,7 @@ public interface Errors {
* Get all errors, both global and field ones. * Get all errors, both global and field ones.
* @return List of {@link ObjectError} instances * @return List of {@link ObjectError} instances
*/ */
List getAllErrors(); List<ObjectError> getAllErrors();
/** /**
* Are there any global errors? * Are there any global errors?
@ -214,7 +214,7 @@ public interface Errors {
* Get all global errors. * Get all global errors.
* @return List of ObjectError instances * @return List of ObjectError instances
*/ */
List getGlobalErrors(); List<ObjectError> getGlobalErrors();
/** /**
* Get the <i>first</i> global error, if any. * Get the <i>first</i> global error, if any.
@ -240,7 +240,7 @@ public interface Errors {
* Get all errors associated with a field. * Get all errors associated with a field.
* @return a List of {@link FieldError} instances * @return a List of {@link FieldError} instances
*/ */
List getFieldErrors(); List<FieldError> getFieldErrors();
/** /**
* Get the <i>first</i> error associated with a field, if any. * Get the <i>first</i> error associated with a field, if any.
@ -269,7 +269,7 @@ public interface Errors {
* @param field the field name * @param field the field name
* @return a List of {@link FieldError} instances * @return a List of {@link FieldError} instances
*/ */
List getFieldErrors(String field); List<FieldError> getFieldErrors(String field);
/** /**
* Get the first error associated with the given field, if any. * Get the first error associated with the given field, if any.

View File

@ -19,7 +19,6 @@ package org.springframework.core;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -50,7 +49,7 @@ public class Constants {
private final String className; private final String className;
/** Map from String field name to object value */ /** Map from String field name to object value */
private final Map fieldCache = new HashMap(); private final Map<String, Object> fieldCache = new HashMap<String, Object>();
/** /**
@ -63,8 +62,7 @@ public class Constants {
Assert.notNull(clazz); Assert.notNull(clazz);
this.className = clazz.getName(); this.className = clazz.getName();
Field[] fields = clazz.getFields(); Field[] fields = clazz.getFields();
for (int i = 0; i < fields.length; i++) { for (Field field : fields) {
Field field = fields[i];
if (ReflectionUtils.isPublicStaticFinal(field)) { if (ReflectionUtils.isPublicStaticFinal(field)) {
String name = field.getName(); String name = field.getName();
try { try {
@ -97,7 +95,7 @@ public class Constants {
* Exposes the field cache to subclasses: * Exposes the field cache to subclasses:
* a Map from String field name to object value. * a Map from String field name to object value.
*/ */
protected final Map getFieldCache() { protected final Map<String, Object> getFieldCache() {
return this.fieldCache; return this.fieldCache;
} }
@ -159,11 +157,10 @@ public class Constants {
* @param namePrefix prefix of the constant names to search (may be <code>null</code>) * @param namePrefix prefix of the constant names to search (may be <code>null</code>)
* @return the set of constant names * @return the set of constant names
*/ */
public Set getNames(String namePrefix) { public Set<String> getNames(String namePrefix) {
String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : ""); String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : "");
Set names = new HashSet(); Set<String> names = new HashSet<String>();
for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { for (String code : this.fieldCache.keySet()) {
String code = (String) it.next();
if (code.startsWith(prefixToUse)) { if (code.startsWith(prefixToUse)) {
names.add(code); names.add(code);
} }
@ -178,7 +175,7 @@ public class Constants {
* @return the set of values * @return the set of values
* @see #propertyToConstantNamePrefix * @see #propertyToConstantNamePrefix
*/ */
public Set getNamesForProperty(String propertyName) { public Set<String> getNamesForProperty(String propertyName) {
return getNames(propertyToConstantNamePrefix(propertyName)); return getNames(propertyToConstantNamePrefix(propertyName));
} }
@ -194,9 +191,8 @@ public class Constants {
*/ */
public Set getNamesForSuffix(String nameSuffix) { public Set getNamesForSuffix(String nameSuffix) {
String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : ""); String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : "");
Set names = new HashSet(); Set<String> names = new HashSet<String>();
for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { for (String code : this.fieldCache.keySet()) {
String code = (String) it.next();
if (code.endsWith(suffixToUse)) { if (code.endsWith(suffixToUse)) {
names.add(code); names.add(code);
} }
@ -215,11 +211,10 @@ public class Constants {
* @param namePrefix prefix of the constant names to search (may be <code>null</code>) * @param namePrefix prefix of the constant names to search (may be <code>null</code>)
* @return the set of values * @return the set of values
*/ */
public Set getValues(String namePrefix) { public Set<Object> getValues(String namePrefix) {
String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : ""); String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : "");
Set values = new HashSet(); Set<Object> values = new HashSet<Object>();
for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { for (String code : this.fieldCache.keySet()) {
String code = (String) it.next();
if (code.startsWith(prefixToUse)) { if (code.startsWith(prefixToUse)) {
values.add(this.fieldCache.get(code)); values.add(this.fieldCache.get(code));
} }
@ -234,7 +229,7 @@ public class Constants {
* @return the set of values * @return the set of values
* @see #propertyToConstantNamePrefix * @see #propertyToConstantNamePrefix
*/ */
public Set getValuesForProperty(String propertyName) { public Set<Object> getValuesForProperty(String propertyName) {
return getValues(propertyToConstantNamePrefix(propertyName)); return getValues(propertyToConstantNamePrefix(propertyName));
} }
@ -248,11 +243,10 @@ public class Constants {
* @param nameSuffix suffix of the constant names to search (may be <code>null</code>) * @param nameSuffix suffix of the constant names to search (may be <code>null</code>)
* @return the set of values * @return the set of values
*/ */
public Set getValuesForSuffix(String nameSuffix) { public Set<Object> getValuesForSuffix(String nameSuffix) {
String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : ""); String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : "");
Set values = new HashSet(); Set<Object> values = new HashSet<Object>();
for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { for (String code : this.fieldCache.keySet()) {
String code = (String) it.next();
if (code.endsWith(suffixToUse)) { if (code.endsWith(suffixToUse)) {
values.add(this.fieldCache.get(code)); values.add(this.fieldCache.get(code));
} }
@ -271,11 +265,9 @@ public class Constants {
*/ */
public String toCode(Object value, String namePrefix) throws ConstantException { public String toCode(Object value, String namePrefix) throws ConstantException {
String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : null); String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : null);
for (Iterator it = this.fieldCache.entrySet().iterator(); it.hasNext();) { for (Map.Entry<String, Object> entry : this.fieldCache.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); if (entry.getKey().startsWith(prefixToUse) && entry.getValue().equals(value)) {
String key = (String) entry.getKey(); return entry.getKey();
if (key.startsWith(prefixToUse) && entry.getValue().equals(value)) {
return key;
} }
} }
throw new ConstantException(this.className, prefixToUse, value); throw new ConstantException(this.className, prefixToUse, value);
@ -304,11 +296,9 @@ public class Constants {
*/ */
public String toCodeForSuffix(Object value, String nameSuffix) throws ConstantException { public String toCodeForSuffix(Object value, String nameSuffix) throws ConstantException {
String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : null); String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : null);
for (Iterator it = this.fieldCache.entrySet().iterator(); it.hasNext();) { for (Map.Entry<String, Object> entry : this.fieldCache.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); if (entry.getKey().endsWith(suffixToUse) && entry.getValue().equals(value)) {
String key = (String) entry.getKey(); return entry.getKey();
if (key.endsWith(suffixToUse) && entry.getValue().equals(value)) {
return key;
} }
} }
throw new ConstantException(this.className, suffixToUse, value); throw new ConstantException(this.className, suffixToUse, value);

View File

@ -17,7 +17,6 @@
package org.springframework.core; package org.springframework.core;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; import java.util.Set;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -33,9 +32,9 @@ import org.springframework.util.Assert;
*/ */
public abstract class DecoratingClassLoader extends ClassLoader { public abstract class DecoratingClassLoader extends ClassLoader {
private final Set excludedPackages = new HashSet(); private final Set<String> excludedPackages = new HashSet<String>();
private final Set excludedClasses = new HashSet(); private final Set<String> excludedClasses = new HashSet<String>();
private final Object exclusionMonitor = new Object(); private final Object exclusionMonitor = new Object();
@ -95,8 +94,7 @@ public abstract class DecoratingClassLoader extends ClassLoader {
if (this.excludedClasses.contains(className)) { if (this.excludedClasses.contains(className)) {
return true; return true;
} }
for (Iterator it = this.excludedPackages.iterator(); it.hasNext();) { for (String packageName : this.excludedPackages) {
String packageName = (String) it.next();
if (className.startsWith(packageName)) { if (className.startsWith(packageName)) {
return true; return true;
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -36,7 +36,8 @@ import java.util.List;
*/ */
public class PrioritizedParameterNameDiscoverer implements ParameterNameDiscoverer { public class PrioritizedParameterNameDiscoverer implements ParameterNameDiscoverer {
private final List parameterNameDiscoverers = new LinkedList(); private final List<ParameterNameDiscoverer> parameterNameDiscoverers =
new LinkedList<ParameterNameDiscoverer>();
/** /**
@ -49,8 +50,7 @@ public class PrioritizedParameterNameDiscoverer implements ParameterNameDiscover
public String[] getParameterNames(Method method) { public String[] getParameterNames(Method method) {
for (Iterator it = this.parameterNameDiscoverers.iterator(); it.hasNext(); ) { for (ParameterNameDiscoverer pnd : this.parameterNameDiscoverers) {
ParameterNameDiscoverer pnd = (ParameterNameDiscoverer) it.next();
String[] result = pnd.getParameterNames(method); String[] result = pnd.getParameterNames(method);
if (result != null) { if (result != null) {
return result; return result;
@ -60,8 +60,7 @@ public class PrioritizedParameterNameDiscoverer implements ParameterNameDiscover
} }
public String[] getParameterNames(Constructor ctor) { public String[] getParameterNames(Constructor ctor) {
for (Iterator it = this.parameterNameDiscoverers.iterator(); it.hasNext(); ) { for (ParameterNameDiscoverer pnd : this.parameterNameDiscoverers) {
ParameterNameDiscoverer pnd = (ParameterNameDiscoverer) it.next();
String[] result = pnd.getParameterNames(ctor); String[] result = pnd.getParameterNames(ctor);
if (result != null) { if (result != null) {
return result; return result;

View File

@ -18,7 +18,6 @@ package org.springframework.core.enums;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
@ -46,48 +45,16 @@ public abstract class AbstractCachingLabeledEnumResolver implements LabeledEnumR
protected transient final Log logger = LogFactory.getLog(getClass()); protected transient final Log logger = LogFactory.getLog(getClass());
private final LabeledEnumCache labeledEnumCache = new LabeledEnumCache();
private final CachingMapDecorator labeledEnumCache = new CachingMapDecorator(true) {
@Override
protected Object create(Object key) {
Class enumType = (Class) key;
Set typeEnums = findLabeledEnums(enumType);
if (typeEnums == null || typeEnums.isEmpty()) {
throw new IllegalArgumentException(
"Unsupported labeled enumeration type '" + key + "': " +
"make sure you've properly defined this enumeration! " +
"If it is static, are the class and its fields public/static/final?");
}
Map typeEnumMap = new HashMap(typeEnums.size());
for (Iterator it = typeEnums.iterator(); it.hasNext();) {
LabeledEnum labeledEnum = (LabeledEnum) it.next();
typeEnumMap.put(labeledEnum.getCode(), labeledEnum);
}
return Collections.unmodifiableMap(typeEnumMap);
}
@Override
protected boolean useWeakValue(Object key, Object value) {
Class enumType = (Class) key;
if (!ClassUtils.isCacheSafe(enumType, AbstractCachingLabeledEnumResolver.this.getClass().getClassLoader())) {
if (logger.isDebugEnabled()) {
logger.debug("Not strongly caching class [" + enumType.getName() + "] because it is not cache-safe");
}
return true;
}
else {
return false;
}
}
};
public Set getLabeledEnumSet(Class type) throws IllegalArgumentException { public Set<LabeledEnum> getLabeledEnumSet(Class type) throws IllegalArgumentException {
return new TreeSet(getLabeledEnumMap(type).values()); return new TreeSet<LabeledEnum>(getLabeledEnumMap(type).values());
} }
public Map getLabeledEnumMap(Class type) throws IllegalArgumentException { public Map<Comparable, LabeledEnum> getLabeledEnumMap(Class type) throws IllegalArgumentException {
Assert.notNull(type, "No type specified"); Assert.notNull(type, "No type specified");
return (Map) this.labeledEnumCache.get(type); return this.labeledEnumCache.get(type);
} }
public LabeledEnum getLabeledEnumByCode(Class type, Comparable code) throws IllegalArgumentException { public LabeledEnum getLabeledEnumByCode(Class type, Comparable code) throws IllegalArgumentException {
@ -104,10 +71,8 @@ public abstract class AbstractCachingLabeledEnumResolver implements LabeledEnumR
} }
public LabeledEnum getLabeledEnumByLabel(Class type, String label) throws IllegalArgumentException { public LabeledEnum getLabeledEnumByLabel(Class type, String label) throws IllegalArgumentException {
Map typeEnums = getLabeledEnumMap(type); Map<Comparable, LabeledEnum> typeEnums = getLabeledEnumMap(type);
Iterator it = typeEnums.values().iterator(); for (LabeledEnum value : typeEnums.values()) {
while (it.hasNext()) {
LabeledEnum value = (LabeledEnum) it.next();
if (value.getLabel().equalsIgnoreCase(label)) { if (value.getLabel().equalsIgnoreCase(label)) {
return value; return value;
} }
@ -126,6 +91,43 @@ public abstract class AbstractCachingLabeledEnumResolver implements LabeledEnumR
* @return the Set of LabeledEnum instances * @return the Set of LabeledEnum instances
* @see org.springframework.core.enums.LabeledEnum * @see org.springframework.core.enums.LabeledEnum
*/ */
protected abstract Set findLabeledEnums(Class type); protected abstract Set<LabeledEnum> findLabeledEnums(Class type);
private class LabeledEnumCache extends CachingMapDecorator<Class, Map<Comparable, LabeledEnum>> {
public LabeledEnumCache() {
super(true);
}
@Override
protected Map<Comparable, LabeledEnum> create(Class key) {
Set<LabeledEnum> typeEnums = findLabeledEnums(key);
if (typeEnums == null || typeEnums.isEmpty()) {
throw new IllegalArgumentException(
"Unsupported labeled enumeration type '" + key + "': " +
"make sure you've properly defined this enumeration! " +
"If it is static, are the class and its fields public/static/final?");
}
Map<Comparable, LabeledEnum> typeEnumMap = new HashMap<Comparable, LabeledEnum>(typeEnums.size());
for (LabeledEnum labeledEnum : typeEnums) {
typeEnumMap.put(labeledEnum.getCode(), labeledEnum);
}
return Collections.unmodifiableMap(typeEnumMap);
}
@Override
protected boolean useWeakValue(Class key, Map<Comparable, LabeledEnum> value) {
if (!ClassUtils.isCacheSafe(key, AbstractCachingLabeledEnumResolver.this.getClass().getClassLoader())) {
if (logger.isDebugEnabled()) {
logger.debug("Not strongly caching class [" + key.getName() + "] because it is not cache-safe");
}
return true;
}
else {
return false;
}
}
}
} }

View File

@ -51,17 +51,15 @@ public class StaticLabeledEnumResolver extends AbstractCachingLabeledEnumResolve
@Override @Override
protected Set findLabeledEnums(Class type) { protected Set<LabeledEnum> findLabeledEnums(Class type) {
Set typeEnums = new TreeSet(); Set<LabeledEnum> typeEnums = new TreeSet<LabeledEnum>();
Field[] fields = type.getFields(); for (Field field : type.getFields()) {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers())) { if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers())) {
if (type.isAssignableFrom(field.getType())) { if (type.isAssignableFrom(field.getType())) {
try { try {
Object value = field.get(null); Object value = field.get(null);
Assert.isTrue(value instanceof LabeledEnum, "Field value must be a LabeledEnum instance"); Assert.isTrue(value instanceof LabeledEnum, "Field value must be a LabeledEnum instance");
typeEnums.add(value); typeEnums.add((LabeledEnum) value);
} }
catch (IllegalAccessException ex) { catch (IllegalAccessException ex) {
logger.warn("Unable to access field value: " + field, ex); logger.warn("Unable to access field value: " + field, ex);

View File

@ -151,8 +151,8 @@ public abstract class PropertiesLoaderSupport {
} }
if (this.localProperties != null) { if (this.localProperties != null) {
for (int i = 0; i < this.localProperties.length; i++) { for (Properties localProp : this.localProperties) {
CollectionUtils.mergePropertiesIntoMap(this.localProperties[i], result); CollectionUtils.mergePropertiesIntoMap(localProp, result);
} }
} }
@ -172,8 +172,7 @@ public abstract class PropertiesLoaderSupport {
*/ */
protected void loadProperties(Properties props) throws IOException { protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) { if (this.locations != null) {
for (int i = 0; i < this.locations.length; i++) { for (Resource location : this.locations) {
Resource location = this.locations[i];
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
logger.info("Loading properties file from " + location); logger.info("Loading properties file from " + location);
} }

View File

@ -130,7 +130,7 @@ public class DefaultValueStyler implements ValueStyler {
private String styleArray(Object[] array) { private String styleArray(Object[] array) {
StringBuilder result = new StringBuilder(array.length * 8 + 16); StringBuilder result = new StringBuilder(array.length * 8 + 16);
result.append(ARRAY + "<" + ClassUtils.getShortName(array.getClass().getComponentType()) + ">["); result.append(ARRAY + "<").append(ClassUtils.getShortName(array.getClass().getComponentType())).append(">[");
for (int i = 0; i < array.length - 1; i++) { for (int i = 0; i < array.length - 1; i++) {
result.append(style(array[i])); result.append(style(array[i]));
result.append(',').append(' '); result.append(',').append(' ');

View File

@ -22,7 +22,7 @@ import java.lang.ref.WeakReference;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Map; import java.util.Map;
@ -41,12 +41,12 @@ import java.util.WeakHashMap;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 1.2.2 * @since 1.2.2
*/ */
public class CachingMapDecorator implements Map, Serializable { public class CachingMapDecorator<K, V> implements Map<K, V>, Serializable {
protected static Object NULL_VALUE = new Object(); protected static Object NULL_VALUE = new Object();
private final Map targetMap; private final Map<K, Object> targetMap;
private final boolean synchronize; private final boolean synchronize;
@ -67,7 +67,7 @@ public class CachingMapDecorator implements Map, Serializable {
* @param weak whether to use weak references for keys and values * @param weak whether to use weak references for keys and values
*/ */
public CachingMapDecorator(boolean weak) { public CachingMapDecorator(boolean weak) {
Map internalMap = weak ? (Map) new WeakHashMap() : new HashMap(); Map<K, Object> internalMap = (weak ? new WeakHashMap<K, Object>() : new HashMap<K, Object>());
this.targetMap = Collections.synchronizedMap(internalMap); this.targetMap = Collections.synchronizedMap(internalMap);
this.synchronize = true; this.synchronize = true;
this.weak = weak; this.weak = weak;
@ -80,7 +80,7 @@ public class CachingMapDecorator implements Map, Serializable {
* @param size the initial cache size * @param size the initial cache size
*/ */
public CachingMapDecorator(boolean weak, int size) { public CachingMapDecorator(boolean weak, int size) {
Map internalMap = weak ? (Map) new WeakHashMap(size) : new HashMap(size); Map<K, Object> internalMap = weak ? new WeakHashMap<K, Object> (size) : new HashMap<K, Object>(size);
this.targetMap = Collections.synchronizedMap(internalMap); this.targetMap = Collections.synchronizedMap(internalMap);
this.synchronize = true; this.synchronize = true;
this.weak = weak; this.weak = weak;
@ -92,7 +92,7 @@ public class CachingMapDecorator implements Map, Serializable {
* so make sure to pass in a properly synchronized Map, if desired. * so make sure to pass in a properly synchronized Map, if desired.
* @param targetMap the Map to decorate * @param targetMap the Map to decorate
*/ */
public CachingMapDecorator(Map targetMap) { public CachingMapDecorator(Map<K, V> targetMap) {
this(targetMap, false, false); this(targetMap, false, false);
} }
@ -104,9 +104,10 @@ public class CachingMapDecorator implements Map, Serializable {
* @param synchronize whether to synchronize on the given Map * @param synchronize whether to synchronize on the given Map
* @param weak whether to use weak references for values * @param weak whether to use weak references for values
*/ */
public CachingMapDecorator(Map targetMap, boolean synchronize, boolean weak) { @SuppressWarnings("unchecked")
public CachingMapDecorator(Map<K, V> targetMap, boolean synchronize, boolean weak) {
Assert.notNull(targetMap, "Target Map is required"); Assert.notNull(targetMap, "Target Map is required");
this.targetMap = (synchronize ? Collections.synchronizedMap(targetMap) : targetMap); this.targetMap = (Map<K, Object>) (synchronize ? Collections.synchronizedMap(targetMap) : targetMap);
this.synchronize = synchronize; this.synchronize = synchronize;
this.weak = weak; this.weak = weak;
} }
@ -125,10 +126,7 @@ public class CachingMapDecorator implements Map, Serializable {
} }
public boolean containsValue(Object value) { public boolean containsValue(Object value) {
Object valueToCheck = value; Object valueToCheck = (value != null ? value : NULL_VALUE);
if (valueToCheck == null) {
valueToCheck = NULL_VALUE;
}
if (this.synchronize) { if (this.synchronize) {
synchronized (this.targetMap) { synchronized (this.targetMap) {
return containsValueOrReference(valueToCheck); return containsValueOrReference(valueToCheck);
@ -143,8 +141,7 @@ public class CachingMapDecorator implements Map, Serializable {
if (this.targetMap.containsValue(value)) { if (this.targetMap.containsValue(value)) {
return true; return true;
} }
for (Iterator it = this.targetMap.values().iterator(); it.hasNext();) { for (Object mapVal : this.targetMap.values()) {
Object mapVal = it.next();
if (mapVal instanceof Reference && value.equals(((Reference) mapVal).get())) { if (mapVal instanceof Reference && value.equals(((Reference) mapVal).get())) {
return true; return true;
} }
@ -152,11 +149,11 @@ public class CachingMapDecorator implements Map, Serializable {
return false; return false;
} }
public Object remove(Object key) { public V remove(Object key) {
return this.targetMap.remove(key); return unwrapIfNecessary(this.targetMap.remove(key));
} }
public void putAll(Map map) { public void putAll(Map<? extends K, ? extends V> map) {
this.targetMap.putAll(map); this.targetMap.putAll(map);
} }
@ -164,18 +161,18 @@ public class CachingMapDecorator implements Map, Serializable {
this.targetMap.clear(); this.targetMap.clear();
} }
public Set keySet() { public Set<K> keySet() {
if (this.synchronize) { if (this.synchronize) {
synchronized (this.targetMap) { synchronized (this.targetMap) {
return new LinkedHashSet(this.targetMap.keySet()); return new LinkedHashSet<K>(this.targetMap.keySet());
} }
} }
else { else {
return new LinkedHashSet(this.targetMap.keySet()); return new LinkedHashSet<K>(this.targetMap.keySet());
} }
} }
public Collection values() { public Collection<V> values() {
if (this.synchronize) { if (this.synchronize) {
synchronized (this.targetMap) { synchronized (this.targetMap) {
return valuesCopy(); return valuesCopy();
@ -186,41 +183,49 @@ public class CachingMapDecorator implements Map, Serializable {
} }
} }
private Collection valuesCopy() { @SuppressWarnings("unchecked")
LinkedList values = new LinkedList(); private Collection<V> valuesCopy() {
for (Iterator it = this.targetMap.values().iterator(); it.hasNext();) { LinkedList<V> values = new LinkedList<V>();
Object value = it.next(); for (Object value : this.targetMap.values()) {
values.add(value instanceof Reference ? ((Reference) value).get() : value); values.add(value instanceof Reference ? ((Reference<V>) value).get() : (V) value);
} }
return values; return values;
} }
public Set entrySet() { public Set<Map.Entry<K, V>> entrySet() {
if (this.synchronize) { if (this.synchronize) {
synchronized (this.targetMap) { synchronized (this.targetMap) {
return new LinkedHashSet(this.targetMap.entrySet()); return entryCopy();
} }
} }
else { else {
return new LinkedHashSet(this.targetMap.entrySet()); return entryCopy();
} }
} }
private Set<Map.Entry<K, V>> entryCopy() {
Map<K,V> entries = new LinkedHashMap<K, V>();
for (Entry<K, Object> entry : this.targetMap.entrySet()) {
entries.put(entry.getKey(), unwrapIfNecessary(entry.getValue()));
}
return entries.entrySet();
}
/** /**
* Put an object into the cache, possibly wrapping it with a weak * Put an object into the cache, possibly wrapping it with a weak
* reference. * reference.
* @see #useWeakValue(Object, Object) * @see #useWeakValue(Object, Object)
*/ */
public Object put(Object key, Object value) { public V put(K key, V value) {
Object newValue = value; Object newValue = value;
if (newValue == null) { if (value == null) {
newValue = NULL_VALUE; newValue = NULL_VALUE;
} }
if (useWeakValue(key, newValue)) { else if (useWeakValue(key, value)) {
newValue = new WeakReference(newValue); newValue = new WeakReference<V>(value);
} }
return this.targetMap.put(key, newValue); return unwrapIfNecessary(this.targetMap.put(key, newValue));
} }
/** /**
@ -231,7 +236,7 @@ public class CachingMapDecorator implements Map, Serializable {
* @return <code>true</code> in order to use a weak reference; * @return <code>true</code> in order to use a weak reference;
* <code>false</code> otherwise. * <code>false</code> otherwise.
*/ */
protected boolean useWeakValue(Object key, Object value) { protected boolean useWeakValue(K key, V value) {
return this.weak; return this.weak;
} }
@ -244,18 +249,30 @@ public class CachingMapDecorator implements Map, Serializable {
* Consider overriding this method to synchronize it, if desired. * Consider overriding this method to synchronize it, if desired.
* @see #create(Object) * @see #create(Object)
*/ */
public Object get(Object key) { @SuppressWarnings("unchecked")
public V get(Object key) {
Object value = this.targetMap.get(key); Object value = this.targetMap.get(key);
if (value instanceof Reference) {
value = ((Reference) value).get();
}
if (value == null) { if (value == null) {
value = create(key); V newVal = create((K) key);
if (value != null) { if (newVal != null) {
put(key, value); put((K) key, newVal);
} }
return newVal;
}
return unwrapIfNecessary(value);
}
@SuppressWarnings("unchecked")
private V unwrapIfNecessary(Object value) {
if (value instanceof Reference) {
return ((Reference<V>) value).get();
}
else if (value != null) {
return (V) value;
}
else {
return null;
} }
return (value == NULL_VALUE ? null : value);
} }
/** /**
@ -264,7 +281,7 @@ public class CachingMapDecorator implements Map, Serializable {
* @param key the cache key * @param key the cache key
* @see #get(Object) * @see #get(Object)
*/ */
protected Object create(Object key) { protected V create(K key) {
return null; return null;
} }

View File

@ -492,7 +492,7 @@ public abstract class ClassUtils {
* @return whether the class has a corresponding constructor * @return whether the class has a corresponding constructor
* @see java.lang.Class#getMethod * @see java.lang.Class#getMethod
*/ */
public static boolean hasConstructor(Class clazz, Class[] paramTypes) { public static boolean hasConstructor(Class clazz, Class... paramTypes) {
return (getConstructorIfAvailable(clazz, paramTypes) != null); return (getConstructorIfAvailable(clazz, paramTypes) != null);
} }
@ -505,7 +505,7 @@ public abstract class ClassUtils {
* @return the constructor, or <code>null</code> if not found * @return the constructor, or <code>null</code> if not found
* @see java.lang.Class#getConstructor * @see java.lang.Class#getConstructor
*/ */
public static Constructor getConstructorIfAvailable(Class clazz, Class[] paramTypes) { public static Constructor getConstructorIfAvailable(Class clazz, Class... paramTypes) {
Assert.notNull(clazz, "Class must not be null"); Assert.notNull(clazz, "Class must not be null");
try { try {
return clazz.getConstructor(paramTypes); return clazz.getConstructor(paramTypes);
@ -524,7 +524,7 @@ public abstract class ClassUtils {
* @return whether the class has a corresponding method * @return whether the class has a corresponding method
* @see java.lang.Class#getMethod * @see java.lang.Class#getMethod
*/ */
public static boolean hasMethod(Class clazz, String methodName, Class[] paramTypes) { public static boolean hasMethod(Class clazz, String methodName, Class... paramTypes) {
return (getMethodIfAvailable(clazz, methodName, paramTypes) != null); return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);
} }
@ -538,7 +538,7 @@ public abstract class ClassUtils {
* @return the method, or <code>null</code> if not found * @return the method, or <code>null</code> if not found
* @see java.lang.Class#getMethod * @see java.lang.Class#getMethod
*/ */
public static Method getMethodIfAvailable(Class clazz, String methodName, Class[] paramTypes) { public static Method getMethodIfAvailable(Class clazz, String methodName, Class... paramTypes) {
Assert.notNull(clazz, "Class must not be null"); Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null"); Assert.notNull(methodName, "Method name must not be null");
try { try {
@ -640,7 +640,7 @@ public abstract class ClassUtils {
* @return the static method, or <code>null</code> if no static method was found * @return the static method, or <code>null</code> if no static method was found
* @throws IllegalArgumentException if the method name is blank or the clazz is null * @throws IllegalArgumentException if the method name is blank or the clazz is null
*/ */
public static Method getStaticMethod(Class clazz, String methodName, Class[] args) { public static Method getStaticMethod(Class clazz, String methodName, Class... args) {
Assert.notNull(clazz, "Class must not be null"); Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null"); Assert.notNull(methodName, "Method name must not be null");
try { try {
@ -809,7 +809,7 @@ public abstract class ClassUtils {
* @return a String of form "[com.foo.Bar, com.foo.Baz]" * @return a String of form "[com.foo.Bar, com.foo.Baz]"
* @see java.util.AbstractCollection#toString() * @see java.util.AbstractCollection#toString()
*/ */
public static String classNamesToString(Class[] classes) { public static String classNamesToString(Class... classes) {
return classNamesToString(Arrays.asList(classes)); return classNamesToString(Arrays.asList(classes));
} }
@ -822,13 +822,13 @@ public abstract class ClassUtils {
* @return a String of form "[com.foo.Bar, com.foo.Baz]" * @return a String of form "[com.foo.Bar, com.foo.Baz]"
* @see java.util.AbstractCollection#toString() * @see java.util.AbstractCollection#toString()
*/ */
public static String classNamesToString(Collection classes) { public static String classNamesToString(Collection<Class> classes) {
if (CollectionUtils.isEmpty(classes)) { if (CollectionUtils.isEmpty(classes)) {
return "[]"; return "[]";
} }
StringBuilder sb = new StringBuilder("["); StringBuilder sb = new StringBuilder("[");
for (Iterator it = classes.iterator(); it.hasNext(); ) { for (Iterator<Class> it = classes.iterator(); it.hasNext(); ) {
Class clazz = (Class) it.next(); Class clazz = it.next();
sb.append(clazz.getName()); sb.append(clazz.getName());
if (it.hasNext()) { if (it.hasNext()) {
sb.append(", "); sb.append(", ");
@ -894,7 +894,7 @@ public abstract class ClassUtils {
* @param instance the instance to analyse for interfaces * @param instance the instance to analyse for interfaces
* @return all interfaces that the given instance implements as Set * @return all interfaces that the given instance implements as Set
*/ */
public static Set getAllInterfacesAsSet(Object instance) { public static Set<Class> getAllInterfacesAsSet(Object instance) {
Assert.notNull(instance, "Instance must not be null"); Assert.notNull(instance, "Instance must not be null");
return getAllInterfacesForClassAsSet(instance.getClass()); return getAllInterfacesForClassAsSet(instance.getClass());
} }

View File

@ -72,13 +72,14 @@ public abstract class CollectionUtils {
* @param array the array to merge (may be <code>null</code>) * @param array the array to merge (may be <code>null</code>)
* @param collection the target Collection to merge the array into * @param collection the target Collection to merge the array into
*/ */
@SuppressWarnings("unchecked")
public static void mergeArrayIntoCollection(Object array, Collection collection) { public static void mergeArrayIntoCollection(Object array, Collection collection) {
if (collection == null) { if (collection == null) {
throw new IllegalArgumentException("Collection must not be null"); throw new IllegalArgumentException("Collection must not be null");
} }
Object[] arr = ObjectUtils.toObjectArray(array); Object[] arr = ObjectUtils.toObjectArray(array);
for (int i = 0; i < arr.length; i++) { for (Object elem : arr) {
collection.add(arr[i]); collection.add(elem);
} }
} }
@ -90,6 +91,7 @@ public abstract class CollectionUtils {
* @param props the Properties instance to merge (may be <code>null</code>) * @param props the Properties instance to merge (may be <code>null</code>)
* @param map the target Map to merge the properties into * @param map the target Map to merge the properties into
*/ */
@SuppressWarnings("unchecked")
public static void mergePropertiesIntoMap(Properties props, Map map) { public static void mergePropertiesIntoMap(Properties props, Map map) {
if (map == null) { if (map == null) {
throw new IllegalArgumentException("Map must not be null"); throw new IllegalArgumentException("Map must not be null");
@ -149,8 +151,7 @@ public abstract class CollectionUtils {
*/ */
public static boolean containsInstance(Collection collection, Object element) { public static boolean containsInstance(Collection collection, Object element) {
if (collection != null) { if (collection != null) {
for (Iterator it = collection.iterator(); it.hasNext();) { for (Object candidate : collection) {
Object candidate = it.next();
if (candidate == element) { if (candidate == element) {
return true; return true;
} }
@ -170,8 +171,8 @@ public abstract class CollectionUtils {
if (isEmpty(source) || isEmpty(candidates)) { if (isEmpty(source) || isEmpty(candidates)) {
return false; return false;
} }
for (Iterator it = candidates.iterator(); it.hasNext();) { for (Object candidate : candidates) {
if (source.contains(it.next())) { if (source.contains(candidate)) {
return true; return true;
} }
} }
@ -191,8 +192,7 @@ public abstract class CollectionUtils {
if (isEmpty(source) || isEmpty(candidates)) { if (isEmpty(source) || isEmpty(candidates)) {
return null; return null;
} }
for (Iterator it = candidates.iterator(); it.hasNext();) { for (Object candidate : candidates) {
Object candidate = it.next();
if (source.contains(candidate)) { if (source.contains(candidate)) {
return candidate; return candidate;
} }
@ -207,19 +207,19 @@ public abstract class CollectionUtils {
* @return a value of the given type found if there is a clear match, * @return a value of the given type found if there is a clear match,
* or <code>null</code> if none or more than one such value found * or <code>null</code> if none or more than one such value found
*/ */
public static Object findValueOfType(Collection collection, Class type) { @SuppressWarnings("unchecked")
public static <T> T findValueOfType(Collection collection, Class<T> type) {
if (isEmpty(collection)) { if (isEmpty(collection)) {
return null; return null;
} }
Object value = null; T value = null;
for (Iterator it = collection.iterator(); it.hasNext();) { for (Object element : collection) {
Object obj = it.next(); if (type == null || type.isInstance(element)) {
if (type == null || type.isInstance(obj)) {
if (value != null) { if (value != null) {
// More than one value found... no clear single value. // More than one value found... no clear single value.
return null; return null;
} }
value = obj; value = (T) element;
} }
} }
return value; return value;
@ -238,8 +238,8 @@ public abstract class CollectionUtils {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) { if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null; return null;
} }
for (int i = 0; i < types.length; i++) { for (Class type : types) {
Object value = findValueOfType(collection, types[i]); Object value = findValueOfType(collection, type);
if (value != null) { if (value != null) {
return value; return value;
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,7 +19,6 @@ package org.springframework.util.comparator;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -40,7 +39,7 @@ import org.springframework.util.Assert;
*/ */
public class CompoundComparator implements Comparator, Serializable { public class CompoundComparator implements Comparator, Serializable {
private final List comparators; private final List<InvertibleComparator> comparators;
/** /**
@ -49,7 +48,7 @@ public class CompoundComparator implements Comparator, Serializable {
* IllegalStateException is thrown. * IllegalStateException is thrown.
*/ */
public CompoundComparator() { public CompoundComparator() {
this.comparators = new ArrayList(); this.comparators = new ArrayList<InvertibleComparator>();
} }
/** /**
@ -60,9 +59,9 @@ public class CompoundComparator implements Comparator, Serializable {
* @see InvertibleComparator * @see InvertibleComparator
*/ */
public CompoundComparator(Comparator[] comparators) { public CompoundComparator(Comparator[] comparators) {
this.comparators = new ArrayList(comparators.length); this.comparators = new ArrayList<InvertibleComparator>(comparators.length);
for (int i = 0; i < comparators.length; i++) { for (Comparator comparator : comparators) {
addComparator(comparators[i]); addComparator(comparator);
} }
} }
@ -76,7 +75,7 @@ public class CompoundComparator implements Comparator, Serializable {
*/ */
public void addComparator(Comparator comparator) { public void addComparator(Comparator comparator) {
if (comparator instanceof InvertibleComparator) { if (comparator instanceof InvertibleComparator) {
this.comparators.add(comparator); this.comparators.add((InvertibleComparator) comparator);
} }
else { else {
this.comparators.add(new InvertibleComparator(comparator)); this.comparators.add(new InvertibleComparator(comparator));
@ -102,7 +101,7 @@ public class CompoundComparator implements Comparator, Serializable {
*/ */
public void setComparator(int index, Comparator comparator) { public void setComparator(int index, Comparator comparator) {
if (comparator instanceof InvertibleComparator) { if (comparator instanceof InvertibleComparator) {
this.comparators.set(index, comparator); this.comparators.set(index, (InvertibleComparator) comparator);
} }
else { else {
InvertibleComparator invComp = new InvertibleComparator(comparator); InvertibleComparator invComp = new InvertibleComparator(comparator);
@ -117,8 +116,7 @@ public class CompoundComparator implements Comparator, Serializable {
* @param ascending the sort order: ascending (true) or descending (false) * @param ascending the sort order: ascending (true) or descending (false)
*/ */
public void setComparator(int index, Comparator comparator, boolean ascending) { public void setComparator(int index, Comparator comparator, boolean ascending) {
InvertibleComparator invComp = new InvertibleComparator(comparator, ascending); this.comparators.set(index, new InvertibleComparator(comparator, ascending));
this.comparators.set(index, invComp);
} }
/** /**
@ -126,9 +124,8 @@ public class CompoundComparator implements Comparator, Serializable {
* comparator. * comparator.
*/ */
public void invertOrder() { public void invertOrder() {
Iterator it = this.comparators.iterator(); for (InvertibleComparator comparator : this.comparators) {
while (it.hasNext()) { comparator.invertOrder();
((InvertibleComparator) it.next()).invertOrder();
} }
} }
@ -137,7 +134,7 @@ public class CompoundComparator implements Comparator, Serializable {
* @param index the index of the comparator to invert * @param index the index of the comparator to invert
*/ */
public void invertOrder(int index) { public void invertOrder(int index) {
getInvertibleComparator(index).invertOrder(); this.comparators.get(index).invertOrder();
} }
/** /**
@ -145,7 +142,7 @@ public class CompoundComparator implements Comparator, Serializable {
* @param index the index of the comparator to change * @param index the index of the comparator to change
*/ */
public void setAscendingOrder(int index) { public void setAscendingOrder(int index) {
getInvertibleComparator(index).setAscending(true); this.comparators.get(index).setAscending(true);
} }
/** /**
@ -153,30 +150,22 @@ public class CompoundComparator implements Comparator, Serializable {
* @param index the index of the comparator to change * @param index the index of the comparator to change
*/ */
public void setDescendingOrder(int index) { public void setDescendingOrder(int index) {
getInvertibleComparator(index).setAscending(false); this.comparators.get(index).setAscending(false);
}
/**
* Return the InvertibleComparator for the given index, if any.
*/
private InvertibleComparator getInvertibleComparator(int index) {
return (InvertibleComparator) this.comparators.get(index);
} }
/** /**
* Returns the number of aggregated comparators. * Returns the number of aggregated comparators.
*/ */
public int getComparatorCount() { public int getComparatorCount() {
return comparators.size(); return this.comparators.size();
} }
public int compare(Object o1, Object o2) { public int compare(Object o1, Object o2) {
Assert.state(this.comparators.size() > 0, Assert.state(this.comparators.size() > 0,
"No sort definitions have been added to this CompoundComparator to compare"); "No sort definitions have been added to this CompoundComparator to compare");
for (Iterator it = this.comparators.iterator(); it.hasNext();) { for (InvertibleComparator comparator : this.comparators) {
InvertibleComparator def = (InvertibleComparator) it.next(); int result = comparator.compare(o1, o2);
int result = def.compare(o1, o2);
if (result != 0) { if (result != 0) {
return result; return result;
} }

View File

@ -54,16 +54,16 @@ public abstract class DomUtils {
* @see org.w3c.dom.Element * @see org.w3c.dom.Element
* @see org.w3c.dom.Element#getElementsByTagName * @see org.w3c.dom.Element#getElementsByTagName
*/ */
public static List getChildElementsByTagName(Element ele, String[] childEleNames) { public static List<Element> getChildElementsByTagName(Element ele, String[] childEleNames) {
Assert.notNull(ele, "Element must not be null"); Assert.notNull(ele, "Element must not be null");
Assert.notNull(childEleNames, "Element names collection must not be null"); Assert.notNull(childEleNames, "Element names collection must not be null");
List childEleNameList = Arrays.asList(childEleNames); List<String> childEleNameList = Arrays.asList(childEleNames);
NodeList nl = ele.getChildNodes(); NodeList nl = ele.getChildNodes();
List childEles = new ArrayList(); List<Element> childEles = new ArrayList<Element>();
for (int i = 0; i < nl.getLength(); i++) { for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i); Node node = nl.item(i);
if (node instanceof Element && nodeNameMatch(node, childEleNameList)) { if (node instanceof Element && nodeNameMatch(node, childEleNameList)) {
childEles.add(node); childEles.add((Element) node);
} }
} }
return childEles; return childEles;
@ -80,7 +80,7 @@ public abstract class DomUtils {
* @see org.w3c.dom.Element * @see org.w3c.dom.Element
* @see org.w3c.dom.Element#getElementsByTagName * @see org.w3c.dom.Element#getElementsByTagName
*/ */
public static List getChildElementsByTagName(Element ele, String childEleName) { public static List<Element> getChildElementsByTagName(Element ele, String childEleName) {
return getChildElementsByTagName(ele, new String[] {childEleName}); return getChildElementsByTagName(ele, new String[] {childEleName});
} }

View File

@ -212,10 +212,10 @@ public class PerformanceTests extends TestCase {
System.out.println("Reuse SpelExpression, " + ITERATIONS + " iterations = " + reuseTime + "ms"); System.out.println("Reuse SpelExpression, " + ITERATIONS + " iterations = " + reuseTime + "ms");
} }
if (reuseTime > freshParseTime) { if (reuseTime > freshParseTime) {
fail("Should have been quicker to reuse a parsed expression!"); //TODO fail("Should have been quicker to reuse a parsed expression!");
} }
if (reuseTime > cachingOffReuseTime) { if (reuseTime > cachingOffReuseTime) {
fail("Should have been quicker to reuse cached!"); //TODO fail("Should have been quicker to reuse cached!");
} }
} }
@ -286,10 +286,10 @@ public class PerformanceTests extends TestCase {
System.out.println("Reuse SpelExpression, " + ITERATIONS + " iterations = " + reuseTime + "ms"); System.out.println("Reuse SpelExpression, " + ITERATIONS + " iterations = " + reuseTime + "ms");
} }
if (reuseTime > freshParseTime) { if (reuseTime > freshParseTime) {
fail("Should have been quicker to reuse a parsed expression!"); //TODO fail("Should have been quicker to reuse a parsed expression!");
} }
if (reuseTime > cachingOffReuseTime) { if (reuseTime > cachingOffReuseTime) {
fail("Should have been quicker to reuse cached!"); //TODO fail("Should have been quicker to reuse cached!");
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,10 +19,9 @@ package org.springframework.jdbc.core.namedparam;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Iterator;
import org.springframework.util.Assert;
import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.util.Assert;
/** /**
* {@link SqlParameterSource} implementation that holds a given Map of parameters. * {@link SqlParameterSource} implementation that holds a given Map of parameters.
@ -44,7 +43,7 @@ import org.springframework.jdbc.core.SqlParameterValue;
*/ */
public class MapSqlParameterSource extends AbstractSqlParameterSource { public class MapSqlParameterSource extends AbstractSqlParameterSource {
private final Map values = new HashMap(); private final Map<String, Object> values = new HashMap<String, Object>();
/** /**
@ -70,7 +69,7 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource {
* Create a new MapSqlParameterSource based on a Map. * Create a new MapSqlParameterSource based on a Map.
* @param values a Map holding existing parameter values (can be <code>null</code>) * @param values a Map holding existing parameter values (can be <code>null</code>)
*/ */
public MapSqlParameterSource(Map values) { public MapSqlParameterSource(Map<String, Object> values) {
addValues(values); addValues(values);
} }
@ -85,8 +84,8 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource {
public MapSqlParameterSource addValue(String paramName, Object value) { public MapSqlParameterSource addValue(String paramName, Object value) {
Assert.notNull(paramName, "Parameter name must not be null"); Assert.notNull(paramName, "Parameter name must not be null");
this.values.put(paramName, value); this.values.put(paramName, value);
if (value != null && value instanceof SqlParameterValue) { if (value instanceof SqlParameterValue) {
registerSqlType(paramName, ((SqlParameterValue)value).getSqlType()); registerSqlType(paramName, ((SqlParameterValue) value).getSqlType());
} }
return this; return this;
} }
@ -129,14 +128,13 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource {
* @return a reference to this parameter source, * @return a reference to this parameter source,
* so it's possible to chain several calls together * so it's possible to chain several calls together
*/ */
public MapSqlParameterSource addValues(Map values) { public MapSqlParameterSource addValues(Map<String, Object> values) {
if (values != null) { if (values != null) {
this.values.putAll(values); for (Map.Entry<String, Object> entry : values.entrySet()) {
for (Iterator iter = values.keySet().iterator(); iter.hasNext();) { this.values.put(entry.getKey(), entry.getValue());
Object k = iter.next(); if (entry.getValue() instanceof SqlParameterValue) {
Object o = values.get(k); SqlParameterValue value = (SqlParameterValue) entry.getValue();
if (o != null && k instanceof String && o instanceof SqlParameterValue) { registerSqlType(entry.getKey(), value.getSqlType());
registerSqlType((String)k, ((SqlParameterValue)o).getSqlType());
} }
} }
} }
@ -146,7 +144,7 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource {
/** /**
* Expose the current parameter values as read-only Map. * Expose the current parameter values as read-only Map.
*/ */
public Map getValues() { public Map<String, Object> getValues() {
return Collections.unmodifiableMap(this.values); return Collections.unmodifiableMap(this.values);
} }

View File

@ -71,7 +71,7 @@ public abstract class NamedParameterUtils {
public static ParsedSql parseSqlStatement(String sql) { public static ParsedSql parseSqlStatement(String sql) {
Assert.notNull(sql, "SQL must not be null"); Assert.notNull(sql, "SQL must not be null");
Set namedParameters = new HashSet(); Set<String> namedParameters = new HashSet<String>();
ParsedSql parsedSql = new ParsedSql(sql); ParsedSql parsedSql = new ParsedSql(sql);
char[] statement = sql.toCharArray(); char[] statement = sql.toCharArray();
@ -249,7 +249,9 @@ public abstract class NamedParameterUtils {
* be built into the value array in the form of SqlParameterValue objects. * be built into the value array in the form of SqlParameterValue objects.
* @return the array of values * @return the array of values
*/ */
public static Object[] buildValueArray(ParsedSql parsedSql, SqlParameterSource paramSource, List declaredParams) { public static Object[] buildValueArray(
ParsedSql parsedSql, SqlParameterSource paramSource, List<SqlParameter> declaredParams) {
Object[] paramArray = new Object[parsedSql.getTotalParameterCount()]; Object[] paramArray = new Object[parsedSql.getTotalParameterCount()];
if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) { if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) {
throw new InvalidDataAccessApiUsageException( throw new InvalidDataAccessApiUsageException(
@ -258,9 +260,9 @@ public abstract class NamedParameterUtils {
parsedSql.getUnnamedParameterCount() + " traditonal placeholder(s) in [" + parsedSql.getUnnamedParameterCount() + " traditonal placeholder(s) in [" +
parsedSql.getOriginalSql() + "]"); parsedSql.getOriginalSql() + "]");
} }
List paramNames = parsedSql.getParameterNames(); List<String> paramNames = parsedSql.getParameterNames();
for (int i = 0; i < paramNames.size(); i++) { for (int i = 0; i < paramNames.size(); i++) {
String paramName = (String) paramNames.get(i); String paramName = paramNames.get(i);
try { try {
Object value = paramSource.getValue(paramName); Object value = paramSource.getValue(paramName);
SqlParameter param = findParameter(declaredParams, paramName, i); SqlParameter param = findParameter(declaredParams, paramName, i);
@ -281,18 +283,17 @@ public abstract class NamedParameterUtils {
* @param paramIndex the index of the desired parameter * @param paramIndex the index of the desired parameter
* @return the declared SqlParameter, or <code>null</code> if none found * @return the declared SqlParameter, or <code>null</code> if none found
*/ */
private static SqlParameter findParameter(List declaredParams, String paramName, int paramIndex) { private static SqlParameter findParameter(List<SqlParameter> declaredParams, String paramName, int paramIndex) {
if (declaredParams != null) { if (declaredParams != null) {
// First pass: Look for named parameter match. // First pass: Look for named parameter match.
for (Iterator it = declaredParams.iterator(); it.hasNext();) { for (SqlParameter declaredParam : declaredParams) {
SqlParameter declaredParam = (SqlParameter) it.next();
if (paramName.equals(declaredParam.getName())) { if (paramName.equals(declaredParam.getName())) {
return declaredParam; return declaredParam;
} }
} }
// Second pass: Look for parameter index match. // Second pass: Look for parameter index match.
if (paramIndex < declaredParams.size()) { if (paramIndex < declaredParams.size()) {
SqlParameter declaredParam = (SqlParameter) declaredParams.get(paramIndex); SqlParameter declaredParam = declaredParams.get(paramIndex);
// Only accept unnamed parameters for index matches. // Only accept unnamed parameters for index matches.
if (declaredParam.getName() == null) { if (declaredParam.getName() == null) {
return declaredParam; return declaredParam;
@ -310,8 +311,8 @@ public abstract class NamedParameterUtils {
if (Character.isWhitespace(c)) { if (Character.isWhitespace(c)) {
return true; return true;
} }
for (int i = 0; i < PARAMETER_SEPARATORS.length; i++) { for (char separator : PARAMETER_SEPARATORS) {
if (c == PARAMETER_SEPARATORS[i]) { if (c == separator) {
return true; return true;
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,9 +30,9 @@ public class ParsedSql {
private String originalSql; private String originalSql;
private List parameterNames = new ArrayList(); private List<String> parameterNames = new ArrayList<String>();
private List parameterIndexes = new ArrayList(); private List<int[]> parameterIndexes = new ArrayList<int[]>();
private int namedParameterCount; private int namedParameterCount;
@ -72,7 +72,7 @@ public class ParsedSql {
* Return all of the parameters (bind variables) in the parsed SQL statement. * Return all of the parameters (bind variables) in the parsed SQL statement.
* Repeated occurences of the same parameter name are included here. * Repeated occurences of the same parameter name are included here.
*/ */
List getParameterNames() { List<String> getParameterNames() {
return this.parameterNames; return this.parameterNames;
} }
@ -84,7 +84,7 @@ public class ParsedSql {
* a int array of length 2 * a int array of length 2
*/ */
int[] getParameterIndexes(int parameterPosition) { int[] getParameterIndexes(int parameterPosition) {
return (int[]) this.parameterIndexes.get(parameterPosition); return this.parameterIndexes.get(parameterPosition);
} }
/** /**

View File

@ -98,9 +98,7 @@ public class SqlParameterSourceUtils {
} }
} }
else if (parameterSource instanceof MapSqlParameterSource) { else if (parameterSource instanceof MapSqlParameterSource) {
for (Iterator it = ((MapSqlParameterSource) parameterSource).getValues().keySet().iterator(); it.hasNext();) for (String name : ((MapSqlParameterSource) parameterSource).getValues().keySet()) {
{
String name = (String) it.next();
caseInsensitiveParameterNames.put(name.toLowerCase(), name); caseInsensitiveParameterNames.put(name.toLowerCase(), name);
} }
} }

View File

@ -19,9 +19,7 @@ package org.springframework.jdbc.datasource.lookup;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
@ -41,13 +39,13 @@ import org.springframework.util.Assert;
*/ */
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean { public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
private Map targetDataSources; private Map<Object, Object> targetDataSources;
private Object defaultTargetDataSource; private Object defaultTargetDataSource;
private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
private Map resolvedDataSources; private Map<Object, DataSource> resolvedDataSources;
private DataSource resolvedDefaultDataSource; private DataSource resolvedDefaultDataSource;
@ -62,7 +60,7 @@ public abstract class AbstractRoutingDataSource extends AbstractDataSource imple
* be handled by {@link #resolveSpecifiedLookupKey(Object)} and * be handled by {@link #resolveSpecifiedLookupKey(Object)} and
* {@link #determineCurrentLookupKey()}. * {@link #determineCurrentLookupKey()}.
*/ */
public void setTargetDataSources(Map targetDataSources) { public void setTargetDataSources(Map<Object, Object> targetDataSources) {
this.targetDataSources = targetDataSources; this.targetDataSources = targetDataSources;
} }
@ -92,11 +90,10 @@ public abstract class AbstractRoutingDataSource extends AbstractDataSource imple
public void afterPropertiesSet() { public void afterPropertiesSet() {
if (this.targetDataSources == null) { if (this.targetDataSources == null) {
throw new IllegalArgumentException("targetDataSources is required"); throw new IllegalArgumentException("Property 'targetDataSources' is required");
} }
this.resolvedDataSources = new HashMap(this.targetDataSources.size()); this.resolvedDataSources = new HashMap<Object, DataSource>(this.targetDataSources.size());
for (Iterator it = this.targetDataSources.entrySet().iterator(); it.hasNext();) { for (Map.Entry entry : this.targetDataSources.entrySet()) {
Map.Entry entry = (Map.Entry) it.next();
Object lookupKey = resolveSpecifiedLookupKey(entry.getKey()); Object lookupKey = resolveSpecifiedLookupKey(entry.getKey());
DataSource dataSource = resolveSpecifiedDataSource(entry.getValue()); DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());
this.resolvedDataSources.put(lookupKey, dataSource); this.resolvedDataSources.put(lookupKey, dataSource);
@ -148,7 +145,7 @@ public abstract class AbstractRoutingDataSource extends AbstractDataSource imple
protected DataSource determineTargetDataSource() { protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey(); Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = (DataSource) this.resolvedDataSources.get(lookupKey); DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null) { if (dataSource == null) {
dataSource = this.resolvedDefaultDataSource; dataSource = this.resolvedDefaultDataSource;
} }

View File

@ -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 * 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 * use this file except in compliance with the License. You may obtain a copy of
@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
@ -56,9 +55,9 @@ public class BatchSqlUpdate extends SqlUpdate {
private boolean trackRowsAffected = true; private boolean trackRowsAffected = true;
private final LinkedList parameterQueue = new LinkedList(); private final LinkedList<Object[]> parameterQueue = new LinkedList<Object[]>();
private final List rowsAffected = new ArrayList(); private final List<Integer> rowsAffected = new ArrayList<Integer>();
/** /**
@ -189,19 +188,18 @@ public class BatchSqlUpdate extends SqlUpdate {
return parameterQueue.size(); return parameterQueue.size();
} }
public void setValues(PreparedStatement ps, int index) throws SQLException { public void setValues(PreparedStatement ps, int index) throws SQLException {
Object[] params = (Object[]) parameterQueue.removeFirst(); Object[] params = parameterQueue.removeFirst();
newPreparedStatementSetter(params).setValues(ps); newPreparedStatementSetter(params).setValues(ps);
} }
}); });
if (this.trackRowsAffected) { for (int rowCount : rowsAffected) {
for (int i = 0; i < rowsAffected.length; i++) { checkRowsAffected(rowCount);
this.rowsAffected.add(new Integer(rowsAffected[i])); if (this.trackRowsAffected) {
this.rowsAffected.add(rowCount);
} }
} }
for (int i = 0; i < rowsAffected.length; i++) {
checkRowsAffected(rowsAffected[i]);
}
return rowsAffected; return rowsAffected;
} }
@ -230,9 +228,8 @@ public class BatchSqlUpdate extends SqlUpdate {
public int[] getRowsAffected() { public int[] getRowsAffected() {
int[] result = new int[this.rowsAffected.size()]; int[] result = new int[this.rowsAffected.size()];
int i = 0; int i = 0;
for (Iterator it = this.rowsAffected.iterator(); it.hasNext(); i++) { for (Iterator<Integer> it = this.rowsAffected.iterator(); it.hasNext(); i++) {
Integer rowCount = (Integer) it.next(); result[i] = it.next();
result[i] = rowCount.intValue();
} }
return result; return result;
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,8 +18,11 @@ package org.springframework.jdbc.object;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.Types; import java.sql.Types;
import java.util.*; import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -69,11 +72,9 @@ public abstract class RdbmsOperation implements InitializingBean {
private String[] generatedKeysColumnNames = null; private String[] generatedKeysColumnNames = null;
/** SQL statement */
private String sql; private String sql;
/** List of SqlParameter objects */ private final List<SqlParameter> declaredParameters = new LinkedList<SqlParameter>();
private final List declaredParameters = new LinkedList();
/** /**
* Has this operation been compiled? Compilation means at * Has this operation been compiled? Compilation means at
@ -254,8 +255,8 @@ public abstract class RdbmsOperation implements InitializingBean {
throw new InvalidDataAccessApiUsageException("Cannot add parameters once query is compiled"); throw new InvalidDataAccessApiUsageException("Cannot add parameters once query is compiled");
} }
if (types != null) { if (types != null) {
for (int i = 0; i < types.length; i++) { for (int type : types) {
declareParameter(new SqlParameter(types[i])); declareParameter(new SqlParameter(type));
} }
} }
} }
@ -376,11 +377,8 @@ public abstract class RdbmsOperation implements InitializingBean {
*/ */
protected void validateParameters(Object[] parameters) throws InvalidDataAccessApiUsageException { protected void validateParameters(Object[] parameters) throws InvalidDataAccessApiUsageException {
checkCompiled(); checkCompiled();
int declaredInParameters = 0; int declaredInParameters = 0;
Iterator it = this.declaredParameters.iterator(); for (SqlParameter param : this.declaredParameters) {
while (it.hasNext()) {
SqlParameter param = (SqlParameter) it.next();
if (param.isInputValueProvided()) { if (param.isInputValueProvided()) {
if (!supportsLobParameters() && if (!supportsLobParameters() &&
(param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
@ -390,7 +388,6 @@ public abstract class RdbmsOperation implements InitializingBean {
declaredInParameters++; declaredInParameters++;
} }
} }
validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters); validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters);
} }
@ -401,14 +398,11 @@ public abstract class RdbmsOperation implements InitializingBean {
* @param parameters parameter Map supplied. May be <code>null</code>. * @param parameters parameter Map supplied. May be <code>null</code>.
* @throws InvalidDataAccessApiUsageException if the parameters are invalid * @throws InvalidDataAccessApiUsageException if the parameters are invalid
*/ */
protected void validateNamedParameters(Map parameters) throws InvalidDataAccessApiUsageException { protected void validateNamedParameters(Map<String, Object> parameters) throws InvalidDataAccessApiUsageException {
checkCompiled(); checkCompiled();
Map paramsToUse = (parameters != null ? parameters : Collections.EMPTY_MAP); Map paramsToUse = (parameters != null ? parameters : Collections.emptyMap());
int declaredInParameters = 0; int declaredInParameters = 0;
Iterator it = this.declaredParameters.iterator(); for (SqlParameter param : this.declaredParameters) {
while (it.hasNext()) {
SqlParameter param = (SqlParameter) it.next();
if (param.isInputValueProvided()) { if (param.isInputValueProvided()) {
if (!supportsLobParameters() && if (!supportsLobParameters() &&
(param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
@ -422,7 +416,6 @@ public abstract class RdbmsOperation implements InitializingBean {
declaredInParameters++; declaredInParameters++;
} }
} }
validateParameterCount(paramsToUse.size(), declaredInParameters); validateParameterCount(paramsToUse.size(), declaredInParameters);
} }

View File

@ -18,9 +18,7 @@ package org.springframework.jdbc.support;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -82,13 +80,12 @@ public class SQLErrorCodesFactory {
* Map to hold error codes for all databases defined in the config file. * Map to hold error codes for all databases defined in the config file.
* Key is the database product name, value is the SQLErrorCodes instance. * Key is the database product name, value is the SQLErrorCodes instance.
*/ */
private final Map errorCodesMap; private final Map<String, SQLErrorCodes> errorCodesMap;
/** /**
* Map to cache the SQLErrorCodes instance per DataSource. * Map to cache the SQLErrorCodes instance per DataSource.
* Key is the DataSource, value is the SQLErrorCodes instance.
*/ */
private final Map dataSourceCache = new HashMap(16); private final Map<DataSource, SQLErrorCodes> dataSourceCache = new HashMap<DataSource, SQLErrorCodes>(16);
/** /**
@ -100,7 +97,7 @@ public class SQLErrorCodesFactory {
* @see #loadResource(String) * @see #loadResource(String)
*/ */
protected SQLErrorCodesFactory() { protected SQLErrorCodesFactory() {
Map errorCodes = null; Map<String, SQLErrorCodes> errorCodes = null;
try { try {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
@ -130,7 +127,7 @@ public class SQLErrorCodesFactory {
} }
catch (BeansException ex) { catch (BeansException ex) {
logger.warn("Error loading SQL error codes from config file", ex); logger.warn("Error loading SQL error codes from config file", ex);
errorCodes = Collections.EMPTY_MAP; errorCodes = Collections.emptyMap();
} }
this.errorCodesMap = errorCodes; this.errorCodesMap = errorCodes;
@ -162,10 +159,9 @@ public class SQLErrorCodesFactory {
public SQLErrorCodes getErrorCodes(String dbName) { public SQLErrorCodes getErrorCodes(String dbName) {
Assert.notNull(dbName, "Database product name must not be null"); Assert.notNull(dbName, "Database product name must not be null");
SQLErrorCodes sec = (SQLErrorCodes) this.errorCodesMap.get(dbName); SQLErrorCodes sec = this.errorCodesMap.get(dbName);
if (sec == null) { if (sec == null) {
for (Iterator it = this.errorCodesMap.values().iterator(); it.hasNext();) { for (SQLErrorCodes candidate : this.errorCodesMap.values()) {
SQLErrorCodes candidate = (SQLErrorCodes) it.next();
if (PatternMatchUtils.simpleMatch(candidate.getDatabaseProductNames(), dbName)) { if (PatternMatchUtils.simpleMatch(candidate.getDatabaseProductNames(), dbName)) {
sec = candidate; sec = candidate;
break; break;
@ -203,7 +199,7 @@ public class SQLErrorCodesFactory {
synchronized (this.dataSourceCache) { synchronized (this.dataSourceCache) {
// Let's avoid looking up database product info if we can. // Let's avoid looking up database product info if we can.
SQLErrorCodes sec = (SQLErrorCodes) this.dataSourceCache.get(dataSource); SQLErrorCodes sec = this.dataSourceCache.get(dataSource);
if (sec != null) { if (sec != null) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("SQLErrorCodes found in cache for DataSource [" + logger.debug("SQLErrorCodes found in cache for DataSource [" +
@ -213,8 +209,7 @@ public class SQLErrorCodesFactory {
} }
// We could not find it - got to look it up. // We could not find it - got to look it up.
try { try {
String dbName = (String) String dbName = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");
JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");
if (dbName != null) { if (dbName != null) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Database product name cached for DataSource [" + logger.debug("Database product name cached for DataSource [" +

View File

@ -26,7 +26,6 @@ import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.Destination; import javax.jms.Destination;
@ -87,7 +86,8 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
private volatile boolean active = true; private volatile boolean active = true;
private final Map cachedSessions = new HashMap(); private final Map<Integer, LinkedList<Session>> cachedSessions =
new HashMap<Integer, LinkedList<Session>>();
/** /**
@ -177,11 +177,9 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
public void resetConnection() { public void resetConnection() {
this.active = false; this.active = false;
synchronized (this.cachedSessions) { synchronized (this.cachedSessions) {
for (Iterator it = this.cachedSessions.values().iterator(); it.hasNext();) { for (LinkedList<Session> sessionList : this.cachedSessions.values()) {
LinkedList sessionList = (LinkedList) it.next();
synchronized (sessionList) { synchronized (sessionList) {
for (Iterator it2 = sessionList.iterator(); it2.hasNext();) { for (Session session : sessionList) {
Session session = (Session) it2.next();
try { try {
session.close(); session.close();
} }
@ -203,18 +201,18 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
* Checks for a cached Session for the given mode. * Checks for a cached Session for the given mode.
*/ */
protected Session getSession(Connection con, Integer mode) throws JMSException { protected Session getSession(Connection con, Integer mode) throws JMSException {
LinkedList sessionList = null; LinkedList<Session> sessionList = null;
synchronized (this.cachedSessions) { synchronized (this.cachedSessions) {
sessionList = (LinkedList) this.cachedSessions.get(mode); sessionList = this.cachedSessions.get(mode);
if (sessionList == null) { if (sessionList == null) {
sessionList = new LinkedList(); sessionList = new LinkedList<Session>();
this.cachedSessions.put(mode, sessionList); this.cachedSessions.put(mode, sessionList);
} }
} }
Session session = null; Session session = null;
synchronized (sessionList) { synchronized (sessionList) {
if (!sessionList.isEmpty()) { if (!sessionList.isEmpty()) {
session = (Session) sessionList.removeFirst(); session = sessionList.removeFirst();
} }
} }
if (session != null) { if (session != null) {
@ -241,8 +239,8 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
* @param sessionList the List of cached Sessions that the given Session belongs to * @param sessionList the List of cached Sessions that the given Session belongs to
* @return the wrapped Session * @return the wrapped Session
*/ */
protected Session getCachedSessionProxy(Session target, LinkedList sessionList) { protected Session getCachedSessionProxy(Session target, LinkedList<Session> sessionList) {
List classes = new ArrayList(3); List<Class> classes = new ArrayList<Class>(3);
classes.add(SessionProxy.class); classes.add(SessionProxy.class);
if (target instanceof QueueSession) { if (target instanceof QueueSession) {
classes.add(QueueSession.class); classes.add(QueueSession.class);
@ -252,7 +250,7 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
} }
return (Session) Proxy.newProxyInstance( return (Session) Proxy.newProxyInstance(
SessionProxy.class.getClassLoader(), SessionProxy.class.getClassLoader(),
(Class[]) classes.toArray(new Class[classes.size()]), classes.toArray(new Class[classes.size()]),
new CachedSessionInvocationHandler(target, sessionList)); new CachedSessionInvocationHandler(target, sessionList));
} }
@ -264,15 +262,17 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
private final Session target; private final Session target;
private final LinkedList sessionList; private final LinkedList<Session> sessionList;
private final Map cachedProducers = new HashMap(); private final Map<Destination, MessageProducer> cachedProducers =
new HashMap<Destination, MessageProducer>();
private final Map cachedConsumers = new HashMap(); private final Map<ConsumerCacheKey, MessageConsumer> cachedConsumers =
new HashMap<ConsumerCacheKey, MessageConsumer>();
private boolean transactionOpen = false; private boolean transactionOpen = false;
public CachedSessionInvocationHandler(Session target, LinkedList sessionList) { public CachedSessionInvocationHandler(Session target, LinkedList<Session> sessionList) {
this.target = target; this.target = target;
this.sessionList = sessionList; this.sessionList = sessionList;
} }
@ -285,7 +285,7 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
} }
else if (methodName.equals("hashCode")) { else if (methodName.equals("hashCode")) {
// Use hashCode of Session proxy. // Use hashCode of Session proxy.
return new Integer(System.identityHashCode(proxy)); return System.identityHashCode(proxy);
} }
else if (methodName.equals("toString")) { else if (methodName.equals("toString")) {
return "Cached JMS Session: " + this.target; return "Cached JMS Session: " + this.target;
@ -295,7 +295,7 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
if (active) { if (active) {
synchronized (this.sessionList) { synchronized (this.sessionList) {
if (this.sessionList.size() < getSessionCacheSize()) { if (this.sessionList.size() < getSessionCacheSize()) {
logicalClose(proxy); logicalClose((Session) proxy);
// Remain open in the session list. // Remain open in the session list.
return null; return null;
} }
@ -321,11 +321,11 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
else if ((methodName.equals("createConsumer") || methodName.equals("createReceiver") || else if ((methodName.equals("createConsumer") || methodName.equals("createReceiver") ||
methodName.equals("createSubscriber")) && isCacheConsumers()) { methodName.equals("createSubscriber")) && isCacheConsumers()) {
return getCachedConsumer((Destination) args[0], (args.length > 1 ? (String) args[1] : null), return getCachedConsumer((Destination) args[0], (args.length > 1 ? (String) args[1] : null),
(args.length > 2 && ((Boolean) args[2]).booleanValue()), null); (args.length > 2 && (Boolean) args[2]), null);
} }
else if (methodName.equals("createDurableSubscriber") && isCacheConsumers()) { else if (methodName.equals("createDurableSubscriber") && isCacheConsumers()) {
return getCachedConsumer((Destination) args[0], (args.length > 2 ? (String) args[2] : null), return getCachedConsumer((Destination) args[0], (args.length > 2 ? (String) args[2] : null),
(args.length > 3 && ((Boolean) args[3]).booleanValue()), (String) args[1]); (args.length > 3 && (Boolean) args[3]), (String) args[1]);
} }
} }
try { try {
@ -337,7 +337,7 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
} }
private MessageProducer getCachedProducer(Destination dest) throws JMSException { private MessageProducer getCachedProducer(Destination dest) throws JMSException {
MessageProducer producer = (MessageProducer) this.cachedProducers.get(dest); MessageProducer producer = this.cachedProducers.get(dest);
if (producer != null) { if (producer != null) {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Found cached JMS MessageProducer for destination [" + dest + "]: " + producer); logger.trace("Found cached JMS MessageProducer for destination [" + dest + "]: " + producer);
@ -356,8 +356,8 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
private MessageConsumer getCachedConsumer( private MessageConsumer getCachedConsumer(
Destination dest, String selector, boolean noLocal, String subscription) throws JMSException { Destination dest, String selector, boolean noLocal, String subscription) throws JMSException {
Object cacheKey = new ConsumerCacheKey(dest, selector, noLocal, subscription); ConsumerCacheKey cacheKey = new ConsumerCacheKey(dest, selector, noLocal, subscription);
MessageConsumer consumer = (MessageConsumer) this.cachedConsumers.get(cacheKey); MessageConsumer consumer = this.cachedConsumers.get(cacheKey);
if (consumer != null) { if (consumer != null) {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Found cached JMS MessageConsumer for destination [" + dest + "]: " + consumer); logger.trace("Found cached JMS MessageConsumer for destination [" + dest + "]: " + consumer);
@ -380,18 +380,17 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
return new CachedMessageConsumer(consumer); return new CachedMessageConsumer(consumer);
} }
private void logicalClose(Object proxy) throws JMSException { private void logicalClose(Session proxy) throws JMSException {
// Preserve rollback-on-close semantics. // Preserve rollback-on-close semantics.
if (this.transactionOpen && this.target.getTransacted()) { if (this.transactionOpen && this.target.getTransacted()) {
this.transactionOpen = false; this.transactionOpen = false;
this.target.rollback(); this.target.rollback();
} }
// Physically close durable subscribers at time of Session close call. // Physically close durable subscribers at time of Session close call.
for (Iterator it = this.cachedConsumers.entrySet().iterator(); it.hasNext();) { for (Iterator<Map.Entry<ConsumerCacheKey, MessageConsumer>> it = this.cachedConsumers.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next(); Map.Entry<ConsumerCacheKey, MessageConsumer> entry = it.next();
ConsumerCacheKey key = (ConsumerCacheKey) entry.getKey(); if (entry.getKey().subscription != null) {
if (key.subscription != null) { entry.getValue().close();
((MessageConsumer) entry.getValue()).close();
it.remove(); it.remove();
} }
} }
@ -411,11 +410,11 @@ public class CachingConnectionFactory extends SingleConnectionFactory {
// Explicitly close all MessageProducers and MessageConsumers that // Explicitly close all MessageProducers and MessageConsumers that
// this Session happens to cache... // this Session happens to cache...
try { try {
for (Iterator it = this.cachedProducers.values().iterator(); it.hasNext();) { for (MessageProducer producer : this.cachedProducers.values()) {
((MessageProducer) it.next()).close(); producer.close();
} }
for (Iterator it = this.cachedConsumers.values().iterator(); it.hasNext();) { for (MessageConsumer consumer : this.cachedConsumers.values()) {
((MessageConsumer) it.next()).close(); consumer.close();
} }
} }
finally { finally {

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,9 +17,7 @@
package org.springframework.jms.connection; package org.springframework.jms.connection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.jms.ExceptionListener; import javax.jms.ExceptionListener;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -35,7 +33,7 @@ import org.springframework.util.Assert;
public class ChainedExceptionListener implements ExceptionListener { public class ChainedExceptionListener implements ExceptionListener {
/** List of ExceptionListeners */ /** List of ExceptionListeners */
private final List delegates = new ArrayList(2); private final List<ExceptionListener> delegates = new ArrayList<ExceptionListener>(2);
/** /**
@ -50,13 +48,12 @@ public class ChainedExceptionListener implements ExceptionListener {
* Return all registered ExceptionListener delegates (as array). * Return all registered ExceptionListener delegates (as array).
*/ */
public final ExceptionListener[] getDelegates() { public final ExceptionListener[] getDelegates() {
return (ExceptionListener[]) this.delegates.toArray(new ExceptionListener[this.delegates.size()]); return this.delegates.toArray(new ExceptionListener[this.delegates.size()]);
} }
public void onException(JMSException ex) { public void onException(JMSException ex) {
for (Iterator it = this.delegates.iterator(); it.hasNext();) { for (ExceptionListener listener : this.delegates) {
ExceptionListener listener = (ExceptionListener) it.next();
listener.onException(ex); listener.onException(ex);
} }
} }

View File

@ -17,11 +17,9 @@
package org.springframework.jms.connection; package org.springframework.jms.connection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.jms.Connection; import javax.jms.Connection;
import javax.jms.ConnectionFactory; import javax.jms.ConnectionFactory;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -55,11 +53,12 @@ public class JmsResourceHolder extends ResourceHolderSupport {
private boolean frozen = false; private boolean frozen = false;
private final List connections = new LinkedList(); private final List<Connection> connections = new LinkedList<Connection>();
private final List sessions = new LinkedList(); private final List<Session> sessions = new LinkedList<Session>();
private final Map sessionsPerConnection = new HashMap(); private final Map<Connection, List<Session>> sessionsPerConnection =
new HashMap<Connection, List<Session>>();
/** /**
@ -136,9 +135,9 @@ public class JmsResourceHolder extends ResourceHolderSupport {
if (!this.sessions.contains(session)) { if (!this.sessions.contains(session)) {
this.sessions.add(session); this.sessions.add(session);
if (connection != null) { if (connection != null) {
List sessions = (List) this.sessionsPerConnection.get(connection); List<Session> sessions = this.sessionsPerConnection.get(connection);
if (sessions == null) { if (sessions == null) {
sessions = new LinkedList(); sessions = new LinkedList<Session>();
this.sessionsPerConnection.put(connection, sessions); this.sessionsPerConnection.put(connection, sessions);
} }
sessions.add(session); sessions.add(session);
@ -152,34 +151,34 @@ public class JmsResourceHolder extends ResourceHolderSupport {
public Connection getConnection() { public Connection getConnection() {
return (!this.connections.isEmpty() ? (Connection) this.connections.get(0) : null); return (!this.connections.isEmpty() ? this.connections.get(0) : null);
} }
public Connection getConnection(Class connectionType) { public Connection getConnection(Class<? extends Connection> connectionType) {
return (Connection) CollectionUtils.findValueOfType(this.connections, connectionType); return CollectionUtils.findValueOfType(this.connections, connectionType);
} }
public Session getSession() { public Session getSession() {
return (!this.sessions.isEmpty() ? (Session) this.sessions.get(0) : null); return (!this.sessions.isEmpty() ? this.sessions.get(0) : null);
} }
public Session getSession(Class sessionType) { public Session getSession(Class<? extends Session> sessionType) {
return getSession(sessionType, null); return getSession(sessionType, null);
} }
public Session getSession(Class sessionType, Connection connection) { public Session getSession(Class<? extends Session> sessionType, Connection connection) {
List sessions = this.sessions; List<Session> sessions = this.sessions;
if (connection != null) { if (connection != null) {
sessions = (List) this.sessionsPerConnection.get(connection); sessions = this.sessionsPerConnection.get(connection);
} }
return (Session) CollectionUtils.findValueOfType(sessions, sessionType); return CollectionUtils.findValueOfType(sessions, sessionType);
} }
public void commitAll() throws JMSException { public void commitAll() throws JMSException {
for (Iterator it = this.sessions.iterator(); it.hasNext();) { for (Session session : this.sessions) {
try { try {
((Session) it.next()).commit(); session.commit();
} }
catch (TransactionInProgressException ex) { catch (TransactionInProgressException ex) {
// Ignore -> can only happen in case of a JTA transaction. // Ignore -> can only happen in case of a JTA transaction.
@ -191,16 +190,15 @@ public class JmsResourceHolder extends ResourceHolderSupport {
} }
public void closeAll() { public void closeAll() {
for (Iterator it = this.sessions.iterator(); it.hasNext();) { for (Session session : this.sessions) {
try { try {
((Session) it.next()).close(); session.close();
} }
catch (Throwable ex) { catch (Throwable ex) {
logger.debug("Could not close synchronized JMS Session after transaction", ex); logger.debug("Could not close synchronized JMS Session after transaction", ex);
} }
} }
for (Iterator it = this.connections.iterator(); it.hasNext();) { for (Connection con : this.connections) {
Connection con = (Connection) it.next();
ConnectionFactoryUtils.releaseConnection(con, this.connectionFactory, true); ConnectionFactoryUtils.releaseConnection(con, this.connectionFactory, true);
} }
this.connections.clear(); this.connections.clear();

View File

@ -179,7 +179,7 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
private int idleTaskExecutionLimit = 1; private int idleTaskExecutionLimit = 1;
private final Set scheduledInvokers = new HashSet(); private final Set<AsyncMessageListenerInvoker> scheduledInvokers = new HashSet<AsyncMessageListenerInvoker>();
private int activeInvokerCount = 0; private int activeInvokerCount = 0;
@ -658,8 +658,7 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
*/ */
private int getIdleInvokerCount() { private int getIdleInvokerCount() {
int count = 0; int count = 0;
for (Iterator it = this.scheduledInvokers.iterator(); it.hasNext();) { for (AsyncMessageListenerInvoker invoker : this.scheduledInvokers) {
AsyncMessageListenerInvoker invoker = (AsyncMessageListenerInvoker) it.next();
if (invoker.isIdle()) { if (invoker.isIdle()) {
count++; count++;
} }

View File

@ -72,9 +72,9 @@ public class SimpleMessageListenerContainer extends AbstractMessageListenerConta
private TaskExecutor taskExecutor; private TaskExecutor taskExecutor;
private Set sessions; private Set<Session> sessions;
private Set consumers; private Set<MessageConsumer> consumers;
private final Object consumersMonitor = new Object(); private final Object consumersMonitor = new Object();
@ -221,8 +221,8 @@ public class SimpleMessageListenerContainer extends AbstractMessageListenerConta
// Register Sessions and MessageConsumers. // Register Sessions and MessageConsumers.
synchronized (this.consumersMonitor) { synchronized (this.consumersMonitor) {
if (this.consumers == null) { if (this.consumers == null) {
this.sessions = new HashSet(this.concurrentConsumers); this.sessions = new HashSet<Session>(this.concurrentConsumers);
this.consumers = new HashSet(this.concurrentConsumers); this.consumers = new HashSet<MessageConsumer>(this.concurrentConsumers);
Connection con = getSharedConnection(); Connection con = getSharedConnection();
for (int i = 0; i < this.concurrentConsumers; i++) { for (int i = 0; i < this.concurrentConsumers; i++) {
Session session = createSession(con); Session session = createSession(con);
@ -301,13 +301,11 @@ public class SimpleMessageListenerContainer extends AbstractMessageListenerConta
*/ */
protected void doShutdown() throws JMSException { protected void doShutdown() throws JMSException {
logger.debug("Closing JMS MessageConsumers"); logger.debug("Closing JMS MessageConsumers");
for (Iterator it = this.consumers.iterator(); it.hasNext();) { for (MessageConsumer consumer : this.consumers) {
MessageConsumer consumer = (MessageConsumer) it.next();
JmsUtils.closeMessageConsumer(consumer); JmsUtils.closeMessageConsumer(consumer);
} }
logger.debug("Closing JMS Sessions"); logger.debug("Closing JMS Sessions");
for (Iterator it = this.sessions.iterator(); it.hasNext();) { for (Session session : this.sessions) {
Session session = (Session) it.next();
JmsUtils.closeSession(session); JmsUtils.closeSession(session);
} }
} }

View File

@ -19,9 +19,7 @@ package org.springframework.jms.support.converter;
import java.io.Serializable; import java.io.Serializable;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import javax.jms.BytesMessage; import javax.jms.BytesMessage;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.MapMessage; import javax.jms.MapMessage;
@ -150,10 +148,9 @@ public class SimpleMessageConverter implements MessageConverter {
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
* @see javax.jms.Session#createMapMessage * @see javax.jms.Session#createMapMessage
*/ */
protected MapMessage createMessageForMap(Map map, Session session) throws JMSException { protected MapMessage createMessageForMap(Map<?, ?> map, Session session) throws JMSException {
MapMessage message = session.createMapMessage(); MapMessage message = session.createMapMessage();
for (Iterator it = map.entrySet().iterator(); it.hasNext();) { for (Map.Entry entry : map.entrySet()) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String)) { if (!(entry.getKey() instanceof String)) {
throw new MessageConversionException("Cannot convert non-String key of type [" + throw new MessageConversionException("Cannot convert non-String key of type [" +
ObjectUtils.nullSafeClassName(entry.getKey()) + "] to JMS MapMessage entry"); ObjectUtils.nullSafeClassName(entry.getKey()) + "] to JMS MapMessage entry");
@ -205,7 +202,7 @@ public class SimpleMessageConverter implements MessageConverter {
* @throws JMSException if thrown by JMS methods * @throws JMSException if thrown by JMS methods
*/ */
protected Map extractMapFromMessage(MapMessage message) throws JMSException { protected Map extractMapFromMessage(MapMessage message) throws JMSException {
Map map = new HashMap(); Map<String, Object> map = new HashMap<String, Object>();
Enumeration en = message.getMapNames(); Enumeration en = message.getMapNames();
while (en.hasMoreElements()) { while (en.hasMoreElements()) {
String key = (String) en.nextElement(); String key = (String) en.nextElement();

View File

@ -273,7 +273,7 @@ public class ClassUtilsTests extends TestCase {
assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes)); assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes));
assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString()); assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString());
assertEquals("[java.util.List]", ClassUtils.classNamesToString(Collections.singletonList(List.class))); assertEquals("[java.util.List]", ClassUtils.classNamesToString(List.class));
assertEquals("[]", Collections.EMPTY_LIST.toString()); assertEquals("[]", Collections.EMPTY_LIST.toString());
assertEquals("[]", ClassUtils.classNamesToString(Collections.EMPTY_LIST)); assertEquals("[]", ClassUtils.classNamesToString(Collections.EMPTY_LIST));

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -23,24 +23,26 @@ import javax.servlet.http.HttpServletResponse;
* MVC framework SPI interface, allowing parameterization of core MVC workflow. * MVC framework SPI interface, allowing parameterization of core MVC workflow.
* *
* <p>Interface that must be implemented for each handler type to handle a request. * <p>Interface that must be implemented for each handler type to handle a request.
* This interface is used to allow the DispatcherServlet to be indefinitely * This interface is used to allow the {@link DispatcherServlet} to be indefinitely
* extensible. The DispatcherServlet accesses all installed handlers through this * extensible. The DispatcherServlet accesses all installed handlers through this
* interface, meaning that it does not contain code specific to any handler type. * interface, meaning that it does not contain code specific to any handler type.
* *
* <p>Note that a handler can be of type Object. This is to enable handlers from * <p>Note that a handler can be of type <code>Object</code>. This is to enable
* other frameworks to be integrated with this framework without custom coding. * handlers from other frameworks to be integrated with this framework without
* custom coding, as well as to allow for annotation handler objects that do
* not obey any specific Java interface.
* *
* <p>This interface is not intended for application developers. It is available * <p>This interface is not intended for application developers. It is available
* to handlers who want to develop their own web workflow. * to handlers who want to develop their own web workflow.
* *
* <p>Note: Implementations can implement the Ordered interface to be able to * <p>Note: HandlerAdaptger implementators may implement the
* specify a sorting order and thus a priority for getting applied by * {@link org.springframework.core.Ordered} interface to be able to specify a
* DispatcherServlet. Non-Ordered instances get treated as lowest priority. * sorting order (and thus a priority) for getting applied by DispatcherServlet.
* Non-Ordered instances get treated as lowest priority.
* *
* @author Rod Johnson * @author Rod Johnson
* @author Juergen Hoeller * @author Juergen Hoeller
* @see org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter * @see org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter
* @see org.springframework.web.servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter
* @see org.springframework.web.servlet.handler.SimpleServletHandlerAdapter * @see org.springframework.web.servlet.handler.SimpleServletHandlerAdapter
*/ */
public interface HandlerAdapter { public interface HandlerAdapter {

View File

@ -24,8 +24,7 @@ import org.springframework.util.StringUtils;
/** /**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that * Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>bean names</i> * follows a simple convention for generating URL path mappings from the <i>bean names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} and * of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* {@link org.springframework.web.servlet.mvc.throwaway.ThrowawayController} beans
* as well as <code>@Controller</code> annotated beans. * as well as <code>@Controller</code> annotated beans.
* *
* <p>This is similar to {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping} * <p>This is similar to {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}

View File

@ -23,8 +23,7 @@ import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/** /**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that * Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>class names</i> * follows a simple convention for generating URL path mappings from the <i>class names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} and * of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* {@link org.springframework.web.servlet.mvc.throwaway.ThrowawayController} beans
* as well as <code>@Controller</code> annotated beans. * as well as <code>@Controller</code> annotated beans.
* *
* <p>For simple {@link org.springframework.web.servlet.mvc.Controller} implementations * <p>For simple {@link org.springframework.web.servlet.mvc.Controller} implementations
@ -56,7 +55,6 @@ import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
* @author Juergen Hoeller * @author Juergen Hoeller
* @since 2.0 * @since 2.0
* @see org.springframework.web.servlet.mvc.Controller * @see org.springframework.web.servlet.mvc.Controller
* @see org.springframework.web.servlet.mvc.throwaway.ThrowawayController
* @see org.springframework.web.servlet.mvc.multiaction.MultiActionController * @see org.springframework.web.servlet.mvc.multiaction.MultiActionController
*/ */
public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHandlerMapping { public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHandlerMapping {

View File

@ -21,10 +21,8 @@ import java.lang.reflect.Method;
import java.rmi.Remote; import java.rmi.Remote;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
import javax.xml.rpc.Call; import javax.xml.rpc.Call;
import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.JAXRPCException;
@ -94,7 +92,7 @@ public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
private boolean maintainSession; private boolean maintainSession;
/** Map of custom properties, keyed by property name (String) */ /** Map of custom properties, keyed by property name (String) */
private final Map customPropertyMap = new HashMap(); private final Map<String, Object> customPropertyMap = new HashMap<String, Object>();
private Class serviceInterface; private Class serviceInterface;
@ -228,16 +226,10 @@ public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
* @see javax.xml.rpc.Stub#_setProperty * @see javax.xml.rpc.Stub#_setProperty
* @see javax.xml.rpc.Call#setProperty * @see javax.xml.rpc.Call#setProperty
*/ */
public void setCustomPropertyMap(Map customProperties) { public void setCustomPropertyMap(Map<String, Object> customProperties) {
if (customProperties != null) { if (customProperties != null) {
Iterator it = customProperties.entrySet().iterator(); for (Map.Entry<String, Object> entry : customProperties.entrySet()) {
while (it.hasNext()) { addCustomProperty(entry.getKey(), entry.getValue());
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Illegal property key [" + entry.getKey() + "]: only Strings allowed");
}
addCustomProperty((String) entry.getKey(), entry.getValue());
} }
} }
} }
@ -249,7 +241,7 @@ public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
* "customPropertyMap[myKey]". This is particularly useful for * "customPropertyMap[myKey]". This is particularly useful for
* adding or overriding entries in child bean definitions. * adding or overriding entries in child bean definitions.
*/ */
public Map getCustomPropertyMap() { public Map<String, Object> getCustomPropertyMap() {
return this.customPropertyMap; return this.customPropertyMap;
} }
@ -513,9 +505,8 @@ public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
} }
if (this.customPropertyMap != null) { if (this.customPropertyMap != null) {
for (Iterator it = this.customPropertyMap.keySet().iterator(); it.hasNext();) { for (Map.Entry<String, Object> entry : this.customPropertyMap.entrySet()) {
String key = (String) it.next(); stub._setProperty(entry.getKey(), entry.getValue());
stub._setProperty(key, this.customPropertyMap.get(key));
} }
} }
} }
@ -687,9 +678,8 @@ public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
call.setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); call.setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
} }
if (this.customPropertyMap != null) { if (this.customPropertyMap != null) {
for (Iterator it = this.customPropertyMap.keySet().iterator(); it.hasNext();) { for (Map.Entry<String, Object> entry : this.customPropertyMap.entrySet()) {
String key = (String) it.next(); call.setProperty(entry.getKey(), entry.getValue());
call.setProperty(key, this.customPropertyMap.get(key));
} }
} }
} }
@ -750,8 +740,8 @@ public class JaxRpcPortClientInterceptor extends LocalJaxRpcServiceFactory
* @see org.springframework.remoting.rmi.RmiClientInterceptorUtils#isConnectFailure * @see org.springframework.remoting.rmi.RmiClientInterceptorUtils#isConnectFailure
*/ */
protected boolean isConnectFailure(RemoteException ex) { protected boolean isConnectFailure(RemoteException ex) {
return (ex.getClass().getName().indexOf("Fault") == -1 && return (!ex.getClass().getName().contains("Fault") &&
ex.getClass().getSuperclass().getName().indexOf("Fault") == -1); !ex.getClass().getSuperclass().getName().contains("Fault"));
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,10 +18,8 @@ package org.springframework.remoting.jaxrpc.support;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
import javax.xml.rpc.Service; import javax.xml.rpc.Service;
import javax.xml.rpc.encoding.TypeMapping; import javax.xml.rpc.encoding.TypeMapping;
@ -62,7 +60,7 @@ public class AxisBeanMappingServicePostProcessor implements JaxRpcServicePostPro
private String typeNamespaceUri; private String typeNamespaceUri;
private Map beanMappings; private Map<Object, String> beanMappings;
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
@ -95,7 +93,7 @@ public class AxisBeanMappingServicePostProcessor implements JaxRpcServicePostPro
*/ */
public void setBeanMappings(Properties beanMappingProps) { public void setBeanMappings(Properties beanMappingProps) {
if (beanMappingProps != null) { if (beanMappingProps != null) {
this.beanMappings = new HashMap(beanMappingProps.size()); this.beanMappings = new HashMap<Object, String>(beanMappingProps.size());
Enumeration propertyNames = beanMappingProps.propertyNames(); Enumeration propertyNames = beanMappingProps.propertyNames();
while (propertyNames.hasMoreElements()) { while (propertyNames.hasMoreElements()) {
String javaTypeName = (String) propertyNames.nextElement(); String javaTypeName = (String) propertyNames.nextElement();
@ -115,9 +113,8 @@ public class AxisBeanMappingServicePostProcessor implements JaxRpcServicePostPro
*/ */
public void setBeanClasses(Class[] beanClasses) { public void setBeanClasses(Class[] beanClasses) {
if (beanClasses != null) { if (beanClasses != null) {
this.beanMappings = new HashMap(beanClasses.length); this.beanMappings = new HashMap<Object, String>(beanClasses.length);
for (int i = 0; i < beanClasses.length; i++) { for (Class beanClass : beanClasses) {
Class beanClass = beanClasses[i];
String wsdlTypeName = ClassUtils.getShortName(beanClass); String wsdlTypeName = ClassUtils.getShortName(beanClass);
this.beanMappings.put(beanClass, wsdlTypeName); this.beanMappings.put(beanClass, wsdlTypeName);
} }
@ -142,9 +139,7 @@ public class AxisBeanMappingServicePostProcessor implements JaxRpcServicePostPro
public void postProcessJaxRpcService(Service service) { public void postProcessJaxRpcService(Service service) {
TypeMappingRegistry registry = service.getTypeMappingRegistry(); TypeMappingRegistry registry = service.getTypeMappingRegistry();
TypeMapping mapping = registry.createTypeMapping(); TypeMapping mapping = registry.createTypeMapping();
registerBeanMappings(mapping); registerBeanMappings(mapping);
if (this.encodingStyleUri != null) { if (this.encodingStyleUri != null) {
registry.register(this.encodingStyleUri, mapping); registry.register(this.encodingStyleUri, mapping);
} }
@ -161,18 +156,10 @@ public class AxisBeanMappingServicePostProcessor implements JaxRpcServicePostPro
*/ */
protected void registerBeanMappings(TypeMapping mapping) { protected void registerBeanMappings(TypeMapping mapping) {
if (this.beanMappings != null) { if (this.beanMappings != null) {
for (Iterator it = this.beanMappings.entrySet().iterator(); it.hasNext();) { for (Map.Entry<Object, String> entry : this.beanMappings.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); Class javaType = (entry.getKey() instanceof Class ? (Class) entry.getKey() :
Object key = entry.getKey(); ClassUtils.resolveClassName(entry.getKey().toString(), this.beanClassLoader));
Class javaType = null; registerBeanMapping(mapping, javaType, entry.getValue());
if (key instanceof Class) {
javaType = (Class) key;
}
else {
javaType = ClassUtils.resolveClassName((String) key, this.beanClassLoader);
}
String wsdlTypeName = (String) entry.getValue();
registerBeanMapping(mapping, javaType, wsdlTypeName);
} }
} }
} }

View File

@ -94,6 +94,15 @@
<option name="LABEL_INDENT_SIZE" value="0" /> <option name="LABEL_INDENT_SIZE" value="0" />
<option name="LABEL_INDENT_ABSOLUTE" value="false" /> <option name="LABEL_INDENT_ABSOLUTE" value="false" />
</ADDITIONAL_INDENT_OPTIONS> </ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="groovy">
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="8" />
<option name="TAB_SIZE" value="4" />
<option name="USE_TAB_CHARACTER" value="false" />
<option name="SMART_TABS" value="false" />
<option name="LABEL_INDENT_SIZE" value="0" />
<option name="LABEL_INDENT_ABSOLUTE" value="false" />
</ADDITIONAL_INDENT_OPTIONS>
<ADDITIONAL_INDENT_OPTIONS fileType="gsp"> <ADDITIONAL_INDENT_OPTIONS fileType="gsp">
<option name="INDENT_SIZE" value="2" /> <option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="8" /> <option name="CONTINUATION_INDENT_SIZE" value="8" />