Java 5 code style

This commit is contained in:
Juergen Hoeller 2008-11-27 00:27:52 +00:00
parent 6bbc966a21
commit b0790bf5e7
248 changed files with 2374 additions and 3208 deletions

View File

@ -74,7 +74,7 @@ import org.springframework.util.StringUtils;
public class AspectJExpressionPointcut extends AbstractExpressionPointcut
implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware {
private static final Set DEFAULT_SUPPORTED_PRIMITIVES = new HashSet();
private static final Set<PointcutPrimitive> DEFAULT_SUPPORTED_PRIMITIVES = new HashSet<PointcutPrimitive>();
static {
DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION);
@ -92,7 +92,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
private static final Log logger = LogFactory.getLog(AspectJExpressionPointcut.class);
private final Map shadowMapCache = new HashMap();
private final Map<Method, ShadowMatch> shadowMatchCache = new HashMap<Method, ShadowMatch>();
private PointcutParser pointcutParser;
@ -364,8 +364,8 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
private ShadowMatch getShadowMatch(Method targetMethod, Method originalMethod) {
synchronized (this.shadowMapCache) {
ShadowMatch shadowMatch = (ShadowMatch) this.shadowMapCache.get(targetMethod);
synchronized (this.shadowMatchCache) {
ShadowMatch shadowMatch = this.shadowMatchCache.get(targetMethod);
if (shadowMatch == null) {
try {
shadowMatch = this.pointcutExpression.matchesMethodExecution(targetMethod);
@ -378,7 +378,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
shadowMatch = this.pointcutExpression.matchesMethodExecution(originalMethod);
}
this.shadowMapCache.put(targetMethod, shadowMatch);
this.shadowMatchCache.put(targetMethod, shadowMatch);
}
return shadowMatch;
}
@ -520,8 +520,8 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
if (beanFactory != null) {
String[] aliases = beanFactory.getAliases(advisedBeanName);
for (int i = 0; i < aliases.length; i++) {
if (this.expressionPattern.matches(aliases[i])) {
for (String alias : aliases) {
if (this.expressionPattern.matches(alias)) {
return true;
}
}

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");
* you may not use this file except in compliance with the License.
@ -48,7 +48,7 @@ import org.springframework.util.ClassUtils;
public class AspectJProxyFactory extends ProxyCreatorSupport {
/** Cache for singleton aspect instances */
private static final Map aspectCache = new HashMap();
private static final Map<Class, Object> aspectCache = new HashMap<Class, Object>();
private final AspectJAdvisorFactory aspectFactory = new ReflectiveAspectJAdvisorFactory();
@ -199,6 +199,7 @@ public class AspectJProxyFactory extends ProxyCreatorSupport {
* (if necessary for proxy creation).
* @return the new proxy
*/
@SuppressWarnings("unchecked")
public <T> T getProxy() {
return (T) createAopProxy().getProxy();
}
@ -211,6 +212,7 @@ public class AspectJProxyFactory extends ProxyCreatorSupport {
* @param classLoader the class loader to create the proxy with
* @return the new proxy
*/
@SuppressWarnings("unchecked")
public <T> T getProxy(ClassLoader classLoader) {
return (T) createAopProxy().getProxy(classLoader);
}

View File

@ -142,8 +142,8 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig
ProxyFactory proxyFactory = new ProxyFactory();
if (this.preInterceptors != null) {
for (int i = 0; i < this.preInterceptors.length; i++) {
proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(this.preInterceptors[i]));
for (Object interceptor : this.preInterceptors) {
proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
}
}
@ -151,8 +151,8 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig
proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainInterceptor()));
if (this.postInterceptors != null) {
for (int i = 0; i < this.postInterceptors.length; i++) {
proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(this.postInterceptors[i]));
for (Object interceptor : this.postInterceptors) {
proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(interceptor));
}
}
@ -170,7 +170,7 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig
ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), this.proxyClassLoader));
}
this.proxy = getProxy(proxyFactory);
this.proxy = proxyFactory.getProxy(this.proxyClassLoader);
}
/**
@ -188,19 +188,6 @@ public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig
}
}
/**
* Return the proxy object to expose.
* <p>The default implementation uses a <code>getProxy</code> call with
* the factory's bean class loader. Can be overridden to specify a
* custom class loader.
* @param aopProxy the prepared AopProxy instance to get the proxy from
* @return the proxy object to expose
* @see AopProxy#getProxy(ClassLoader)
*/
protected Object getProxy(AopProxy aopProxy) {
return aopProxy.getProxy(this.proxyClassLoader);
}
public Object getObject() {
if (this.proxy == null) {

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");
* you may not use this file except in compliance with the License.
@ -362,7 +362,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
* <p>Use with care, and remember to {@link #updateAdvisorArray() refresh the advisor array}
* and {@link #adviceChanged() fire advice changed events} when making any modifications.
*/
protected final List getAdvisorsInternal() {
protected final List<Advisor> getAdvisorsInternal() {
return this.advisors;
}
@ -454,7 +454,7 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
* @param targetClass the target class
* @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers)
*/
public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) {
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) {
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {

View File

@ -90,7 +90,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
protected final static Log logger = LogFactory.getLog(Cglib2AopProxy.class);
/** Keeps track of the Classes that we have validated for final methods */
private static final Map validatedClasses = new WeakHashMap();
private static final Map<Class, Boolean> validatedClasses = new WeakHashMap<Class, Boolean>();
/** The configuration used to configure this proxy */
@ -103,7 +103,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
/** Dispatcher used for methods on Advised */
private final transient AdvisedDispatcher advisedDispatcher;
private transient Map fixedInterceptorMap;
private transient Map<String, Integer> fixedInterceptorMap;
private transient int fixedInterceptorOffset;
@ -158,8 +158,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
if (AopUtils.isCglibProxyClass(rootClass)) {
proxySuperClass = rootClass.getSuperclass();
Class[] additionalInterfaces = rootClass.getInterfaces();
for (int i = 0; i < additionalInterfaces.length; i++) {
Class additionalInterface = additionalInterfaces[i];
for (Class additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}
@ -250,8 +249,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
*/
private void doValidateClass(Class proxySuperClass) {
Method[] methods = proxySuperClass.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
for (Method method : methods) {
if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) {
logger.warn("Unable to proxy method [" + method + "] because it is final: " +
"All calls to this method via a proxy will be routed directly to the proxy.");
@ -271,22 +269,21 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
// Choose a "straight to target" interceptor. (used for calls that are
// unadvised but can return this). May be required to expose the proxy.
Callback targetInterceptor = null;
if (exposeProxy) {
targetInterceptor = isStatic ?
(Callback) new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
(Callback) new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
}
else {
targetInterceptor = isStatic ?
(Callback) new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
(Callback) new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
}
// Choose a "direct to target" dispatcher (used for
// unadvised calls to static targets that cannot return this).
Callback targetDispatcher = isStatic ?
(Callback) new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();
Callback[] mainCallbacks = new Callback[]{
aopInterceptor, // for normal advice
@ -305,29 +302,26 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
if (isStatic && isFrozen) {
Method[] methods = rootClass.getMethods();
Callback[] fixedCallbacks = new Callback[methods.length];
this.fixedInterceptorMap = new HashMap(methods.length);
this.fixedInterceptorMap = new HashMap<String, Integer>(methods.length);
// TODO: small memory optimisation here (can skip creation for
// methods with no advice)
for (int x = 0; x < methods.length; x++) {
List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
this.fixedInterceptorMap.put(methods[x].toString(), new Integer(x));
this.fixedInterceptorMap.put(methods[x].toString(), x);
}
// Now copy both the callbacks from mainCallbacks
// and fixedCallbacks into the callbacks array.
callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
for (int x = 0; x < mainCallbacks.length; x++) {
callbacks[x] = mainCallbacks[x];
}
for (int x = 0; x < fixedCallbacks.length; x++) {
callbacks[x + mainCallbacks.length] = fixedCallbacks[x];
}
this.fixedInterceptorOffset = mainCallbacks.length;
}
else {
@ -523,20 +517,19 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
Object other = args[0];
if (proxy == other) {
return Boolean.TRUE;
return true;
}
AdvisedSupport otherAdvised = null;
if (other instanceof Factory) {
Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
if (!(callback instanceof EqualsInterceptor)) {
return Boolean.FALSE;
return false;
}
otherAdvised = ((EqualsInterceptor) callback).advised;
AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
}
else {
return Boolean.FALSE;
return false;
}
return (AopProxyUtils.equalsInProxy(this.advised, otherAdvised) ? Boolean.TRUE : Boolean.FALSE);
}
}
@ -554,7 +547,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
}
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
return new Integer(Cglib2AopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode());
return Cglib2AopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode();
}
}
@ -564,24 +557,23 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
*/
private static class FixedChainStaticTargetInterceptor implements MethodInterceptor, Serializable {
private final List adviceChain;
private final List<Object> adviceChain;
private final Object target;
private final Class targetClass;
public FixedChainStaticTargetInterceptor(List adviceChain, Object target, Class targetClass) {
public FixedChainStaticTargetInterceptor(List<Object> adviceChain, Object target, Class targetClass) {
this.adviceChain = adviceChain;
this.target = target;
this.targetClass = targetClass;
}
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object retVal = null;
MethodInvocation invocation = new CglibMethodInvocation(proxy, this.target, method, args,
this.targetClass, this.adviceChain, methodProxy);
// If we get here, we need to create a MethodInvocation.
retVal = invocation.proceed();
Object retVal = invocation.proceed();
retVal = massageReturnTypeIfNecessary(proxy, this.target, method, retVal);
return retVal;
}
@ -601,13 +593,11 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
}
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
MethodInvocation invocation = null;
Object oldProxy = null;
boolean setProxyContext = false;
Class targetClass = null;
Object target = null;
try {
Object retVal = null;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
@ -619,7 +609,8 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
if (target != null) {
targetClass = target.getClass();
}
List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal = null;
// Check whether we only have one InvokerInterceptor: that is,
// no real advice, but just reflective invocation of the target.
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
@ -631,12 +622,8 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
}
else {
// We need to create a method invocation...
invocation = new CglibMethodInvocation(proxy, target, method, args,
targetClass, chain, methodProxy);
// If we get here, we need to create a MethodInvocation.
retVal = invocation.proceed();
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
retVal = massageReturnTypeIfNecessary(proxy, target, method, retVal);
return retVal;
}
@ -686,7 +673,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
private boolean protectedMethod;
public CglibMethodInvocation(Object proxy, Object target, Method method, Object[] arguments,
Class targetClass, List interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) {
Class targetClass, List<Object> interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) {
super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers);
this.methodProxy = methodProxy;
this.protectedMethod = Modifier.isProtected(method.getModifiers());
@ -715,11 +702,11 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
private final AdvisedSupport advised;
private final Map fixedInterceptorMap;
private final Map<String, Integer> fixedInterceptorMap;
private final int fixedInterceptorOffset;
public ProxyCallbackFilter(AdvisedSupport advised, Map fixedInterceptorMap, int fixedInterceptorOffset) {
public ProxyCallbackFilter(AdvisedSupport advised, Map<String, Integer> fixedInterceptorMap, int fixedInterceptorOffset) {
this.advised = advised;
this.fixedInterceptorMap = fixedInterceptorMap;
this.fixedInterceptorOffset = fixedInterceptorOffset;
@ -807,7 +794,7 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
}
// We know that we are optimising so we can use the
// FixedStaticChainInterceptors.
int index = ((Integer) this.fixedInterceptorMap.get(key)).intValue();
int index = this.fixedInterceptorMap.get(key);
return (index + this.fixedInterceptorOffset);
}
else {
@ -910,23 +897,17 @@ final class Cglib2AopProxy implements AopProxy, Serializable {
private boolean equalsPointcuts(Advisor a, Advisor b) {
// If only one of the advisor (but not both) is PointcutAdvisor, then it is a mismatch.
// Takes care of the situations where an IntroductionAdvisor is used (see SPR-3959).
if (a instanceof PointcutAdvisor ^ b instanceof PointcutAdvisor) {
return false;
}
// If both are PointcutAdvisor, match their pointcuts.
if (a instanceof PointcutAdvisor && b instanceof PointcutAdvisor) {
return ObjectUtils.nullSafeEquals(((PointcutAdvisor) a).getPointcut(), ((PointcutAdvisor) b).getPointcut());
}
// If neither is PointcutAdvisor, then from the pointcut matching perspective, it is a match.
return true;
return (!(a instanceof PointcutAdvisor) ||
(b instanceof PointcutAdvisor &&
ObjectUtils.nullSafeEquals(((PointcutAdvisor) a).getPointcut(), ((PointcutAdvisor) b).getPointcut())));
}
@Override
public int hashCode() {
int hashCode = 0;
Advisor[] advisors = this.advised.getAdvisors();
for (int i = 0; i < advisors.length; i++) {
Advice advice = advisors[i].getAdvice();
for (Advisor advisor : advisors) {
Advice advice = advisor.getAdvice();
if (advice != null) {
hashCode = 13 * hashCode + advice.getClass().hashCode();
}

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");
* you may not use this file except in compliance with the License.
@ -32,7 +32,7 @@ import org.springframework.util.ClassUtils;
* @author Rob Harrop
* @since 14.03.2003
*/
public class ProxyFactory extends ProxyCreatorSupport implements AopProxy {
public class ProxyFactory extends ProxyCreatorSupport {
/**
* Create a new ProxyFactory.
@ -93,8 +93,9 @@ public class ProxyFactory extends ProxyCreatorSupport implements AopProxy {
* (if necessary for proxy creation).
* @return the proxy object
*/
public Object getProxy() {
return createAopProxy().getProxy();
@SuppressWarnings("unchecked")
public <T> T getProxy() {
return (T) createAopProxy().getProxy();
}
/**
@ -106,8 +107,9 @@ public class ProxyFactory extends ProxyCreatorSupport implements AopProxy {
* (or <code>null</code> for the low-level proxy facility's default)
* @return the proxy object
*/
public Object getProxy(ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
@SuppressWarnings("unchecked")
public <T> T getProxy(ClassLoader classLoader) {
return (T) createAopProxy().getProxy(classLoader);
}

View File

@ -433,8 +433,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
}
// Materialize interceptor chain from bean names.
for (int i = 0; i < this.interceptorNames.length; i++) {
String name = this.interceptorNames[i];
for (String name : this.interceptorNames) {
if (logger.isTraceEnabled()) {
logger.trace("Configuring advisor or advice '" + name + "'");
}
@ -452,16 +451,16 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
// If we get here, we need to add a named interceptor.
// We must check if it's a singleton or prototype.
Object advice = null;
if (this.singleton || this.beanFactory.isSingleton(this.interceptorNames[i])) {
if (this.singleton || this.beanFactory.isSingleton(name)) {
// Add the real Advisor/Advice to the chain.
advice = this.beanFactory.getBean(this.interceptorNames[i]);
advice = this.beanFactory.getBean(name);
}
else {
// It's a prototype Advice or Advisor: replace with a prototype.
// Avoid unnecessary creation of prototype bean just for advisor chain initialization.
advice = new PrototypePlaceholderAdvisor(this.interceptorNames[i]);
advice = new PrototypePlaceholderAdvisor(name);
}
addAdvisorOnChainCreation(advice, this.interceptorNames[i]);
addAdvisorOnChainCreation(advice, name);
}
}
}
@ -477,11 +476,10 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
*/
private List freshAdvisorChain() {
Advisor[] advisors = getAdvisors();
List freshAdvisors = new ArrayList(advisors.length);
for (int i = 0; i < advisors.length; i++) {
if (advisors[i] instanceof PrototypePlaceholderAdvisor) {
PrototypePlaceholderAdvisor pa = (PrototypePlaceholderAdvisor) advisors[i];
List<Advisor> freshAdvisors = new ArrayList<Advisor>(advisors.length);
for (Advisor advisor : advisors) {
if (advisor instanceof PrototypePlaceholderAdvisor) {
PrototypePlaceholderAdvisor pa = (PrototypePlaceholderAdvisor) advisor;
if (logger.isDebugEnabled()) {
logger.debug("Refreshing bean named '" + pa.getBeanName() + "'");
}
@ -497,7 +495,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
}
else {
// Add the shared instance.
freshAdvisors.add(advisors[i]);
freshAdvisors.add(advisor);
}
}
return freshAdvisors;
@ -511,24 +509,21 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Advisor.class);
String[] globalInterceptorNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Interceptor.class);
List beans = new ArrayList(globalAdvisorNames.length + globalInterceptorNames.length);
Map names = new HashMap();
for (int i = 0; i < globalAdvisorNames.length; i++) {
String name = globalAdvisorNames[i];
List<Object> beans = new ArrayList<Object>(globalAdvisorNames.length + globalInterceptorNames.length);
Map<Object, String> names = new HashMap<Object, String>(beans.size());
for (String name : globalAdvisorNames) {
Object bean = beanFactory.getBean(name);
beans.add(bean);
names.put(bean, name);
}
for (int i = 0; i < globalInterceptorNames.length; i++) {
String name = globalInterceptorNames[i];
for (String name : globalInterceptorNames) {
Object bean = beanFactory.getBean(name);
beans.add(bean);
names.put(bean, name);
}
Collections.sort(beans, new OrderComparator());
for (Iterator it = beans.iterator(); it.hasNext();) {
Object bean = it.next();
String name = (String) names.get(bean);
for (Object bean : beans) {
String name = names.get(bean);
if (name.startsWith(prefix)) {
addAdvisorOnChainCreation(bean, name);
}
@ -551,7 +546,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
if (logger.isTraceEnabled()) {
logger.trace("Adding advisor with name '" + name + "'");
}
addAdvisor((Advisor) advisor);
addAdvisor(advisor);
}
/**

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");
* you may not use this file except in compliance with the License.
@ -72,7 +72,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
/**
* Lazily initialized map of user-specific attributes for this invocation.
*/
private Map userAttributes;
private Map<String, Object> userAttributes;
/**
* List of MethodInterceptor and InterceptorAndDynamicMethodMatcher
@ -102,7 +102,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
*/
protected ReflectiveMethodInvocation(
Object proxy, Object target, Method method, Object[] arguments,
Class targetClass, List interceptorsAndDynamicMethodMatchers) {
Class targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {
this.proxy = proxy;
this.target = target;
@ -213,7 +213,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
// Force initialization of the user attributes Map,
// for having a shared Map reference in the clone.
if (this.userAttributes == null) {
this.userAttributes = new HashMap();
this.userAttributes = new HashMap<String, Object>();
}
// Create the MethodInvocation clone.
@ -232,7 +232,7 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
public void setUserAttribute(String key, Object value) {
if (value != null) {
if (this.userAttributes == null) {
this.userAttributes = new HashMap();
this.userAttributes = new HashMap<String, Object>();
}
this.userAttributes.put(key, value);
}
@ -254,9 +254,9 @@ public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Clonea
* @return any user attributes associated with this invocation
* (never <code>null</code>)
*/
public Map getUserAttributes() {
public Map<String, Object> getUserAttributes() {
if (this.userAttributes == null) {
this.userAttributes = new HashMap();
this.userAttributes = new HashMap<String, Object>();
}
return this.userAttributes;
}

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");
* you may not use this file except in compliance with the License.
@ -61,7 +61,7 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
private final Object throwsAdvice;
/** Methods on throws advice, keyed by exception class */
private final Map exceptionHandlerMap = new HashMap();
private final Map<Class, Method> exceptionHandlerMap = new HashMap<Class, Method>();
/**
@ -75,10 +75,8 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
this.throwsAdvice = throwsAdvice;
Method[] methods = throwsAdvice.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
for (Method method : methods) {
if (method.getName().equals(AFTER_THROWING) &&
//m.getReturnType() == null &&
(method.getParameterTypes().length == 1 || method.getParameterTypes().length == 4) &&
Throwable.class.isAssignableFrom(method.getParameterTypes()[method.getParameterTypes().length - 1])
) {
@ -110,10 +108,10 @@ public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
if (logger.isTraceEnabled()) {
logger.trace("Trying to find handler for exception of type [" + exceptionClass.getName() + "]");
}
Method handler = (Method) this.exceptionHandlerMap.get(exceptionClass);
Method handler = this.exceptionHandlerMap.get(exceptionClass);
while (handler == null && !exceptionClass.equals(Throwable.class)) {
exceptionClass = exceptionClass.getSuperclass();
handler = (Method) this.exceptionHandlerMap.get(exceptionClass);
handler = this.exceptionHandlerMap.get(exceptionClass);
}
if (handler != null && logger.isDebugEnabled()) {
logger.debug("Found handler for exception of type [" + exceptionClass.getName() + "]: " + handler);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2087 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -56,7 +56,7 @@ public class DelegatePerTargetObjectIntroductionInterceptor extends Introduction
/**
* Hold weak references to keys as we don't want to interfere with garbage collection..
*/
private Map delegateMap = new WeakHashMap();
private final Map<Object, Object> delegateMap = new WeakHashMap<Object, Object>();
private Class defaultImplType;
@ -115,7 +115,7 @@ public class DelegatePerTargetObjectIntroductionInterceptor extends Introduction
}
private Object getIntroductionDelegateFor(Object targetObject) {
synchronized(this.delegateMap) {
synchronized (this.delegateMap) {
if (this.delegateMap.containsKey(targetObject)) {
return this.delegateMap.get(targetObject);
}

View File

@ -18,7 +18,6 @@ package org.springframework.aop.target;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.springframework.aop.IntroductionAdvisor;
@ -26,6 +25,7 @@ import org.springframework.aop.support.DefaultIntroductionAdvisor;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.core.NamedThreadLocal;
/**
* Alternative to an object pool. This TargetSource uses a threading model in which
@ -56,17 +56,13 @@ public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource
* thread. Unlike most ThreadLocals, which are static, this variable
* is meant to be per thread per instance of the ThreadLocalTargetSource class.
*/
private final ThreadLocal targetInThread = new ThreadLocal() {
@Override
public String toString() {
return "Thread-local instance of bean '" + getTargetBeanName() + "'";
}
};
private final ThreadLocal<Object> targetInThread =
new NamedThreadLocal<Object>("Thread-local instance of bean '" + getTargetBeanName() + "'");
/**
* Set of managed targets, enabling us to keep track of the targets we've created.
*/
private final Set targetSet = Collections.synchronizedSet(new HashSet());
private final Set<Object> targetSet = Collections.synchronizedSet(new HashSet<Object>());
private int invocationCount;
@ -104,8 +100,8 @@ public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource
public void destroy() {
logger.debug("Destroying ThreadLocalTargetSource bindings");
synchronized (this.targetSet) {
for (Iterator it = this.targetSet.iterator(); it.hasNext(); ) {
destroyPrototypeInstance(it.next());
for (Object target : this.targetSet) {
destroyPrototypeInstance(target);
}
this.targetSet.clear();
}

View File

@ -60,6 +60,32 @@ public abstract class BeanUtils {
Collections.synchronizedMap(new WeakHashMap<Class, Boolean>());
/**
* Convenience method to instantiate a class using its no-arg constructor.
* As this method doesn't try to load classes by name, it should avoid
* class-loading issues.
* <p>Note that this method tries to set the constructor accessible
* if given a non-accessible (that is, non-public) constructor.
* @param clazz class to instantiate
* @return the new instance
* @throws BeanInstantiationException if the bean cannot be instantiated
*/
public static <T> T instantiate(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
return clazz.newInstance();
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(clazz, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(clazz, "Is the constructor accessible?", ex);
}
}
/**
* Convenience method to instantiate a class using its no-arg constructor.
* As this method doesn't try to load classes by name, it should avoid
@ -106,7 +132,7 @@ public abstract class BeanUtils {
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor.getDeclaringClass(),
"Has the class definition changed? Is the constructor accessible?", ex);
"Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor.getDeclaringClass(),

View File

@ -100,7 +100,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
/**
* Map with cached nested BeanWrappers: nested path -> BeanWrapper instance.
*/
private Map nestedBeanWrappers;
private Map<String, BeanWrapperImpl> nestedBeanWrappers;
/**
@ -431,7 +431,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
*/
private BeanWrapperImpl getNestedBeanWrapper(String nestedProperty) {
if (this.nestedBeanWrappers == null) {
this.nestedBeanWrappers = new HashMap();
this.nestedBeanWrappers = new HashMap<String, BeanWrapperImpl>();
}
// Get value of bean property.
PropertyTokenHolder tokens = getPropertyNameTokens(nestedProperty);
@ -442,7 +442,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
}
// Lookup cached sub-BeanWrapper, create new one if not found.
BeanWrapperImpl nestedBw = (BeanWrapperImpl) this.nestedBeanWrappers.get(canonicalName);
BeanWrapperImpl nestedBw = this.nestedBeanWrappers.get(canonicalName);
if (nestedBw == null || nestedBw.getWrappedInstance() != propertyValue) {
if (logger.isTraceEnabled()) {
logger.trace("Creating new nested BeanWrapper for property '" + canonicalName + "'");
@ -805,7 +805,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
readMethod.setAccessible(true);
}
try {
oldValue = readMethod.invoke(this.object, new Object[0]);
oldValue = readMethod.invoke(this.object);
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
@ -816,13 +816,13 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra
}
valueToApply = this.typeConverterDelegate.convertIfNecessary(oldValue, originalValue, pd);
}
pv.getOriginalPropertyValue().conversionNecessary = Boolean.valueOf(valueToApply != originalValue);
pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
}
Method writeMethod = pd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(this.object, new Object[] {valueToApply});
writeMethod.invoke(this.object, valueToApply);
}
catch (InvocationTargetException ex) {
PropertyChangeEvent propertyChangeEvent =

View File

@ -46,7 +46,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor {
private final Object target;
private final Map fieldMap = new HashMap();
private final Map<String, Field> fieldMap = new HashMap<String, Field>();
private final TypeConverterDelegate typeConverterDelegate;
@ -79,7 +79,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor {
@Override
public Class getPropertyType(String propertyName) throws BeansException {
Field field = (Field) this.fieldMap.get(propertyName);
Field field = this.fieldMap.get(propertyName);
if (field != null) {
return field.getType();
}
@ -88,7 +88,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor {
@Override
public Object getPropertyValue(String propertyName) throws BeansException {
Field field = (Field) this.fieldMap.get(propertyName);
Field field = this.fieldMap.get(propertyName);
if (field == null) {
throw new NotReadablePropertyException(
this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist");
@ -104,7 +104,7 @@ public class DirectFieldAccessor extends AbstractPropertyAccessor {
@Override
public void setPropertyValue(String propertyName, Object newValue) throws BeansException {
Field field = (Field) this.fieldMap.get(propertyName);
Field field = this.fieldMap.get(propertyName);
if (field == null) {
throw new NotWritablePropertyException(
this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist");

View File

@ -16,6 +16,7 @@
package org.springframework.beans.factory;
import java.lang.annotation.Annotation;
import java.util.Map;
import org.springframework.beans.BeansException;
@ -210,4 +211,42 @@ $ * <p>Does not consider any hierarchy this factory may participate in.
<T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException;
/**
* Find all beans whose <code>Class</code> has the supplied {@link java.lang.annotation.Annotation} type.
* @param annotationType the type of annotation to look for
* @return a Map with the matching beans, containing the bean names as
* keys and the corresponding bean instances as values
* @throws BeansException if a bean could not be created
*/
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
throws BeansException;
/**
* Find all beans whose <code>Class</code> has the supplied {@link java.lang.annotation.Annotation} type.
* @param annotationType the type of annotation to look for
* @return a Map with the matching beans, containing the bean names as
* keys and the corresponding bean instances as values
* @param includeNonSingletons whether to include prototype or scoped beans too
* or just singletons (also applies to FactoryBeans)
* @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
* <i>objects created by FactoryBeans</i> (or by factory methods with a
* "factory-bean" reference) for the type check. Note that FactoryBeans need to be
* eagerly initialized to determine their type: So be aware that passing in "true"
* for this flag will initialize FactoryBeans and "factory-bean" references.
* @throws BeansException if a bean could not be created
*/
Map<String, Object> getBeansWithAnnotation(
Class<? extends Annotation> annotationType, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException;
/**
* Find a {@link Annotation} of <code>annotationType</code> on the specified
* bean, traversing its interfaces and super classes if no annotation can be
* found on the given class itself.
* @param beanName the name of the bean to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotation of the given type found, or <code>null</code>
*/
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType);
}

View File

@ -277,7 +277,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator {
protected static final Log logger = LogFactory.getLog(SingletonBeanFactoryLocator.class);
/** The keyed BeanFactory instances */
private static Map instances = new HashMap();
private static final Map<String, BeanFactoryLocator> instances = new HashMap<String, BeanFactoryLocator>();
/**
@ -324,7 +324,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator {
logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
instances.hashCode() + ", instances=" + instances);
}
BeanFactoryLocator bfl = (BeanFactoryLocator) instances.get(resourceLocation);
BeanFactoryLocator bfl = instances.get(resourceLocation);
if (bfl == null) {
bfl = new SingletonBeanFactoryLocator(resourceLocation);
instances.put(resourceLocation, bfl);
@ -335,9 +335,9 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator {
// We map BeanFactoryGroup objects by String keys, and by the definition object.
private final Map bfgInstancesByKey = new HashMap();
private final Map<String, BeanFactoryGroup> bfgInstancesByKey = new HashMap<String, BeanFactoryGroup>();
private final Map bfgInstancesByObj = new HashMap();
private final Map<BeanFactory, BeanFactoryGroup> bfgInstancesByObj = new HashMap<BeanFactory, BeanFactoryGroup>();
private final String resourceLocation;
@ -354,7 +354,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator {
public BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException {
synchronized (this.bfgInstancesByKey) {
BeanFactoryGroup bfg = (BeanFactoryGroup) this.bfgInstancesByKey.get(this.resourceLocation);
BeanFactoryGroup bfg = this.bfgInstancesByKey.get(this.resourceLocation);
if (bfg != null) {
bfg.refCount++;
@ -394,11 +394,10 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator {
try {
BeanFactory beanFactory = null;
if (factoryKey != null) {
beanFactory = (BeanFactory) bfg.definition.getBean(factoryKey, BeanFactory.class);
beanFactory = bfg.definition.getBean(factoryKey, BeanFactory.class);
}
else if (bfg.definition instanceof ListableBeanFactory) {
beanFactory = (BeanFactory)
BeanFactoryUtils.beanOfType((ListableBeanFactory) bfg.definition, BeanFactory.class);
beanFactory = BeanFactoryUtils.beanOfType((ListableBeanFactory) bfg.definition, BeanFactory.class);
}
else {
throw new IllegalStateException(
@ -518,7 +517,7 @@ public class SingletonBeanFactoryLocator implements BeanFactoryLocator {
BeanFactory savedRef = this.groupContextRef;
if (savedRef != null) {
this.groupContextRef = null;
BeanFactoryGroup bfg = (BeanFactoryGroup) bfgInstancesByObj.get(savedRef);
BeanFactoryGroup bfg = bfgInstancesByObj.get(savedRef);
if (bfg != null) {
bfg.refCount--;
if (bfg.refCount == 0) {

View File

@ -57,8 +57,8 @@ import org.springframework.util.ReflectionUtils;
* @see #setSingleton
* @see #createInstance()
*/
public abstract class AbstractFactoryBean
implements FactoryBean, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean {
public abstract class AbstractFactoryBean<T>
implements FactoryBean<T>, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
@ -71,9 +71,9 @@ public abstract class AbstractFactoryBean
private boolean initialized = false;
private Object singletonInstance;
private T singletonInstance;
private Object earlySingletonInstance;
private T earlySingletonInstance;
/**
@ -138,7 +138,7 @@ public abstract class AbstractFactoryBean
* @see #createInstance()
* @see #getEarlySingletonInterfaces()
*/
public final Object getObject() throws Exception {
public final T getObject() throws Exception {
if (isSingleton()) {
return (this.initialized ? this.singletonInstance : getEarlySingletonInstance());
}
@ -151,14 +151,15 @@ public abstract class AbstractFactoryBean
* Determine an 'eager singleton' instance, exposed in case of a
* circular reference. Not called in a non-circular scenario.
*/
private Object getEarlySingletonInstance() throws Exception {
@SuppressWarnings("unchecked")
private T getEarlySingletonInstance() throws Exception {
Class[] ifcs = getEarlySingletonInterfaces();
if (ifcs == null) {
throw new FactoryBeanNotInitializedException(
getClass().getName() + " does not support circular references");
}
if (this.earlySingletonInstance == null) {
this.earlySingletonInstance = Proxy.newProxyInstance(
this.earlySingletonInstance = (T) Proxy.newProxyInstance(
this.beanClassLoader, ifcs, new EarlySingletonInvocationHandler());
}
return this.earlySingletonInstance;
@ -169,7 +170,7 @@ public abstract class AbstractFactoryBean
* @return the singleton instance that this FactoryBean holds
* @throws IllegalStateException if the singleton instance is not initialized
*/
private Object getSingletonInstance() throws IllegalStateException {
private T getSingletonInstance() throws IllegalStateException {
if (!this.initialized) {
throw new IllegalStateException("Singleton instance not initialized yet");
}
@ -192,7 +193,7 @@ public abstract class AbstractFactoryBean
* interface, for a consistent offering of abstract template methods.
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
public abstract Class getObjectType();
public abstract Class<? extends T> getObjectType();
/**
* Template method that subclasses must override to construct
@ -203,7 +204,7 @@ public abstract class AbstractFactoryBean
* @throws Exception if an exception occured during object creation
* @see #getObject()
*/
protected abstract Object createInstance() throws Exception;
protected abstract T createInstance() throws Exception;
/**
* Return an array of interfaces that a singleton object exposed by this
@ -231,7 +232,7 @@ public abstract class AbstractFactoryBean
* @throws Exception in case of shutdown errors
* @see #createInstance()
*/
protected void destroyInstance(Object instance) throws Exception {
protected void destroyInstance(T instance) throws Exception {
}
@ -240,11 +241,11 @@ public abstract class AbstractFactoryBean
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (ReflectionUtils.isEqualsMethod(method)) {
// Only consider equal when proxies are identical.
return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
return (proxy == args[0]);
}
else if (ReflectionUtils.isHashCodeMethod(method)) {
// Use hashCode of reference proxy.
return new Integer(System.identityHashCode(proxy));
return System.identityHashCode(proxy);
}
else if (!initialized && ReflectionUtils.isToStringMethod(method)) {
return "Early singleton proxy for interfaces " +

View File

@ -32,7 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver;
* @see SetFactoryBean
* @see MapFactoryBean
*/
public class ListFactoryBean extends AbstractFactoryBean {
public class ListFactoryBean extends AbstractFactoryBean<List> {
private List sourceList;
@ -64,13 +64,13 @@ public class ListFactoryBean extends AbstractFactoryBean {
@Override
public Class getObjectType() {
public Class<List> getObjectType() {
return List.class;
}
@Override
@SuppressWarnings("unchecked")
protected Object createInstance() {
protected List createInstance() {
if (this.sourceList == null) {
throw new IllegalArgumentException("'sourceList' is required");
}

View File

@ -32,7 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver;
* @see SetFactoryBean
* @see ListFactoryBean
*/
public class MapFactoryBean extends AbstractFactoryBean {
public class MapFactoryBean extends AbstractFactoryBean<Map> {
private Map<?, ?> sourceMap;
@ -64,13 +64,13 @@ public class MapFactoryBean extends AbstractFactoryBean {
@Override
public Class getObjectType() {
public Class<Map> getObjectType() {
return Map.class;
}
@Override
@SuppressWarnings("unchecked")
protected Object createInstance() {
protected Map createInstance() {
if (this.sourceMap == null) {
throw new IllegalArgumentException("'sourceMap' is required");
}

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");
* you may not use this file except in compliance with the License.
@ -43,11 +43,11 @@ import org.springframework.core.io.support.PropertiesLoaderSupport;
* @see java.util.Properties
*/
public class PropertiesFactoryBean extends PropertiesLoaderSupport
implements FactoryBean, InitializingBean {
implements FactoryBean<Properties>, InitializingBean {
private boolean singleton = true;
private Object singletonInstance;
private Properties singletonInstance;
/**
@ -66,36 +66,21 @@ public class PropertiesFactoryBean extends PropertiesLoaderSupport
public final void afterPropertiesSet() throws IOException {
if (this.singleton) {
this.singletonInstance = createInstance();
this.singletonInstance = mergeProperties();
}
}
public final Object getObject() throws IOException {
public final Properties getObject() throws IOException {
if (this.singleton) {
return this.singletonInstance;
}
else {
return createInstance();
return mergeProperties();
}
}
public Class getObjectType() {
public Class<Properties> getObjectType() {
return Properties.class;
}
/**
* Template method that subclasses may override to construct the object
* returned by this factory. The default implementation returns the
* plain merged Properties instance.
* <p>Invoked on initialization of this FactoryBean in case of a
* shared singleton; else, on each {@link #getObject()} call.
* @return the object returned by this factory
* @throws IOException if an exception occured during properties loading
* @see #mergeProperties()
*/
protected Object createInstance() throws IOException {
return mergeProperties();
}
}

View File

@ -32,7 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver;
* @see ListFactoryBean
* @see MapFactoryBean
*/
public class SetFactoryBean extends AbstractFactoryBean {
public class SetFactoryBean extends AbstractFactoryBean<Set> {
private Set sourceSet;
@ -64,13 +64,13 @@ public class SetFactoryBean extends AbstractFactoryBean {
@Override
public Class getObjectType() {
public Class<Set> getObjectType() {
return Set.class;
}
@Override
@SuppressWarnings("unchecked")
protected Object createInstance() {
protected Set createInstance() {
if (this.sourceSet == null) {
throw new IllegalArgumentException("'sourceSet' is required");
}

View File

@ -1,140 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.generic;
import java.lang.annotation.Annotation;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
/**
* Simple wrapper around a {@link ListableBeanFactory} that provides typed, generics-based
* access to key methods. This removes the need for casting in many cases and should
* increase compile-time type safety.
*
* <p>Provides a simple mechanism for accessing all beans with a particular {@link Annotation}.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
*/
public class GenericBeanFactoryAccessor {
/**
* The {@link ListableBeanFactory} being wrapped.
*/
private final ListableBeanFactory beanFactory;
/**
* Constructs a <code>GenericBeanFactoryAccessor</code> that wraps the supplied {@link ListableBeanFactory}.
*/
public GenericBeanFactoryAccessor(ListableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "Bean factory must not be null");
this.beanFactory = beanFactory;
}
/**
* Return the wrapped {@link ListableBeanFactory}.
*/
public final ListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
/**
* @see org.springframework.beans.factory.BeanFactory#getBean(String)
*/
public <T> T getBean(String name) throws BeansException {
return (T) this.beanFactory.getBean(name);
}
/**
* @see org.springframework.beans.factory.BeanFactory#getBean(String, Class)
*/
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return (T) this.beanFactory.getBean(name, requiredType);
}
/**
* @see ListableBeanFactory#getBeansOfType(Class)
*/
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
return this.beanFactory.getBeansOfType(type);
}
/**
* @see ListableBeanFactory#getBeansOfType(Class, boolean, boolean)
*/
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
return this.beanFactory.getBeansOfType(type, includeNonSingletons, allowEagerInit);
}
/**
* Find all beans whose <code>Class</code> has the supplied {@link Annotation} type.
* @param annotationType the type of annotation to look for
* @return a Map with the matching beans, containing the bean names as
* keys and the corresponding bean instances as values
*/
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) {
Map<String, Object> results = new LinkedHashMap<String, Object>();
for (String beanName : this.beanFactory.getBeanNamesForType(Object.class)) {
if (findAnnotationOnBean(beanName, annotationType) != null) {
results.put(beanName, this.beanFactory.getBean(beanName));
}
}
return results;
}
/**
* Find a {@link Annotation} of <code>annotationType</code> on the specified
* bean, traversing its interfaces and super classes if no annotation can be
* found on the given class itself, as well as checking its raw bean class
* if not found on the exposed bean reference (e.g. in case of a proxy).
* @param beanName the name of the bean to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotation of the given type found, or <code>null</code>
* @see org.springframework.core.annotation.AnnotationUtils#findAnnotation(Class, Class)
*/
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
Class<?> handlerType = this.beanFactory.getType(beanName);
A ann = AnnotationUtils.findAnnotation(handlerType, annotationType);
if (ann == null && this.beanFactory instanceof ConfigurableBeanFactory &&
this.beanFactory.containsBeanDefinition(beanName)) {
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) this.beanFactory;
BeanDefinition bd = cbf.getMergedBeanDefinition(beanName);
if (bd instanceof AbstractBeanDefinition) {
AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
if (abd.hasBeanClass()) {
Class<?> beanClass = abd.getBeanClass();
ann = AnnotationUtils.findAnnotation(beanClass, annotationType);
}
}
}
return ann;
}
}

View File

@ -1,8 +0,0 @@
<html>
<body>
Support package for generic BeanFactory access,
leveraging Java 5 generics in the accessor API.
</body>
</html>

View File

@ -167,15 +167,15 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
//---------------------------------------------------------------------
public Object getBean(String name) throws BeansException {
return getBean(name, null, null);
return doGetBean(name, null, null, false);
}
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return getBean(name, requiredType, null);
return doGetBean(name, requiredType, null, false);
}
public Object getBean(String name, Object[] args) throws BeansException {
return getBean(name, null, args);
return doGetBean(name, null, args, false);
}
/**
@ -202,6 +202,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {

View File

@ -16,6 +16,7 @@
package org.springframework.beans.factory.support;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@ -43,6 +44,7 @@ import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
@ -327,6 +329,44 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return result;
}
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) {
return getBeansWithAnnotation(annotationType, true, true);
}
public Map<String, Object> getBeansWithAnnotation(
Class<? extends Annotation> annotationType, boolean includeNonSingletons, boolean allowEagerInit) {
Map<String, Object> results = new LinkedHashMap<String, Object>();
for (String beanName : getBeanNamesForType(Object.class, includeNonSingletons, allowEagerInit)) {
if (findAnnotationOnBean(beanName, annotationType) != null) {
results.put(beanName, getBean(beanName));
}
}
return results;
}
/**
* Find a {@link Annotation} of <code>annotationType</code> on the specified
* bean, traversing its interfaces and super classes if no annotation can be
* found on the given class itself, as well as checking its raw bean class
* if not found on the exposed bean reference (e.g. in case of a proxy).
*/
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
Class<?> handlerType = getType(beanName);
A ann = AnnotationUtils.findAnnotation(handlerType, annotationType);
if (ann == null && containsBeanDefinition(beanName)) {
BeanDefinition bd = getMergedBeanDefinition(beanName);
if (bd instanceof AbstractBeanDefinition) {
AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
if (abd.hasBeanClass()) {
Class<?> beanClass = abd.getBeanClass();
ann = AnnotationUtils.findAnnotation(beanClass, annotationType);
}
}
}
return ann;
}
//---------------------------------------------------------------------
// Implementation of ConfigurableListableBeanFactory interface

View File

@ -16,8 +16,10 @@
package org.springframework.beans.factory.support;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@ -30,6 +32,7 @@ import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;
/**
@ -95,9 +98,12 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
}
else {
return bean;
}
}
@SuppressWarnings("unchecked")
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
Object bean = getBean(name);
if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
@ -106,6 +112,7 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
return (T) bean;
}
@SuppressWarnings("unchecked")
public Object getBean(String name, Object[] args) throws BeansException {
if (args != null) {
throw new UnsupportedOperationException(
@ -203,6 +210,7 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
return getBeansOfType(type, true, true);
}
@SuppressWarnings("unchecked")
public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean includeFactoryBeans)
throws BeansException {
@ -238,4 +246,27 @@ public class StaticListableBeanFactory implements ListableBeanFactory {
return matches;
}
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
throws BeansException {
return getBeansWithAnnotation(annotationType, true, true);
}
public Map<String, Object> getBeansWithAnnotation(
Class<? extends Annotation> annotationType, boolean includeNonSingletons, boolean allowEagerInit) {
Map<String, Object> results = new LinkedHashMap<String, Object>();
for (String beanName : this.beans.keySet()) {
if (findAnnotationOnBean(beanName, annotationType) != null) {
results.put(beanName, getBean(beanName));
}
}
return results;
}
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
Class<?> handlerType = getType(beanName);
return AnnotationUtils.findAnnotation(handlerType, annotationType);
}
}

View File

@ -29,6 +29,7 @@ import org.springframework.beans.FatalBeanException;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
/**
* Default implementation of the {@link NamespaceHandlerResolver} interface.
@ -63,7 +64,7 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver
private final String handlerMappingsLocation;
/** Stores the mappings from namespace URI to NamespaceHandler class name / instance */
private Map handlerMappings;
private Map<String, NamespaceHandler> handlerMappings;
/**
@ -109,7 +110,7 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver
* @return the located {@link NamespaceHandler}, or <code>null</code> if none found
*/
public NamespaceHandler resolve(String namespaceUri) {
Map handlerMappings = getHandlerMappings();
Map<String, NamespaceHandler> handlerMappings = getHandlerMappings();
Object handlerOrClassName = handlerMappings.get(namespaceUri);
if (handlerOrClassName == null) {
return null;
@ -144,7 +145,7 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver
/**
* Load the specified NamespaceHandler mappings lazily.
*/
private Map getHandlerMappings() {
private Map<String, NamespaceHandler> getHandlerMappings() {
if (this.handlerMappings == null) {
try {
Properties mappings =
@ -152,7 +153,8 @@ public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver
if (logger.isDebugEnabled()) {
logger.debug("Loaded mappings [" + mappings + "]");
}
this.handlerMappings = new HashMap(mappings);
this.handlerMappings = new HashMap<String, NamespaceHandler>();
CollectionUtils.mergePropertiesIntoMap(mappings, this.handlerMappings);
}
catch (IOException ex) {
throw new IllegalStateException(

View File

@ -136,9 +136,7 @@ public class ArgumentConvertingMethodInvoker extends MethodInvoker {
Method[] candidates = ReflectionUtils.getAllDeclaredMethods(getTargetClass());
int minTypeDiffWeight = Integer.MAX_VALUE;
Object[] argumentsToUse = null;
for (int i = 0; i < candidates.length; i++) {
Method candidate = candidates[i];
for (Method candidate : candidates) {
if (candidate.getName().equals(targetMethod)) {
// Check if the inspected method has the correct number of parameters.
Class[] paramTypes = candidate.getParameterTypes();
@ -166,13 +164,11 @@ public class ArgumentConvertingMethodInvoker extends MethodInvoker {
}
}
}
if (matchingMethod != null) {
setArguments(argumentsToUse);
return matchingMethod;
}
}
return null;
}

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");
* you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.mail;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@ -33,7 +32,7 @@ import org.springframework.util.ObjectUtils;
*/
public class MailSendException extends MailException {
private transient Map failedMessages;
private transient final Map<Object, Exception> failedMessages;
private Exception[] messageExceptions;
@ -43,7 +42,7 @@ public class MailSendException extends MailException {
* @param msg the detail message
*/
public MailSendException(String msg) {
super(msg);
this(msg, null);
}
/**
@ -53,6 +52,7 @@ public class MailSendException extends MailException {
*/
public MailSendException(String msg, Throwable cause) {
super(msg, cause);
this.failedMessages = new LinkedHashMap<Object, Exception>();
}
/**
@ -63,10 +63,10 @@ public class MailSendException extends MailException {
* @param failedMessages Map of failed messages as keys and thrown
* exceptions as values
*/
public MailSendException(Map failedMessages) {
public MailSendException(Map<Object, Exception> failedMessages) {
super(null);
this.failedMessages = new LinkedHashMap(failedMessages);
this.messageExceptions = (Exception[]) failedMessages.values().toArray(new Exception[failedMessages.size()]);
this.failedMessages = new LinkedHashMap<Object, Exception>(failedMessages);
this.messageExceptions = failedMessages.values().toArray(new Exception[failedMessages.size()]);
}
@ -84,13 +84,12 @@ public class MailSendException extends MailException {
* <p><b>NOTE:</b> This Map will not be available after serialization.
* Use {@link #getMessageExceptions()} in such a scenario, which will
* be available after serialization as well.
* @return the Map of failed messages as keys and thrown exceptions as
* values, or an empty Map if no failed messages
* @return the Map of failed messages as keys and thrown exceptions as values
* @see SimpleMailMessage
* @see javax.mail.internet.MimeMessage
*/
public final Map getFailedMessages() {
return (this.failedMessages != null ? this.failedMessages : Collections.EMPTY_MAP);
public final Map<Object, Exception> getFailedMessages() {
return this.failedMessages;
}
/**
@ -112,7 +111,7 @@ public class MailSendException extends MailException {
return super.getMessage();
}
else {
StringBuffer sb = new StringBuffer("Failed messages: ");
StringBuilder sb = new StringBuilder("Failed messages: ");
for (int i = 0; i < this.messageExceptions.length; i++) {
Exception subEx = this.messageExceptions[i];
sb.append(subEx.toString());
@ -130,7 +129,7 @@ public class MailSendException extends MailException {
return super.toString();
}
else {
StringBuffer sb = new StringBuffer(getClass().getName());
StringBuilder sb = new StringBuilder(getClass().getName());
sb.append("; nested exceptions (").append(this.messageExceptions.length).append(") are:");
for (int i = 0; i < this.messageExceptions.length; i++) {
Exception subEx = this.messageExceptions[i];

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 use this file except in compliance with the License.
@ -201,7 +201,7 @@ public class SimpleMailMessage implements MailMessage, Serializable {
@Override
public String toString() {
StringBuffer sb = new StringBuffer("SimpleMailMessage: ");
StringBuilder sb = new StringBuilder("SimpleMailMessage: ");
sb.append("from=").append(this.from).append("; ");
sb.append("replyTo=").append(this.replyTo).append("; ");
sb.append("to=").append(StringUtils.arrayToCommaDelimitedString(this.to)).append("; ");

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");
* you may not use this file except in compliance with the License.
@ -298,14 +298,13 @@ public class JavaMailSenderImpl implements JavaMailSender {
}
public void send(SimpleMailMessage[] simpleMessages) throws MailException {
List mimeMessages = new ArrayList(simpleMessages.length);
for (int i = 0; i < simpleMessages.length; i++) {
SimpleMailMessage simpleMessage = simpleMessages[i];
List<MimeMessage> mimeMessages = new ArrayList<MimeMessage>(simpleMessages.length);
for (SimpleMailMessage simpleMessage : simpleMessages) {
MimeMailMessage message = new MimeMailMessage(createMimeMessage());
simpleMessage.copyTo(message);
mimeMessages.add(message.getMimeMessage());
}
doSend((MimeMessage[]) mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages);
doSend(mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages);
}
@ -348,13 +347,13 @@ public class JavaMailSenderImpl implements JavaMailSender {
public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException {
try {
List mimeMessages = new ArrayList(mimeMessagePreparators.length);
for (int i = 0; i < mimeMessagePreparators.length; i++) {
List<MimeMessage> mimeMessages = new ArrayList<MimeMessage>(mimeMessagePreparators.length);
for (MimeMessagePreparator preparator : mimeMessagePreparators) {
MimeMessage mimeMessage = createMimeMessage();
mimeMessagePreparators[i].prepare(mimeMessage);
preparator.prepare(mimeMessage);
mimeMessages.add(mimeMessage);
}
send((MimeMessage[]) mimeMessages.toArray(new MimeMessage[mimeMessages.size()]));
send(mimeMessages.toArray(new MimeMessage[mimeMessages.size()]));
}
catch (MailException ex) {
throw ex;
@ -383,7 +382,7 @@ public class JavaMailSenderImpl implements JavaMailSender {
* in case of failure when sending a message
*/
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
Map failedMessages = new LinkedHashMap();
Map<Object, Exception> failedMessages = new LinkedHashMap<Object, Exception>();
try {
Transport transport = getTransport(getSession());
transport.connect(getHost(), getPort(), getUsername(), getPassword());

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 use this file except in compliance with the License.
@ -19,7 +19,6 @@ package org.springframework.ui.velocity;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
@ -33,6 +32,7 @@ import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
@ -76,7 +76,7 @@ public class VelocityEngineFactory {
private Resource configLocation;
private final Map velocityProperties = new HashMap();
private final Map<String, Object> velocityProperties = new HashMap<String, Object>();
private String resourceLoaderPath;
@ -110,7 +110,7 @@ public class VelocityEngineFactory {
* @see #setResourceLoaderPath
*/
public void setVelocityProperties(Properties velocityProperties) {
setVelocityPropertiesMap(velocityProperties);
CollectionUtils.mergePropertiesIntoMap(velocityProperties, this.velocityProperties);
}
/**
@ -118,7 +118,7 @@ public class VelocityEngineFactory {
* like "ds.resource.loader.instance".
* @see #setVelocityProperties
*/
public void setVelocityPropertiesMap(Map velocityPropertiesMap) {
public void setVelocityPropertiesMap(Map<String, Object> velocityPropertiesMap) {
if (velocityPropertiesMap != null) {
this.velocityProperties.putAll(velocityPropertiesMap);
}
@ -214,14 +214,14 @@ public class VelocityEngineFactory {
*/
public VelocityEngine createVelocityEngine() throws IOException, VelocityException {
VelocityEngine velocityEngine = newVelocityEngine();
Properties props = new Properties();
Map<String, Object> props = new HashMap<String, Object>();
// Load config file if set.
if (this.configLocation != null) {
if (logger.isInfoEnabled()) {
logger.info("Loading Velocity config from [" + this.configLocation + "]");
}
PropertiesLoaderUtils.fillProperties(props, this.configLocation);
CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props);
}
// Merge local properties if set.
@ -240,13 +240,8 @@ public class VelocityEngineFactory {
}
// Apply properties to VelocityEngine.
for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Illegal property key [" + entry.getKey() + "]: only Strings allowed");
}
velocityEngine.setProperty((String) entry.getKey(), entry.getValue());
for (Map.Entry<String, Object> entry : props.entrySet()) {
velocityEngine.setProperty(entry.getKey(), entry.getValue());
}
postProcessVelocityEngine(velocityEngine);
@ -301,7 +296,7 @@ public class VelocityEngineFactory {
// Try to load via the file system, fall back to SpringResourceLoader
// (for hot detection of template changes, if possible).
try {
StringBuffer resolvedPath = new StringBuffer();
StringBuilder resolvedPath = new StringBuilder();
String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
for (int i = 0; i < paths.length; i++) {
String path = paths[i];

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");
* you may not use this file except in compliance with the License.
@ -54,7 +54,7 @@ public class ContextSingletonBeanFactoryLocator extends SingletonBeanFactoryLoca
private static final String DEFAULT_RESOURCE_LOCATION = "classpath*:beanRefContext.xml";
/** The keyed singleton instances */
private static final Map instances = new HashMap();
private static final Map<String, BeanFactoryLocator> instances = new HashMap<String, BeanFactoryLocator>();
/**
@ -101,7 +101,7 @@ public class ContextSingletonBeanFactoryLocator extends SingletonBeanFactoryLoca
logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" +
instances.hashCode() + ", instances=" + instances);
}
BeanFactoryLocator bfl = (BeanFactoryLocator) instances.get(resourceLocation);
BeanFactoryLocator bfl = instances.get(resourceLocation);
if (bfl == null) {
bfl = new ContextSingletonBeanFactoryLocator(resourceLocation);
instances.put(resourceLocation, bfl);

View File

@ -17,6 +17,7 @@
package org.springframework.context.support;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@ -907,8 +908,8 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
// Implementation of ListableBeanFactory interface
//---------------------------------------------------------------------
public boolean containsBeanDefinition(String name) {
return getBeanFactory().containsBeanDefinition(name);
public boolean containsBeanDefinition(String beanName) {
return getBeanFactory().containsBeanDefinition(beanName);
}
public int getBeanDefinitionCount() {
@ -937,6 +938,23 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
return getBeanFactory().getBeansOfType(type, includePrototypes, allowEagerInit);
}
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
throws BeansException {
return getBeanFactory().getBeansWithAnnotation(annotationType);
}
public Map<String, Object> getBeansWithAnnotation(
Class<? extends Annotation> annotationType, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
return getBeanFactory().getBeansWithAnnotation(annotationType, includeNonSingletons, allowEagerInit);
}
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
return getBeanFactory().findAnnotationOnBean(beanName, annotationType);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface

View File

@ -51,7 +51,7 @@ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements Smart
/** Cache for byte array per class name */
private final Map bytesCache = new HashMap();
private final Map<String, byte[]> bytesCache = new HashMap<String, byte[]>();
public ContextTypeMatchClassLoader(ClassLoader parent) {
@ -96,7 +96,7 @@ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements Smart
@Override
protected Class loadClassForOverriding(String name) throws ClassNotFoundException {
byte[] bytes = (byte[]) bytesCache.get(name);
byte[] bytes = bytesCache.get(name);
if (bytes == null) {
bytes = loadBytesForClass(name);
if (bytes != null) {

View File

@ -48,7 +48,7 @@ public abstract class MessageSourceSupport {
* Used for passed-in default messages. MessageFormats for resolved
* codes are cached on a specific basis in subclasses.
*/
private final Map cachedMessageFormats = new HashMap();
private final Map<String, MessageFormat> cachedMessageFormats = new HashMap<String, MessageFormat>();
/**
@ -94,7 +94,7 @@ public abstract class MessageSourceSupport {
}
MessageFormat messageFormat = null;
synchronized (this.cachedMessageFormats) {
messageFormat = (MessageFormat) this.cachedMessageFormats.get(msg);
messageFormat = this.cachedMessageFormats.get(msg);
if (messageFormat == null) {
messageFormat = createMessageFormat(msg, locale);
this.cachedMessageFormats.put(msg, messageFormat);

View File

@ -117,8 +117,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
/** Cache to hold already loaded properties per filename */
private final Map<String, PropertiesHolder> cachedProperties = new HashMap<String, PropertiesHolder>();
/** Cache to hold merged loaded properties per basename */
private final Map cachedMergedProperties = new HashMap();
/** Cache to hold merged loaded properties per locale */
private final Map<Locale, PropertiesHolder> cachedMergedProperties = new HashMap<Locale, PropertiesHolder>();
/**
@ -300,9 +300,8 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
}
else {
for (String basename : this.basenames) {
List filenames = calculateAllFilenames(basename, locale);
for (int j = 0; j < filenames.size(); j++) {
String filename = (String) filenames.get(j);
List<String> filenames = calculateAllFilenames(basename, locale);
for (String filename : filenames) {
PropertiesHolder propHolder = getProperties(filename);
MessageFormat result = propHolder.getMessageFormat(code, locale);
if (result != null) {
@ -325,7 +324,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractMessageSource
*/
protected PropertiesHolder getMergedProperties(Locale locale) {
synchronized (this.cachedMergedProperties) {
PropertiesHolder mergedHolder = (PropertiesHolder) this.cachedMergedProperties.get(locale);
PropertiesHolder mergedHolder = this.cachedMergedProperties.get(locale);
if (mergedHolder != null) {
return mergedHolder;
}

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");
* you may not use this file except in compliance with the License.
@ -69,7 +69,8 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement
* This allows for very efficient hash lookups, significantly faster
* than the ResourceBundle class's own cache.
*/
private final Map cachedResourceBundles = new HashMap();
private final Map<String, Map<Locale, ResourceBundle>> cachedResourceBundles =
new HashMap<String, Map<Locale, ResourceBundle>>();
/**
* Cache to hold already generated MessageFormats.
@ -79,7 +80,8 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement
* very efficient hash lookups without concatenated keys.
* @see #getMessageFormat
*/
private final Map cachedBundleMessageFormats = new HashMap();
private final Map<ResourceBundle, Map<String, Map<Locale, MessageFormat>>> cachedBundleMessageFormats =
new HashMap<ResourceBundle, Map<String, Map<Locale, MessageFormat>>>();
/**
@ -200,9 +202,9 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement
*/
protected ResourceBundle getResourceBundle(String basename, Locale locale) {
synchronized (this.cachedResourceBundles) {
Map localeMap = (Map) this.cachedResourceBundles.get(basename);
Map<Locale, ResourceBundle> localeMap = this.cachedResourceBundles.get(basename);
if (localeMap != null) {
ResourceBundle bundle = (ResourceBundle) localeMap.get(locale);
ResourceBundle bundle = localeMap.get(locale);
if (bundle != null) {
return bundle;
}
@ -210,7 +212,7 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement
try {
ResourceBundle bundle = doGetBundle(basename, locale);
if (localeMap == null) {
localeMap = new HashMap();
localeMap = new HashMap<Locale, ResourceBundle>();
this.cachedResourceBundles.put(basename, localeMap);
}
localeMap.put(locale, bundle);
@ -254,12 +256,12 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement
throws MissingResourceException {
synchronized (this.cachedBundleMessageFormats) {
Map codeMap = (Map) this.cachedBundleMessageFormats.get(bundle);
Map localeMap = null;
Map<String, Map<Locale, MessageFormat>> codeMap = this.cachedBundleMessageFormats.get(bundle);
Map<Locale, MessageFormat> localeMap = null;
if (codeMap != null) {
localeMap = (Map) codeMap.get(code);
localeMap = codeMap.get(code);
if (localeMap != null) {
MessageFormat result = (MessageFormat) localeMap.get(locale);
MessageFormat result = localeMap.get(locale);
if (result != null) {
return result;
}
@ -269,11 +271,11 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement
String msg = getStringOrNull(bundle, code);
if (msg != null) {
if (codeMap == null) {
codeMap = new HashMap();
codeMap = new HashMap<String, Map<Locale, MessageFormat>>();
this.cachedBundleMessageFormats.put(bundle, codeMap);
}
if (localeMap == null) {
localeMap = new HashMap();
localeMap = new HashMap<Locale, MessageFormat>();
codeMap.put(code, localeMap);
}
MessageFormat result = createMessageFormat(msg, locale);

View File

@ -1,100 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
/**
* FactoryBean that creates a Map with String keys and Resource values from
* properties, interpreting passed-in String values as resource locations.
*
* <p>Extends PropertiesFactoryBean to inherit the capability of defining
* local properties and loading from properties files.
*
* <p>Implements the ResourceLoaderAware interface to automatically use
* the context ResourceLoader if running in an ApplicationContext.
* Uses DefaultResourceLoader else.
*
* @author Juergen Hoeller
* @author Keith Donald
* @since 1.0.2
* @see org.springframework.core.io.DefaultResourceLoader
*/
public class ResourceMapFactoryBean extends PropertiesFactoryBean implements ResourceLoaderAware {
private String resourceBasePath = "";
private ResourceLoader resourceLoader = new DefaultResourceLoader();
/**
* Set a base path to prepend to each resource location value
* in the properties file.
* <p>E.g.: resourceBasePath="/images", value="/test.gif"
* -> location="/images/test.gif"
*/
public void setResourceBasePath(String resourceBasePath) {
this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
}
@Override
public Class getObjectType() {
return Map.class;
}
/**
* Create the Map instance, populated with keys and Resource values.
*/
@Override
protected Object createInstance() throws IOException {
Map resourceMap = new HashMap();
Properties props = mergeProperties();
for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
String location = props.getProperty(key);
resourceMap.put(key, getResource(location));
}
return resourceMap;
}
/**
* Fetch the Resource handle for the given location,
* prepeding the resource base path.
* @param location the resource location
* @return the Resource handle
* @see org.springframework.core.io.ResourceLoader#getResource(String)
*/
protected Resource getResource(String location) {
return this.resourceLoader.getResource(this.resourceBasePath + location);
}
}

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");
* you may not use this file except in compliance with the License.
@ -19,10 +19,8 @@ package org.springframework.jmx.export.assembler;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.management.modelmbean.ModelMBeanNotificationInfo;
import org.springframework.jmx.export.metadata.JmxMetadataUtils;
@ -41,7 +39,8 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
private ModelMBeanNotificationInfo[] notificationInfos;
private final Map notificationInfoMappings = new HashMap();
private final Map<String, ModelMBeanNotificationInfo[]> notificationInfoMappings =
new HashMap<String, ModelMBeanNotificationInfo[]>();
public void setNotificationInfos(ManagedNotification[] notificationInfos) {
@ -53,13 +52,8 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
this.notificationInfos = infos;
}
public void setNotificationInfoMappings(Map notificationInfoMappings) {
Iterator entries = notificationInfoMappings.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException("Property [notificationInfoMappings] only accepts Strings for Map keys");
}
public void setNotificationInfoMappings(Map<String, Object> notificationInfoMappings) {
for (Map.Entry<String, Object> entry : notificationInfoMappings.entrySet()) {
this.notificationInfoMappings.put(entry.getKey(), extractNotificationMetadata(entry.getValue()));
}
}
@ -68,16 +62,13 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
@Override
protected ModelMBeanNotificationInfo[] getNotificationInfo(Object managedBean, String beanKey) {
ModelMBeanNotificationInfo[] result = null;
if (StringUtils.hasText(beanKey)) {
result = (ModelMBeanNotificationInfo[]) this.notificationInfoMappings.get(beanKey);
result = this.notificationInfoMappings.get(beanKey);
}
if (result == null) {
result = this.notificationInfos;
}
return (result == null) ? new ModelMBeanNotificationInfo[0] : result;
return (result != null ? result : new ModelMBeanNotificationInfo[0]);
}
private ModelMBeanNotificationInfo[] extractNotificationMetadata(Object mapValue) {
@ -87,9 +78,8 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
}
else if (mapValue instanceof Collection) {
Collection col = (Collection) mapValue;
List result = new ArrayList();
for (Iterator iterator = col.iterator(); iterator.hasNext();) {
Object colValue = iterator.next();
List<ModelMBeanNotificationInfo> result = new ArrayList<ModelMBeanNotificationInfo>();
for (Object colValue : col) {
if (!(colValue instanceof ManagedNotification)) {
throw new IllegalArgumentException(
"Property 'notificationInfoMappings' only accepts ManagedNotifications for Map values");
@ -97,7 +87,7 @@ public abstract class AbstractConfigurableMBeanInfoAssembler extends AbstractRef
ManagedNotification mn = (ManagedNotification) colValue;
result.add(JmxMetadataUtils.convertToModelMBeanNotificationInfo(mn));
}
return (ModelMBeanNotificationInfo[]) result.toArray(new ModelMBeanNotificationInfo[result.size()]);
return result.toArray(new ModelMBeanNotificationInfo[result.size()]);
}
else {
throw new IllegalArgumentException(

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 use this file except in compliance with the License.
@ -88,10 +88,9 @@ public class InterfaceBasedMBeanInfoAssembler extends AbstractConfigurableMBeanI
*/
public void setManagedInterfaces(Class[] managedInterfaces) {
if (managedInterfaces != null) {
for (int x = 0; x < managedInterfaces.length; x++) {
if (!managedInterfaces[x].isInterface()) {
throw new IllegalArgumentException(
"Management interface [" + managedInterfaces[x].getName() + "] is no interface");
for (Class ifc : managedInterfaces) {
if (ifc.isInterface()) {
throw new IllegalArgumentException("Management interface [" + ifc.getName() + "] is no interface");
}
}
}
@ -126,7 +125,7 @@ public class InterfaceBasedMBeanInfoAssembler extends AbstractConfigurableMBeanI
* @return the resolved interface mappings (with Class objects as values)
*/
private Map resolveInterfaceMappings(Properties mappings) {
Map resolvedMappings = new HashMap(mappings.size());
Map<String, Class[]> resolvedMappings = new HashMap<String, Class[]>(mappings.size());
for (Enumeration en = mappings.propertyNames(); en.hasMoreElements();) {
String beanKey = (String) en.nextElement();
String[] classNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey));
@ -229,12 +228,10 @@ public class InterfaceBasedMBeanInfoAssembler extends AbstractConfigurableMBeanI
}
if (ifaces != null) {
for (int i = 0; i < ifaces.length; i++) {
Method[] methods = ifaces[i].getMethods();
for (int j = 0; j < methods.length; j++) {
Method ifaceMethod = methods[j];
if (ifaceMethod.getName().equals(method.getName()) &&
Arrays.equals(ifaceMethod.getParameterTypes(), method.getParameterTypes())) {
for (Class ifc : ifaces) {
for (Method ifcMethod : ifc.getMethods()) {
if (ifcMethod.getName().equals(method.getName()) &&
Arrays.equals(ifcMethod.getParameterTypes(), method.getParameterTypes())) {
return true;
}
}

View File

@ -57,9 +57,9 @@ import org.springframework.util.StringUtils;
*/
public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBeanInfoAssembler {
private Set ignoredMethods;
private Set<String> ignoredMethods;
private Map ignoredMethodMappings;
private Map<String, Set<String>> ignoredMethodMappings;
/**
@ -69,7 +69,7 @@ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBean
* @see #setIgnoredMethodMappings(java.util.Properties)
*/
public void setIgnoredMethods(String[] ignoredMethodNames) {
this.ignoredMethods = new HashSet(Arrays.asList(ignoredMethodNames));
this.ignoredMethods = new HashSet<String>(Arrays.asList(ignoredMethodNames));
}
/**
@ -80,11 +80,11 @@ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBean
* Spring will check these mappings first.
*/
public void setIgnoredMethodMappings(Properties mappings) {
this.ignoredMethodMappings = new HashMap();
this.ignoredMethodMappings = new HashMap<String, Set<String>>();
for (Enumeration en = mappings.keys(); en.hasMoreElements();) {
String beanKey = (String) en.nextElement();
String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey));
this.ignoredMethodMappings.put(beanKey, new HashSet(Arrays.asList(methodNames)));
this.ignoredMethodMappings.put(beanKey, new HashSet<String>(Arrays.asList(methodNames)));
}
}
@ -113,7 +113,7 @@ public class MethodExclusionMBeanInfoAssembler extends AbstractConfigurableMBean
*/
protected boolean isNotIgnored(Method method, String beanKey) {
if (this.ignoredMethodMappings != null) {
Set methodNames = (Set) this.ignoredMethodMappings.get(beanKey);
Set<String> methodNames = this.ignoredMethodMappings.get(beanKey);
if (methodNames != null) {
return !methodNames.contains(method.getName());
}

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");
* you may not use this file except in compliance with the License.
@ -57,12 +57,12 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean
/**
* Stores the set of method names to use for creating the management interface.
*/
private Set managedMethods;
private Set<String> managedMethods;
/**
* Stores the mappings of bean keys to an array of method names.
*/
private Map methodMappings;
private Map<String, Set<String>> methodMappings;
/**
@ -73,7 +73,7 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean
* @see #setMethodMappings
*/
public void setManagedMethods(String[] methodNames) {
this.managedMethods = new HashSet(Arrays.asList(methodNames));
this.managedMethods = new HashSet<String>(Arrays.asList(methodNames));
}
/**
@ -84,11 +84,11 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean
* @param mappings the mappins of bean keys to method names
*/
public void setMethodMappings(Properties mappings) {
this.methodMappings = new HashMap();
this.methodMappings = new HashMap<String, Set<String>>();
for (Enumeration en = mappings.keys(); en.hasMoreElements();) {
String beanKey = (String) en.nextElement();
String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey));
this.methodMappings.put(beanKey, new HashSet(Arrays.asList(methodNames)));
this.methodMappings.put(beanKey, new HashSet<String>(Arrays.asList(methodNames)));
}
}
@ -110,7 +110,7 @@ public class MethodNameBasedMBeanInfoAssembler extends AbstractConfigurableMBean
protected boolean isMatch(Method method, String beanKey) {
if (this.methodMappings != null) {
Set methodNames = (Set) this.methodMappings.get(beanKey);
Set<String> methodNames = this.methodMappings.get(beanKey);
if (methodNames != null) {
return methodNames.contains(method.getName());
}

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");
* you may not use this file except in compliance with the License.
@ -29,21 +29,21 @@ import javax.naming.NamingException;
* interface, as JndiTemplate provides all usual JNDI operations via
* convenience methods.
*
* @author Rod Johnson
* @see JndiTemplate
* @see org.springframework.jdbc.core.JdbcTemplate
* @author Rod Johnson
*/
public interface JndiCallback {
public interface JndiCallback<T> {
/**
* Do something with the given JNDI context.
* Implementations don't need to worry about error handling
* <p>Implementations don't need to worry about error handling
* or cleanup, as the JndiTemplate class will handle this.
* @param ctx the current JNDI context
* @throws NamingException if thrown by JNDI methods
* @return a result object, or <code>null</code>
*/
Object doInContext(Context ctx) throws NamingException;
T doInContext(Context ctx) throws NamingException;
}

View File

@ -87,10 +87,10 @@ public abstract class JndiLocatorSupport extends JndiAccessor {
* @throws NamingException if the JNDI lookup failed
* @see #setResourceRef
*/
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
protected <T> T lookup(String jndiName, Class<T> requiredType) throws NamingException {
Assert.notNull(jndiName, "'jndiName' must not be null");
String convertedName = convertJndiName(jndiName);
Object jndiObject = null;
T jndiObject = null;
try {
jndiObject = getJndiTemplate().lookup(convertedName, requiredType);
}

View File

@ -18,7 +18,6 @@ package org.springframework.jndi;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
@ -82,7 +81,7 @@ public class JndiTemplate {
* @throws NamingException thrown by the callback implementation
* @see #createInitialContext
*/
public Object execute(JndiCallback contextCallback) throws NamingException {
public <T> T execute(JndiCallback<T> contextCallback) throws NamingException {
Context ctx = getContext();
try {
return contextCallback.doInContext(ctx);
@ -174,13 +173,14 @@ public class JndiTemplate {
* @throws NamingException if there is no object with the given
* name bound to JNDI
*/
public Object lookup(String name, Class requiredType) throws NamingException {
@SuppressWarnings("unchecked")
public <T> T lookup(String name, Class<T> requiredType) throws NamingException {
Object jndiObject = lookup(name);
if (requiredType != null && !requiredType.isInstance(jndiObject)) {
throw new TypeMismatchNamingException(
name, requiredType, (jndiObject != null ? jndiObject.getClass() : null));
}
return jndiObject;
return (T) jndiObject;
}
/**

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");
* you may not use this file except in compliance with the License.
@ -60,13 +60,13 @@ import org.springframework.jndi.TypeMismatchNamingException;
public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFactory {
/** JNDI names of resources that are known to be shareable, i.e. can be cached */
private final Set shareableResources = new HashSet();
private final Set<String> shareableResources = new HashSet<String>();
/** Cache of shareable singleton objects: bean name --> bean instance */
private final Map singletonObjects = new HashMap();
private final Map<String, Object> singletonObjects = new HashMap<String, Object>();
/** Cache of the types of nonshareable resources: bean name --> bean type */
private final Map resourceTypes = new HashMap();
private final Map<String, Class> resourceTypes = new HashMap<String, Class>();
public SimpleJndiBeanFactory() {
@ -96,10 +96,10 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac
public Object getBean(String name) throws BeansException {
return getBean(name, (Class) null);
return getBean(name, Object.class);
}
public Object getBean(String name, Class requiredType) throws BeansException {
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
try {
if (isSingleton(name)) {
return doGetSingleton(name, requiredType);
@ -170,7 +170,8 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac
}
private Object doGetSingleton(String name, Class requiredType) throws NamingException {
@SuppressWarnings("unchecked")
private <T> T doGetSingleton(String name, Class<T> requiredType) throws NamingException {
synchronized (this.singletonObjects) {
if (this.singletonObjects.containsKey(name)) {
Object jndiObject = this.singletonObjects.get(name);
@ -178,9 +179,9 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac
throw new TypeMismatchNamingException(
convertJndiName(name), requiredType, (jndiObject != null ? jndiObject.getClass() : null));
}
return jndiObject;
return (T) jndiObject;
}
Object jndiObject = lookup(name, requiredType);
T jndiObject = lookup(name, requiredType);
this.singletonObjects.put(name, jndiObject);
return jndiObject;
}
@ -194,7 +195,7 @@ public class SimpleJndiBeanFactory extends JndiLocatorSupport implements BeanFac
else {
synchronized (this.resourceTypes) {
if (this.resourceTypes.containsKey(name)) {
return (Class) this.resourceTypes.get(name);
return this.resourceTypes.get(name);
}
else {
Object jndiObject = lookup(name, null);

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");
* you may not use this file except in compliance with the License.
@ -55,7 +55,7 @@ public class RemoteInvocation implements Serializable {
private Object[] arguments;
private Map attributes;
private Map<String, Serializable> attributes;
/**
@ -143,7 +143,7 @@ public class RemoteInvocation implements Serializable {
*/
public void addAttribute(String key, Serializable value) throws IllegalStateException {
if (this.attributes == null) {
this.attributes = new HashMap();
this.attributes = new HashMap<String, Serializable>();
}
if (this.attributes.containsKey(key)) {
throw new IllegalStateException("There is already an attribute with key '" + key + "' bound");
@ -162,7 +162,7 @@ public class RemoteInvocation implements Serializable {
if (this.attributes == null) {
return null;
}
return (Serializable) this.attributes.get(key);
return this.attributes.get(key);
}
/**
@ -172,7 +172,7 @@ public class RemoteInvocation implements Serializable {
* @see #addAttribute
* @see #getAttribute
*/
public void setAttributes(Map attributes) {
public void setAttributes(Map<String, Serializable> attributes) {
this.attributes = attributes;
}
@ -183,7 +183,7 @@ public class RemoteInvocation implements Serializable {
* @see #addAttribute
* @see #getAttribute
*/
public Map getAttributes() {
public Map<String, Serializable> getAttributes() {
return this.attributes;
}

View File

@ -34,7 +34,6 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.core.task.support.ConcurrentExecutorAdapter;
/**
* {@link org.springframework.beans.factory.FactoryBean} that creates a simple
@ -120,7 +119,7 @@ public class SimpleHttpServerFactoryBean implements FactoryBean, InitializingBea
* @see com.sun.net.httpserver.HttpServer#setExecutor
*/
public void setTaskExecutor(TaskExecutor executor) {
this.executor = new ConcurrentExecutorAdapter(executor);
this.executor = executor;
}
/**

View File

@ -42,16 +42,6 @@ import org.springframework.util.Assert;
*/
public class BindException extends Exception implements BindingResult {
/**
* Prefix for the name of the BindException instance in a model,
* followed by the object name.
* @deprecated in favor of <code>BindingResult.MODEL_KEY_PREFIX</code>
* @see BindingResult#MODEL_KEY_PREFIX
*/
@Deprecated
public static final String ERROR_KEY_PREFIX = BindException.class.getName() + ".";
private final BindingResult bindingResult;
@ -208,7 +198,7 @@ public class BindException extends Exception implements BindingResult {
return this.bindingResult.getTarget();
}
public Map getModel() {
public Map<String, Object> getModel() {
return this.bindingResult.getModel();
}

View File

@ -499,8 +499,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
*/
protected void checkAllowedFields(MutablePropertyValues mpvs) {
PropertyValue[] pvs = mpvs.getPropertyValues();
for (int i = 0; i < pvs.length; i++) {
PropertyValue pv = pvs[i];
for (PropertyValue pv : pvs) {
String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
if (!isAllowed(field)) {
mpvs.removePropertyValue(pv);
@ -545,16 +544,14 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
protected void checkRequiredFields(MutablePropertyValues mpvs) {
String[] requiredFields = getRequiredFields();
if (!ObjectUtils.isEmpty(requiredFields)) {
Map propertyValues = new HashMap();
Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
PropertyValue[] pvs = mpvs.getPropertyValues();
for (int i = 0; i < pvs.length; i++) {
PropertyValue pv = pvs[i];
for (PropertyValue pv : pvs) {
String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
propertyValues.put(canonicalName, pv);
}
for (int i = 0; i < requiredFields.length; i++) {
String field = requiredFields[i];
PropertyValue pv = (PropertyValue) propertyValues.get(field);
for (String field : requiredFields) {
PropertyValue pv = propertyValues.get(field);
if (pv == null || pv.getValue() == null ||
(pv.getValue() instanceof String && !StringUtils.hasText((String) pv.getValue()))) {
// Use bind error processor to create FieldError.
@ -589,9 +586,8 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
}
catch (PropertyBatchUpdateException ex) {
// Use bind error processor to create FieldErrors.
PropertyAccessException[] exs = ex.getPropertyAccessExceptions();
for (int i = 0; i < exs.length; i++) {
getBindingErrorProcessor().processPropertyAccessException(exs[i], getInternalBindingResult());
for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) {
getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult());
}
}
}

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");
* you may not use this file except in compliance with the License.
@ -19,7 +19,6 @@ package org.springframework.core;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.util.Assert;
@ -36,7 +35,7 @@ import org.springframework.util.Assert;
public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable {
/** Map with String keys and Object values */
private final Map attributes = new LinkedHashMap();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
public void setAttribute(String name, Object value) {
@ -65,8 +64,7 @@ public abstract class AttributeAccessorSupport implements AttributeAccessor, Ser
}
public String[] attributeNames() {
Set attributeNames = this.attributes.keySet();
return (String[]) attributeNames.toArray(new String[attributeNames.size()]);
return this.attributes.keySet().toArray(new String[this.attributes.size()]);
}
@ -77,8 +75,7 @@ public abstract class AttributeAccessorSupport implements AttributeAccessor, Ser
protected void copyAttributesFrom(AttributeAccessor source) {
Assert.notNull(source, "Source must not be null");
String[] attributeNames = source.attributeNames();
for (int i = 0; i < attributeNames.length; i++) {
String attributeName = attributeNames[i];
for (String attributeName : attributeNames) {
setAttribute(attributeName, source.getAttribute(attributeName));
}
}

View File

@ -64,10 +64,9 @@ public abstract class BridgeMethodResolver {
}
// Gather all methods with matching name and parameter size.
List candidateMethods = new ArrayList();
List<Method> candidateMethods = new ArrayList<Method>();
Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass());
for (int i = 0; i < methods.length; i++) {
Method candidateMethod = methods[i];
for (Method candidateMethod : methods) {
if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) {
candidateMethods.add(candidateMethod);
}
@ -76,7 +75,7 @@ public abstract class BridgeMethodResolver {
Method result;
// Now perform simple quick checks.
if (candidateMethods.size() == 1) {
result = (Method) candidateMethods.get(0);
result = candidateMethods.get(0);
}
else {
result = searchCandidates(candidateMethods, bridgeMethod);
@ -86,7 +85,6 @@ public abstract class BridgeMethodResolver {
throw new IllegalStateException(
"Unable to locate bridged method for bridge method '" + bridgeMethod + "'");
}
return result;
}
@ -96,10 +94,9 @@ public abstract class BridgeMethodResolver {
* @param bridgeMethod the bridge method
* @return the bridged method, or <code>null</code> if none found
*/
private static Method searchCandidates(List candidateMethods, Method bridgeMethod) {
Map typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass());
for (int i = 0; i < candidateMethods.size(); i++) {
Method candidateMethod = (Method) candidateMethods.get(i);
private static Method searchCandidates(List<Method> candidateMethods, Method bridgeMethod) {
Map<TypeVariable, Type> typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass());
for (Method candidateMethod : candidateMethods) {
if (isBridgeMethodFor(bridgeMethod, candidateMethod, typeParameterMap)) {
return candidateMethod;
}
@ -123,7 +120,7 @@ public abstract class BridgeMethodResolver {
* Determines whether or not the bridge {@link Method} is the bridge for the
* supplied candidate {@link Method}.
*/
static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map typeVariableMap) {
static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map<TypeVariable, Type> typeVariableMap) {
if (isResolvedTypeMatch(candidateMethod, bridgeMethod, typeVariableMap)) {
return true;
}
@ -149,9 +146,8 @@ public abstract class BridgeMethodResolver {
// Search interfaces.
Class[] interfaces = ClassUtils.getAllInterfacesForClass(bridgeMethod.getDeclaringClass());
for (int i = 0; i < interfaces.length; i++) {
Class anInterface = interfaces[i];
Method method = searchForMatch(anInterface, bridgeMethod);
for (Class ifc : interfaces) {
Method method = searchForMatch(ifc, bridgeMethod);
if (method != null && !method.isBridge()) {
return method;
}
@ -166,7 +162,9 @@ public abstract class BridgeMethodResolver {
* are equal after resolving all {@link TypeVariable TypeVariables} using the supplied
* TypeVariable Map, otherwise returns <code>false</code>.
*/
private static boolean isResolvedTypeMatch(Method genericMethod, Method candidateMethod, Map typeVariableMap) {
private static boolean isResolvedTypeMatch(
Method genericMethod, Method candidateMethod, Map<TypeVariable, Type> typeVariableMap) {
Type[] genericParameters = genericMethod.getGenericParameterTypes();
Class[] candidateParameters = candidateMethod.getParameterTypes();
if (genericParameters.length != candidateParameters.length) {

View File

@ -34,12 +34,8 @@ import java.util.Map;
* target type of values to be added to a collection or map
* (to be able to attempt type conversion if appropriate).
*
* <p>Only usable on Java 5. Use an appropriate {@link JdkVersion} check
* before calling this class, if a fallback for JDK 1.4 is desirable.
*
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.beans.BeanWrapper
*/
public abstract class GenericCollectionTypeResolver {
@ -283,7 +279,7 @@ public abstract class GenericCollectionTypeResolver {
Type resolvedType = type;
if (type instanceof TypeVariable && methodParam != null && methodParam.typeVariableMap != null) {
Type mappedType = (Type) methodParam.typeVariableMap.get(type);
Type mappedType = methodParam.typeVariableMap.get((TypeVariable) type);
if (mappedType != null) {
resolvedType = mappedType;
}
@ -322,7 +318,7 @@ public abstract class GenericCollectionTypeResolver {
int nextLevel = currentLevel + 1;
Integer currentTypeIndex = (methodParam != null ? methodParam.getTypeIndexForLevel(nextLevel) : null);
// Default is last parameter type: Collection element or Map value.
int indexToUse = (currentTypeIndex != null ? currentTypeIndex.intValue() : paramTypes.length - 1);
int indexToUse = (currentTypeIndex != null ? currentTypeIndex : paramTypes.length - 1);
Type paramType = paramTypes[indexToUse];
return extractType(methodParam, paramType, source, typeIndex, nestingLevel, nextLevel);
}
@ -339,7 +335,7 @@ public abstract class GenericCollectionTypeResolver {
}
Type paramType = paramTypes[typeIndex];
if (paramType instanceof TypeVariable && methodParam != null && methodParam.typeVariableMap != null) {
Type mappedType = (Type) methodParam.typeVariableMap.get(paramType);
Type mappedType = methodParam.typeVariableMap.get((TypeVariable) paramType);
if (mappedType != null) {
paramType = mappedType;
}
@ -399,8 +395,7 @@ public abstract class GenericCollectionTypeResolver {
}
Type[] ifcs = clazz.getGenericInterfaces();
if (ifcs != null) {
for (int i = 0; i < ifcs.length; i++) {
Type ifc = ifcs[i];
for (Type ifc : ifcs) {
Type rawType = ifc;
if (ifc instanceof ParameterizedType) {
rawType = ((ParameterizedType) ifc).getRawType();

View File

@ -34,9 +34,6 @@ import org.springframework.util.Assert;
* <p>Mainly intended for usage within the framework, resolving method
* parameter types even when they are declared generically.
*
* <p>Only usable on Java 5. Use an appropriate JdkVersion check before
* calling this class, if a fallback for JDK 1.4 is desirable.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 2.5.2
@ -46,7 +43,8 @@ import org.springframework.util.Assert;
public abstract class GenericTypeResolver {
/** Cache from Class to TypeVariable Map */
private static final Map typeVariableCache = Collections.synchronizedMap(new WeakHashMap());
private static final Map<Class, Map<TypeVariable, Type>> typeVariableCache =
Collections.synchronizedMap(new WeakHashMap<Class, Map<TypeVariable, Type>>());
/**
@ -78,7 +76,7 @@ public abstract class GenericTypeResolver {
public static Class resolveParameterType(MethodParameter methodParam, Class clazz) {
Type genericType = getTargetType(methodParam);
Assert.notNull(clazz, "Class must not be null");
Map typeVariableMap = getTypeVariableMap(clazz);
Map<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);
Type rawType = getRawType(genericType, typeVariableMap);
Class result = (rawType instanceof Class ? (Class) rawType : methodParam.getParameterType());
methodParam.setParameterType(result);
@ -96,7 +94,7 @@ public abstract class GenericTypeResolver {
Assert.notNull(method, "Method must not be null");
Type genericType = method.getGenericReturnType();
Assert.notNull(clazz, "Class must not be null");
Map typeVariableMap = getTypeVariableMap(clazz);
Map<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);
Type rawType = getRawType(genericType, typeVariableMap);
return (rawType instanceof Class ? (Class) rawType : method.getReturnType());
}
@ -108,7 +106,7 @@ public abstract class GenericTypeResolver {
* @param typeVariableMap the TypeVariable Map to resolved against
* @return the type if it resolves to a Class, or <code>Object.class</code> otherwise
*/
static Class resolveType(Type genericType, Map typeVariableMap) {
static Class resolveType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {
Type rawType = getRawType(genericType, typeVariableMap);
return (rawType instanceof Class ? (Class) rawType : Object.class);
}
@ -119,11 +117,11 @@ public abstract class GenericTypeResolver {
* @param typeVariableMap the TypeVariable Map to resolved against
* @return the resolved raw type
*/
static Type getRawType(Type genericType, Map typeVariableMap) {
static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {
Type resolvedType = genericType;
if (genericType instanceof TypeVariable) {
TypeVariable tv = (TypeVariable) genericType;
resolvedType = (Type) typeVariableMap.get(tv);
resolvedType = typeVariableMap.get(tv);
if (resolvedType == null) {
resolvedType = extractBoundForTypeVariable(tv);
}
@ -141,11 +139,11 @@ public abstract class GenericTypeResolver {
* {@link Class} for the specified {@link Class}. Searches all super types,
* enclosing types and interfaces.
*/
static Map getTypeVariableMap(Class clazz) {
Map typeVariableMap = (Map) typeVariableCache.get(clazz);
static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
Map<TypeVariable, Type> typeVariableMap = typeVariableCache.get(clazz);
if (typeVariableMap == null) {
typeVariableMap = new HashMap();
typeVariableMap = new HashMap<TypeVariable, Type>();
// interfaces
extractTypeVariablesFromGenericInterfaces(clazz.getGenericInterfaces(), typeVariableMap);
@ -195,9 +193,8 @@ public abstract class GenericTypeResolver {
return bound;
}
private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces, Map typeVariableMap) {
for (int i = 0; i < genericInterfaces.length; i++) {
Type genericInterface = genericInterfaces[i];
private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces, Map<TypeVariable, Type> typeVariableMap) {
for (Type genericInterface : genericInterfaces) {
if (genericInterface instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericInterface;
populateTypeMapFromParameterizedType(pt, typeVariableMap);
@ -229,7 +226,7 @@ public abstract class GenericTypeResolver {
* For '<code>FooImpl</code>' the following mappings would be added to the {@link Map}:
* {S=java.lang.String, T=java.lang.Integer}.
*/
private static void populateTypeMapFromParameterizedType(ParameterizedType type, Map typeVariableMap) {
private static void populateTypeMapFromParameterizedType(ParameterizedType type, Map<TypeVariable, Type> typeVariableMap) {
if (type.getRawType() instanceof Class) {
Type[] actualTypeArguments = type.getActualTypeArguments();
TypeVariable[] typeVariables = ((Class) type.getRawType()).getTypeParameters();
@ -249,7 +246,7 @@ public abstract class GenericTypeResolver {
// We have a type that is parameterized at instantiation time
// the nearest match on the bridge method will be the bounded type.
TypeVariable typeVariableArgument = (TypeVariable) actualTypeArgument;
Type resolvedType = (Type) typeVariableMap.get(typeVariableArgument);
Type resolvedType = typeVariableMap.get(typeVariableArgument);
if (resolvedType == null) {
resolvedType = extractBoundForTypeVariable(typeVariableArgument);
}

View File

@ -19,6 +19,8 @@ package org.springframework.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
@ -59,7 +61,7 @@ public class MethodParameter {
/** Map from Integer level to Integer type index */
private Map<Integer,Integer> typeIndexesPerLevel;
Map typeVariableMap;
Map<TypeVariable, Type> typeVariableMap;
/**

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");
* you may not use this file except in compliance with the License.
@ -16,6 +16,8 @@
package org.springframework.core.task;
import java.util.concurrent.Executor;
/**
* Simple task executor interface that abstracts the execution
* of a {@link Runnable}.
@ -24,15 +26,16 @@ package org.springframework.core.task;
* such as: synchronous, asynchronous, using a thread pool, and more.
*
* <p>Equivalent to JDK 1.5's {@link java.util.concurrent.Executor}
* interface. Separate mainly for compatibility with JDK 1.4.
* Implementations can simply implement the JDK 1.5 <code>Executor</code>
* interface as well, as it defines the exact same method signature.
* interface; extending it now in Spring 3.0, so that clients may declare
* a dependency on an Executor and receive any TaskExecutor implementation.
* This interface remains separate from the standard Executor interface
* mainly for backwards compatibility with JDK 1.4 in Spring 2.x.
*
* @author Juergen Hoeller
* @since 2.0
* @see java.util.concurrent.Executor
*/
public interface TaskExecutor {
public interface TaskExecutor extends Executor {
/**
* Execute the given <code>task</code>.

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");
* you may not use this file except in compliance with the License.
@ -16,7 +16,7 @@
package org.springframework.core.task;
import org.springframework.core.NestedRuntimeException;
import java.util.concurrent.RejectedExecutionException;
/**
* Exception thrown when a {@link TaskExecutor} rejects to accept
@ -27,7 +27,7 @@ import org.springframework.core.NestedRuntimeException;
* @see TaskExecutor#execute(Runnable)
* @see TaskTimeoutException
*/
public class TaskRejectedException extends NestedRuntimeException {
public class TaskRejectedException extends RejectedExecutionException {
/**
* Create a new <code>TaskRejectedException</code>

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");
* you may not use this file except in compliance with the License.
@ -17,21 +17,19 @@
package org.springframework.core.task.support;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import org.springframework.core.task.TaskExecutor;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.util.Assert;
/**
* Adapter that exposes the {@link java.util.concurrent.Executor java.util.concurrent.Executor}
* Adapter that exposes the {@link java.util.concurrent.Executor}
* interface for any Spring {@link org.springframework.core.task.TaskExecutor}.
* Follows the JDK executor contract for exception handling.
*
* @author Juergen Hoeller
* @since 2.5
* @see java.util.concurrent.Executor
* @see org.springframework.core.task.TaskExecutor
* @deprecated as of Spring 3.0 since TaskExecutor itself implements the Executor interface now
*/
public class ConcurrentExecutorAdapter implements Executor {
@ -49,12 +47,7 @@ public class ConcurrentExecutorAdapter implements Executor {
public void execute(Runnable command) {
try {
this.taskExecutor.execute(command);
}
catch (TaskRejectedException ex) {
throw new RejectedExecutionException(ex.getMessage(), ex);
}
}
}

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");
* you may not use this file except in compliance with the License.
@ -51,10 +51,11 @@ public class WeakReferenceMonitor {
private static final Log logger = LogFactory.getLog(WeakReferenceMonitor.class);
// Queue receiving reachability events
private static final ReferenceQueue handleQueue = new ReferenceQueue();
private static final ReferenceQueue<Object> handleQueue = new ReferenceQueue<Object>();
// All tracked entries (WeakReference => ReleaseListener)
private static final Map trackedEntries = Collections.synchronizedMap(new HashMap());
private static final Map<Reference, ReleaseListener> trackedEntries =
Collections.synchronizedMap(new HashMap<Reference, ReleaseListener>());
// Thread polling handleQueue, lazy initialized
private static Thread monitoringThread = null;
@ -73,7 +74,7 @@ public class WeakReferenceMonitor {
// Make weak reference to this handle, so we can say when
// handle is not used any more by polling on handleQueue.
WeakReference weakRef = new WeakReference(handle, handleQueue);
WeakReference<Object> weakRef = new WeakReference<Object>(handle, handleQueue);
// Add monitored entry to internal map of all monitored entries.
addEntry(weakRef, listener);
@ -105,7 +106,7 @@ public class WeakReferenceMonitor {
* @return entry object associated with given reference
*/
private static ReleaseListener removeEntry(Reference reference) {
return (ReleaseListener) trackedEntries.remove(reference);
return trackedEntries.remove(reference);
}
/**

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");
* you may not use this file except in compliance with the License.
@ -25,7 +25,7 @@ import java.util.Comparator;
* @author Keith Donald
* @since 1.2.2
*/
public final class BooleanComparator implements Comparator, Serializable {
public final class BooleanComparator implements Comparator<Boolean>, Serializable {
/**
* A shared default instance of this comparator, treating true lower
@ -58,9 +58,7 @@ public final class BooleanComparator implements Comparator, Serializable {
}
public int compare(Object o1, Object o2) {
boolean v1 = ((Boolean) o1).booleanValue();
boolean v2 = ((Boolean) o2).booleanValue();
public int compare(Boolean v1, Boolean v2) {
return (v1 ^ v2) ? ((v1 ^ this.trueLow) ? 1 : -1) : 0;
}

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");
* you may not use this file except in compliance with the License.
@ -29,12 +29,10 @@ import org.springframework.util.Assert;
* @since 1.2.2
* @see Comparable
*/
public class ComparableComparator implements Comparator {
public class ComparableComparator<T extends Comparable<T>> implements Comparator<T> {
public int compare(Object o1, Object o2) {
Assert.isTrue(o1 instanceof Comparable, "The first object provided is not Comparable");
Assert.isTrue(o2 instanceof Comparable, "The second object provided is not Comparable");
return ((Comparable) o1).compareTo(o2);
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}
}

View File

@ -37,9 +37,9 @@ import org.springframework.util.Assert;
* @author Juergen Hoeller
* @since 1.2.2
*/
public class CompoundComparator implements Comparator, Serializable {
public class CompoundComparator<T> implements Comparator<T>, Serializable {
private final List<InvertibleComparator> comparators;
private final List<InvertibleComparator<T>> comparators;
/**
@ -48,7 +48,7 @@ public class CompoundComparator implements Comparator, Serializable {
* IllegalStateException is thrown.
*/
public CompoundComparator() {
this.comparators = new ArrayList<InvertibleComparator>();
this.comparators = new ArrayList<InvertibleComparator<T>>();
}
/**
@ -59,8 +59,8 @@ public class CompoundComparator implements Comparator, Serializable {
* @see InvertibleComparator
*/
public CompoundComparator(Comparator[] comparators) {
this.comparators = new ArrayList<InvertibleComparator>(comparators.length);
for (Comparator comparator : comparators) {
this.comparators = new ArrayList<InvertibleComparator<T>>(comparators.length);
for (Comparator<T> comparator : comparators) {
addComparator(comparator);
}
}
@ -73,12 +73,12 @@ public class CompoundComparator implements Comparator, Serializable {
* @param comparator the Comparator to add to the end of the chain
* @see InvertibleComparator
*/
public void addComparator(Comparator comparator) {
public void addComparator(Comparator<T> comparator) {
if (comparator instanceof InvertibleComparator) {
this.comparators.add((InvertibleComparator) comparator);
this.comparators.add((InvertibleComparator<T>) comparator);
}
else {
this.comparators.add(new InvertibleComparator(comparator));
this.comparators.add(new InvertibleComparator<T>(comparator));
}
}
@ -87,8 +87,8 @@ public class CompoundComparator implements Comparator, Serializable {
* @param comparator the Comparator to add to the end of the chain
* @param ascending the sort order: ascending (true) or descending (false)
*/
public void addComparator(Comparator comparator, boolean ascending) {
this.comparators.add(new InvertibleComparator(comparator, ascending));
public void addComparator(Comparator<T> comparator, boolean ascending) {
this.comparators.add(new InvertibleComparator<T>(comparator, ascending));
}
/**
@ -99,13 +99,12 @@ public class CompoundComparator implements Comparator, Serializable {
* @param comparator the Comparator to place at the given index
* @see InvertibleComparator
*/
public void setComparator(int index, Comparator comparator) {
public void setComparator(int index, Comparator<T> comparator) {
if (comparator instanceof InvertibleComparator) {
this.comparators.set(index, (InvertibleComparator) comparator);
this.comparators.set(index, (InvertibleComparator<T>) comparator);
}
else {
InvertibleComparator invComp = new InvertibleComparator(comparator);
this.comparators.set(index, invComp);
this.comparators.set(index, new InvertibleComparator<T>(comparator));
}
}
@ -115,8 +114,8 @@ public class CompoundComparator implements Comparator, Serializable {
* @param comparator the Comparator to place at the given index
* @param ascending the sort order: ascending (true) or descending (false)
*/
public void setComparator(int index, Comparator comparator, boolean ascending) {
this.comparators.set(index, new InvertibleComparator(comparator, ascending));
public void setComparator(int index, Comparator<T> comparator, boolean ascending) {
this.comparators.set(index, new InvertibleComparator<T>(comparator, ascending));
}
/**
@ -161,10 +160,10 @@ public class CompoundComparator implements Comparator, Serializable {
}
public int compare(Object o1, Object o2) {
public int compare(T o1, T o2) {
Assert.state(this.comparators.size() > 0,
"No sort definitions have been added to this CompoundComparator to compare");
for (InvertibleComparator comparator : this.comparators) {
for (InvertibleComparator<T> comparator : this.comparators) {
int result = comparator.compare(o1, o2);
if (result != 0) {
return result;

View File

@ -28,9 +28,9 @@ import java.util.Comparator;
* @author Juergen Hoeller
* @since 1.2.2
*/
public class InvertibleComparator implements Comparator, Serializable {
public class InvertibleComparator<T> implements Comparator<T>, Serializable {
private final Comparator comparator;
private final Comparator<T> comparator;
private boolean ascending = true;
@ -40,7 +40,7 @@ public class InvertibleComparator implements Comparator, Serializable {
* For the actual comparison, the specified Comparator will be used.
* @param comparator the comparator to decorate
*/
public InvertibleComparator(Comparator comparator) {
public InvertibleComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
@ -50,7 +50,7 @@ public class InvertibleComparator implements Comparator, Serializable {
* @param comparator the comparator to decorate
* @param ascending the sort order: ascending (true) or descending (false)
*/
public InvertibleComparator(Comparator comparator, boolean ascending) {
public InvertibleComparator(Comparator<T> comparator, boolean ascending) {
this.comparator = comparator;
setAscending(ascending);
}
@ -67,7 +67,7 @@ public class InvertibleComparator implements Comparator, Serializable {
* Return the sort order: ascending (true) or descending (false).
*/
public boolean isAscending() {
return ascending;
return this.ascending;
}
/**
@ -79,7 +79,7 @@ public class InvertibleComparator implements Comparator, Serializable {
}
public int compare(Object o1, Object o2) {
public int compare(T o1, T o2) {
int result = this.comparator.compare(o1, o2);
if (result != 0) {
// Invert the order if it is a reverse sort.

View File

@ -29,7 +29,7 @@ import org.springframework.util.Assert;
* @since 1.2.2
* @see Comparable
*/
public class NullSafeComparator implements Comparator {
public class NullSafeComparator<T> implements Comparator<T> {
/**
* A shared default instance of this comparator, treating nulls lower
@ -44,7 +44,7 @@ public class NullSafeComparator implements Comparator {
public static final NullSafeComparator NULLS_HIGH = new NullSafeComparator(false);
private final Comparator nonNullComparator;
private final Comparator<T> nonNullComparator;
private final boolean nullsLow;
@ -63,8 +63,10 @@ public class NullSafeComparator implements Comparator {
* @see #NULLS_LOW
* @see #NULLS_HIGH
*/
@SuppressWarnings("unchecked")
private NullSafeComparator(boolean nullsLow) {
this(new ComparableComparator(), nullsLow);
this.nonNullComparator = new ComparableComparator();
this.nullsLow = nullsLow;
}
/**
@ -76,14 +78,14 @@ public class NullSafeComparator implements Comparator {
* @param comparator the comparator to use when comparing two non-null objects
* @param nullsLow whether to treat nulls lower or higher than non-null objects
*/
public NullSafeComparator(Comparator comparator, boolean nullsLow) {
public NullSafeComparator(Comparator<T> comparator, boolean nullsLow) {
Assert.notNull(comparator, "The non-null comparator is required");
this.nonNullComparator = comparator;
this.nullsLow = nullsLow;
}
public int compare(Object o1, Object o2) {
public int compare(T o1, T o2) {
if (o1 == o2) {
return 0;
}

View File

@ -44,7 +44,7 @@ public class SpelUtilities {
*/
private static void printAST(PrintStream out, SpelNode t, String indent) {
if (t != null) {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
String s = (t.getType() == -1 ? "EOF" : t.getClass().getSimpleName());
sb.append(indent).append(s);
sb.append(" value=").append(t.getText());

View File

@ -110,7 +110,7 @@ public class CompoundExpression extends SpelNode {
@Override
public String toStringAST() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < getChildCount(); i++) {
sb.append(getChild(i).toStringAST());
}

View File

@ -54,16 +54,18 @@ public abstract class Operator extends SpelNode {
*/
@Override
public String toStringAST() {
StringBuffer sb = new StringBuffer();
if (getChildCount() > 0)
StringBuilder sb = new StringBuilder();
if (getChildCount() > 0) {
sb.append("(");
}
sb.append(getChild(0).toStringAST());
for (int i = 1; i < getChildCount(); i++) {
sb.append(" ").append(getOperatorName()).append(" ");
sb.append(getChild(i).toStringAST());
}
if (getChildCount() > 0)
if (getChildCount() > 0) {
sb.append(")");
}
return sb.toString();
}

View File

@ -86,7 +86,7 @@ public class Projection extends SpelNode {
@Override
public String toStringAST() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
return sb.append("!{").append(getChild(0).toStringAST()).append("}").toString();
}

View File

@ -123,7 +123,7 @@ public class Selection extends SpelNode {
@Override
public String toStringAST() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
switch (variant) {
case ALL:
sb.append("?{");

View File

@ -198,7 +198,7 @@ public class TestScenarioCreator {
}
public static String reverseString(String input) {
StringBuffer backwards = new StringBuffer();
StringBuilder backwards = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
backwards.append(input.charAt(input.length() - 1 - i));
}

View File

@ -61,22 +61,22 @@ import org.springframework.util.Assert;
* @author Juergen Hoeller
* @since 2.5
*/
public class BeanPropertyRowMapper implements RowMapper {
public class BeanPropertyRowMapper<T> implements RowMapper<T> {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** The class we are mapping to */
private Class mappedClass;
private Class<T> mappedClass;
/** Whether we're strictly validating */
private boolean checkFullyPopulated = false;
/** Map of the fields we provide mapping for */
private Map mappedFields;
private Map<String, PropertyDescriptor> mappedFields;
/** Set of bean properties we provide mapping for */
private Set mappedProperties;
private Set<String> mappedProperties;
/**
@ -92,7 +92,7 @@ public class BeanPropertyRowMapper implements RowMapper {
* in the target bean.
* @param mappedClass the class that each row should be mapped to
*/
public BeanPropertyRowMapper(Class mappedClass) {
public BeanPropertyRowMapper(Class<T> mappedClass) {
initialize(mappedClass);
}
@ -102,7 +102,7 @@ public class BeanPropertyRowMapper implements RowMapper {
* @param checkFullyPopulated whether we're strictly validating that
* all bean properties have been mapped from corresponding database fields
*/
public BeanPropertyRowMapper(Class mappedClass, boolean checkFullyPopulated) {
public BeanPropertyRowMapper(Class<T> mappedClass, boolean checkFullyPopulated) {
initialize(mappedClass);
this.checkFullyPopulated = checkFullyPopulated;
}
@ -111,7 +111,7 @@ public class BeanPropertyRowMapper implements RowMapper {
/**
* Set the class that each row should be mapped to.
*/
public void setMappedClass(Class mappedClass) {
public void setMappedClass(Class<T> mappedClass) {
if (this.mappedClass == null) {
initialize(mappedClass);
}
@ -127,13 +127,12 @@ public class BeanPropertyRowMapper implements RowMapper {
* Initialize the mapping metadata for the given class.
* @param mappedClass the mapped class.
*/
protected void initialize(Class mappedClass) {
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap();
this.mappedProperties = new HashSet();
this.mappedFields = new HashMap<String, PropertyDescriptor>();
this.mappedProperties = new HashSet<String>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
this.mappedFields.put(pd.getName().toLowerCase(), pd);
String underscoredName = underscoreName(pd.getName());
@ -152,7 +151,7 @@ public class BeanPropertyRowMapper implements RowMapper {
* @return the converted name
*/
private String underscoreName(String name) {
StringBuffer result = new StringBuffer();
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
result.append(name.substring(0, 1).toLowerCase());
for (int i = 1; i < name.length(); i++) {
@ -172,7 +171,7 @@ public class BeanPropertyRowMapper implements RowMapper {
/**
* Get the class that we are mapping to.
*/
public final Class getMappedClass() {
public final Class<T> getMappedClass() {
return this.mappedClass;
}
@ -200,19 +199,19 @@ public class BeanPropertyRowMapper implements RowMapper {
* <p>Utilizes public setters and result set metadata.
* @see java.sql.ResultSetMetaData
*/
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
Assert.state(this.mappedClass != null, "Mapped class was not specified");
Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Set populatedProperties = (isCheckFullyPopulated() ? new HashSet() : null);
Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);
for (int index = 1; index <= columnCount; index++) {
String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
PropertyDescriptor pd = this.mappedFields.get(column);
if (pd != null) {
try {
Object value = getColumnValue(rs, index, pd);

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");
* you may not use this file except in compliance with the License.
@ -40,7 +40,7 @@ import org.springframework.dao.DataAccessException;
* @see JdbcTemplate#execute(String, CallableStatementCallback)
* @see JdbcTemplate#execute(CallableStatementCreator, CallableStatementCallback)
*/
public interface CallableStatementCallback {
public interface CallableStatementCallback<T> {
/**
* Gets called by <code>JdbcTemplate.execute</code> with an active JDBC
@ -72,6 +72,6 @@ public interface CallableStatementCallback {
* into a DataAccessException by a SQLExceptionTranslator
* @throws DataAccessException in case of custom exceptions
*/
Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException;
T doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException;
}

View File

@ -43,7 +43,7 @@ public class CallableStatementCreatorFactory {
private final String callString;
/** List of SqlParameter objects. May not be <code>null</code>. */
private final List declaredParameters;
private final List<SqlParameter> declaredParameters;
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
@ -58,7 +58,7 @@ public class CallableStatementCreatorFactory {
*/
public CallableStatementCreatorFactory(String callString) {
this.callString = callString;
this.declaredParameters = new LinkedList();
this.declaredParameters = new LinkedList<SqlParameter>();
}
/**
@ -66,7 +66,7 @@ public class CallableStatementCreatorFactory {
* @param callString the SQL call string
* @param declaredParameters list of {@link SqlParameter} objects
*/
public CallableStatementCreatorFactory(String callString, List declaredParameters) {
public CallableStatementCreatorFactory(String callString, List<SqlParameter> declaredParameters) {
this.callString = callString;
this.declaredParameters = declaredParameters;
}
@ -112,8 +112,8 @@ public class CallableStatementCreatorFactory {
* Return a new CallableStatementCreator instance given this parameters.
* @param params list of parameters (may be <code>null</code>)
*/
public CallableStatementCreator newCallableStatementCreator(Map params) {
return new CallableStatementCreatorImpl(params != null ? params : new HashMap());
public CallableStatementCreator newCallableStatementCreator(Map<String, ?> params) {
return new CallableStatementCreatorImpl(params != null ? params : new HashMap<String, Object>());
}
/**
@ -132,7 +132,7 @@ public class CallableStatementCreatorFactory {
private ParameterMapper inParameterMapper;
private Map inParameters;
private Map<String, ?> inParameters;
/**
* Create a new CallableStatementCreatorImpl.
@ -146,7 +146,7 @@ public class CallableStatementCreatorFactory {
* Create a new CallableStatementCreatorImpl.
* @param inParams list of SqlParameter objects
*/
public CallableStatementCreatorImpl(Map inParams) {
public CallableStatementCreatorImpl(Map<String, ?> inParams) {
this.inParameters = inParams;
}
@ -178,8 +178,7 @@ public class CallableStatementCreatorFactory {
}
int sqlColIndx = 1;
for (int i = 0; i < declaredParameters.size(); i++) {
SqlParameter declaredParam = (SqlParameter) declaredParameters.get(i);
for (SqlParameter declaredParam : declaredParameters) {
if (!declaredParam.isResultsParameter()) {
// So, it's a call parameter - part of the call string.
// Get the value - it may still be null.
@ -193,7 +192,7 @@ public class CallableStatementCreatorFactory {
}
else {
if (declaredParam.getScale() != null) {
cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getScale().intValue());
cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getScale());
}
else {
cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType());
@ -231,9 +230,10 @@ public class CallableStatementCreatorFactory {
@Override
public String toString() {
StringBuffer buf = new StringBuffer("CallableStatementCreatorFactory.CallableStatementCreatorImpl: sql=[");
buf.append(callString).append("]; parameters=").append(this.inParameters);
return buf.toString();
StringBuilder sb = new StringBuilder();
sb.append("CallableStatementCreatorFactory.CallableStatementCreatorImpl: sql=[");
sb.append(callString).append("]; parameters=").append(this.inParameters);
return sb.toString();
}
}

View File

@ -45,12 +45,12 @@ import org.springframework.jdbc.support.JdbcUtils;
* @see JdbcTemplate#queryForList(String)
* @see JdbcTemplate#queryForMap(String)
*/
public class ColumnMapRowMapper implements RowMapper {
public class ColumnMapRowMapper implements RowMapper<Map<String, Object>> {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Map mapOfColValues = createColumnMap(columnCount);
Map<String, Object> mapOfColValues = createColumnMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
String key = getColumnKey(JdbcUtils.lookupColumnName(rsmd, i));
Object obj = getColumnValue(rs, i);
@ -68,8 +68,9 @@ public class ColumnMapRowMapper implements RowMapper {
* @return the new Map instance
* @see org.springframework.core.CollectionFactory#createLinkedCaseInsensitiveMapIfPossible
*/
protected Map createColumnMap(int columnCount) {
return CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(columnCount);
@SuppressWarnings("unchecked")
protected Map<String, Object> createColumnMap(int columnCount) {
return (Map<String, Object>) CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(columnCount);
}
/**

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");
* you may not use this file except in compliance with the License.
@ -37,7 +37,7 @@ import org.springframework.dao.DataAccessException;
* @see JdbcTemplate#query
* @see JdbcTemplate#update
*/
public interface ConnectionCallback {
public interface ConnectionCallback<T> {
/**
* Gets called by <code>JdbcTemplate.execute</code> with an active JDBC
@ -64,6 +64,6 @@ public interface ConnectionCallback {
* @see JdbcTemplate#queryForObject(String, Class)
* @see JdbcTemplate#queryForRowSet(String)
*/
Object doInConnection(Connection con) throws SQLException, DataAccessException;
T doInConnection(Connection con) throws SQLException, DataAccessException;
}

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");
* you may not use this file except in compliance with the License.
@ -58,7 +58,7 @@ public interface JdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(ConnectionCallback action) throws DataAccessException;
<T> T execute(ConnectionCallback<T> action) throws DataAccessException;
//-------------------------------------------------------------------------
@ -77,7 +77,7 @@ public interface JdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(StatementCallback action) throws DataAccessException;
<T> T execute(StatementCallback<T> action) throws DataAccessException;
/**
* Issue a single SQL execute, typically a DDL statement.
@ -98,7 +98,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem executing the query
* @see #query(String, Object[], ResultSetExtractor)
*/
Object query(String sql, ResultSetExtractor rse) throws DataAccessException;
<T> T query(String sql, ResultSetExtractor<T> rse) throws DataAccessException;
/**
* Execute a query given static SQL, reading the ResultSet on a per-row
@ -125,7 +125,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem executing the query
* @see #query(String, Object[], RowMapper)
*/
List query(String sql, RowMapper rowMapper) throws DataAccessException;
<T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException;
/**
* Execute a query given static SQL, mapping a single result row to a Java
@ -141,7 +141,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem executing the query
* @see #queryForObject(String, Object[], RowMapper)
*/
Object queryForObject(String sql, RowMapper rowMapper) throws DataAccessException;
<T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException;
/**
* Execute a query for a result object, given static SQL.
@ -159,7 +159,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem executing the query
* @see #queryForObject(String, Object[], Class)
*/
Object queryForObject(String sql, Class requiredType) throws DataAccessException;
<T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException;
/**
* Execute a query for a result Map, given static SQL.
@ -177,7 +177,7 @@ public interface JdbcOperations {
* @see #queryForMap(String, Object[])
* @see ColumnMapRowMapper
*/
Map queryForMap(String sql) throws DataAccessException;
Map<String, Object> queryForMap(String sql) throws DataAccessException;
/**
* Execute a query that results in a long value, given static SQL.
@ -228,7 +228,7 @@ public interface JdbcOperations {
* @see #queryForList(String, Object[], Class)
* @see SingleColumnRowMapper
*/
List queryForList(String sql, Class elementType) throws DataAccessException;
<T> List<T> queryForList(String sql, Class<T> elementType) throws DataAccessException;
/**
* Execute a query for a result list, given static SQL.
@ -244,7 +244,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem executing the query
* @see #queryForList(String, Object[])
*/
List queryForList(String sql) throws DataAccessException;
List<Map<String, Object>> queryForList(String sql) throws DataAccessException;
/**
* Execute a query for a SqlRowSet, given static SQL.
@ -303,7 +303,7 @@ public interface JdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(PreparedStatementCreator psc, PreparedStatementCallback action)
<T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)
throws DataAccessException;
/**
@ -319,7 +319,7 @@ public interface JdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(String sql, PreparedStatementCallback action) throws DataAccessException;
<T> T execute(String sql, PreparedStatementCallback<T> action) throws DataAccessException;
/**
* Query using a prepared statement, reading the ResultSet with a
@ -332,7 +332,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem
* @see PreparedStatementCreatorFactory
*/
Object query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException;
<T> T query(PreparedStatementCreator psc, ResultSetExtractor<T> rse) throws DataAccessException;
/**
* Query using a prepared statement, reading the ResultSet with a
@ -346,7 +346,7 @@ public interface JdbcOperations {
* @return an arbitrary result object, as returned by the ResultSetExtractor
* @throws DataAccessException if there is any problem
*/
Object query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse)
<T> T query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse)
throws DataAccessException;
/**
@ -362,7 +362,7 @@ public interface JdbcOperations {
* @throws DataAccessException if the query fails
* @see java.sql.Types
*/
Object query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse)
<T> T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor<T> rse)
throws DataAccessException;
/**
@ -378,7 +378,7 @@ public interface JdbcOperations {
* @return an arbitrary result object, as returned by the ResultSetExtractor
* @throws DataAccessException if the query fails
*/
Object query(String sql, Object[] args, ResultSetExtractor rse) throws DataAccessException;
<T> T query(String sql, Object[] args, ResultSetExtractor<T> rse) throws DataAccessException;
/**
* Query using a prepared statement, reading the ResultSet on a per-row
@ -448,7 +448,7 @@ public interface JdbcOperations {
* @throws DataAccessException if there is any problem
* @see PreparedStatementCreatorFactory
*/
List query(PreparedStatementCreator psc, RowMapper rowMapper) throws DataAccessException;
<T> List<T> query(PreparedStatementCreator psc, RowMapper<T> rowMapper) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -463,7 +463,7 @@ public interface JdbcOperations {
* @return the result List, containing mapped objects
* @throws DataAccessException if the query fails
*/
List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper)
<T> List<T> query(String sql, PreparedStatementSetter pss, RowMapper<T> rowMapper)
throws DataAccessException;
/**
@ -479,7 +479,7 @@ public interface JdbcOperations {
* @throws DataAccessException if the query fails
* @see java.sql.Types
*/
List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper)
<T> List<T> query(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper)
throws DataAccessException;
/**
@ -495,7 +495,7 @@ public interface JdbcOperations {
* @return the result List, containing mapped objects
* @throws DataAccessException if the query fails
*/
List query(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException;
<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list
@ -512,7 +512,7 @@ public interface JdbcOperations {
* return exactly one row
* @throws DataAccessException if the query fails
*/
Object queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper)
<T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper)
throws DataAccessException;
/**
@ -530,7 +530,7 @@ public interface JdbcOperations {
* return exactly one row
* @throws DataAccessException if the query fails
*/
Object queryForObject(String sql, Object[] args, RowMapper rowMapper)
<T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper)
throws DataAccessException;
/**
@ -550,7 +550,7 @@ public interface JdbcOperations {
* @see #queryForObject(String, Class)
* @see java.sql.Types
*/
Object queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType)
<T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType)
throws DataAccessException;
/**
@ -570,7 +570,7 @@ public interface JdbcOperations {
* @throws DataAccessException if the query fails
* @see #queryForObject(String, Class)
*/
Object queryForObject(String sql, Object[] args, Class requiredType) throws DataAccessException;
<T> T queryForObject(String sql, Object[] args, Class<T> requiredType) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -590,7 +590,7 @@ public interface JdbcOperations {
* @see ColumnMapRowMapper
* @see java.sql.Types
*/
Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException;
Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -613,7 +613,7 @@ public interface JdbcOperations {
* @see #queryForMap(String)
* @see ColumnMapRowMapper
*/
Map queryForMap(String sql, Object[] args) throws DataAccessException;
Map<String, Object> queryForMap(String sql, Object[] args) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -703,7 +703,7 @@ public interface JdbcOperations {
* @see #queryForList(String, Class)
* @see SingleColumnRowMapper
*/
List queryForList(String sql, Object[] args, int[] argTypes, Class elementType)
<T>List<T> queryForList(String sql, Object[] args, int[] argTypes, Class<T> elementType)
throws DataAccessException;
/**
@ -723,7 +723,7 @@ public interface JdbcOperations {
* @see #queryForList(String, Class)
* @see SingleColumnRowMapper
*/
List queryForList(String sql, Object[] args, Class elementType) throws DataAccessException;
<T> List<T> queryForList(String sql, Object[] args, Class<T> elementType) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -741,7 +741,7 @@ public interface JdbcOperations {
* @see #queryForList(String)
* @see java.sql.Types
*/
List queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException;
List<Map<String, Object>> queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -759,7 +759,7 @@ public interface JdbcOperations {
* @throws DataAccessException if the query fails
* @see #queryForList(String)
*/
List queryForList(String sql, Object[] args) throws DataAccessException;
List<Map<String, Object>> queryForList(String sql, Object[] args) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -905,7 +905,7 @@ public interface JdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(CallableStatementCreator csc, CallableStatementCallback action)
<T> T execute(CallableStatementCreator csc, CallableStatementCallback<T> action)
throws DataAccessException;
/**
@ -921,7 +921,7 @@ public interface JdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(String callString, CallableStatementCallback action) throws DataAccessException;
<T> T execute(String callString, CallableStatementCallback<T> action) throws DataAccessException;
/**
* Execute a SQL call using a CallableStatementCreator to provide SQL and any
@ -931,6 +931,7 @@ public interface JdbcOperations {
* @return Map of extracted out parameters
* @throws DataAccessException if there is any problem issuing the update
*/
Map call(CallableStatementCreator csc, List declaredParameters) throws DataAccessException;
Map<String, Object> call(CallableStatementCreator csc, List<SqlParameter> declaredParameters)
throws DataAccessException;
}

View File

@ -33,7 +33,6 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.core.CollectionFactory;
@ -325,7 +324,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
// Methods dealing with a plain java.sql.Connection
//-------------------------------------------------------------------------
public Object execute(ConnectionCallback action) throws DataAccessException {
public <T> T execute(ConnectionCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(getDataSource());
@ -376,7 +375,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
// Methods dealing with static SQL (java.sql.Statement)
//-------------------------------------------------------------------------
public Object execute(StatementCallback action) throws DataAccessException {
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(getDataSource());
@ -393,7 +392,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (this.nativeJdbcExtractor != null) {
stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
}
Object result = action.doInStatement(stmtToUse);
T result = action.doInStatement(stmtToUse);
handleWarnings(stmt);
return result;
}
@ -416,8 +415,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
class ExecuteStatementCallback implements StatementCallback, SqlProvider {
class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
@ -429,15 +427,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
execute(new ExecuteStatementCallback());
}
public Object query(final String sql, final ResultSetExtractor rse) throws DataAccessException {
public <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {
Assert.notNull(sql, "SQL must not be null");
Assert.notNull(rse, "ResultSetExtractor must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL query [" + sql + "]");
}
class QueryStatementCallback implements StatementCallback, SqlProvider {
public Object doInStatement(Statement stmt) throws SQLException {
class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
public T doInStatement(Statement stmt) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
@ -462,43 +459,43 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
query(sql, new RowCallbackHandlerResultSetExtractor(rch));
}
public List query(String sql, RowMapper rowMapper) throws DataAccessException {
return (List) query(sql, new RowMapperResultSetExtractor(rowMapper));
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {
return query(sql, new RowMapperResultSetExtractor<T>(rowMapper));
}
public Map queryForMap(String sql) throws DataAccessException {
return (Map) queryForObject(sql, getColumnMapRowMapper());
public Map<String, Object> queryForMap(String sql) throws DataAccessException {
return queryForObject(sql, getColumnMapRowMapper());
}
public Object queryForObject(String sql, RowMapper rowMapper) throws DataAccessException {
List results = query(sql, rowMapper);
public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, rowMapper);
return DataAccessUtils.requiredSingleResult(results);
}
public Object queryForObject(String sql, Class requiredType) throws DataAccessException {
public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException {
return queryForObject(sql, getSingleColumnRowMapper(requiredType));
}
public long queryForLong(String sql) throws DataAccessException {
Number number = (Number) queryForObject(sql, Long.class);
Number number = queryForObject(sql, Long.class);
return (number != null ? number.longValue() : 0);
}
public int queryForInt(String sql) throws DataAccessException {
Number number = (Number) queryForObject(sql, Integer.class);
Number number = queryForObject(sql, Integer.class);
return (number != null ? number.intValue() : 0);
}
public List queryForList(String sql, Class elementType) throws DataAccessException {
public <T> List<T> queryForList(String sql, Class<T> elementType) throws DataAccessException {
return query(sql, getSingleColumnRowMapper(elementType));
}
public List queryForList(String sql) throws DataAccessException {
public List<Map<String, Object>> queryForList(String sql) throws DataAccessException {
return query(sql, getColumnMapRowMapper());
}
public SqlRowSet queryForRowSet(String sql) throws DataAccessException {
return (SqlRowSet) query(sql, new SqlRowSetResultSetExtractor());
return query(sql, new SqlRowSetResultSetExtractor());
}
public int update(final String sql) throws DataAccessException {
@ -506,20 +503,19 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL update [" + sql + "]");
}
class UpdateStatementCallback implements StatementCallback, SqlProvider {
public Object doInStatement(Statement stmt) throws SQLException {
class UpdateStatementCallback implements StatementCallback<Integer>, SqlProvider {
public Integer doInStatement(Statement stmt) throws SQLException {
int rows = stmt.executeUpdate(sql);
if (logger.isDebugEnabled()) {
logger.debug("SQL update affected " + rows + " rows");
}
return new Integer(rows);
return rows;
}
public String getSql() {
return sql;
}
}
return ((Integer) execute(new UpdateStatementCallback())).intValue();
return execute(new UpdateStatementCallback());
}
public int[] batchUpdate(final String[] sql) throws DataAccessException {
@ -527,15 +523,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL batch update of " + sql.length + " statements");
}
class BatchUpdateStatementCallback implements StatementCallback, SqlProvider {
class BatchUpdateStatementCallback implements StatementCallback<int[]>, SqlProvider {
private String currSql;
public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
public int[] doInStatement(Statement stmt) throws SQLException, DataAccessException {
int[] rowsAffected = new int[sql.length];
if (JdbcUtils.supportsBatchUpdates(stmt.getConnection())) {
for (int i = 0; i < sql.length; i++) {
this.currSql = sql[i];
stmt.addBatch(sql[i]);
for (String sqlStmt : sql) {
this.currSql = sqlStmt;
stmt.addBatch(sqlStmt);
}
rowsAffected = stmt.executeBatch();
}
@ -553,10 +548,10 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
return rowsAffected;
}
public String getSql() {
return currSql;
return this.currSql;
}
}
return (int[]) execute(new BatchUpdateStatementCallback());
return execute(new BatchUpdateStatementCallback());
}
@ -564,7 +559,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
// Methods dealing with prepared statements
//-------------------------------------------------------------------------
public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action)
public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action)
throws DataAccessException {
Assert.notNull(psc, "PreparedStatementCreator must not be null");
@ -588,7 +583,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (this.nativeJdbcExtractor != null) {
psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps);
}
Object result = action.doInPreparedStatement(psToUse);
T result = action.doInPreparedStatement(psToUse);
handleWarnings(ps);
return result;
}
@ -615,7 +610,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
}
public Object execute(String sql, PreparedStatementCallback action) throws DataAccessException {
public <T> T execute(String sql, PreparedStatementCallback<T> action) throws DataAccessException {
return execute(new SimplePreparedStatementCreator(sql), action);
}
@ -631,15 +626,15 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @return an arbitrary result object, as returned by the ResultSetExtractor
* @throws DataAccessException if there is any problem
*/
public Object query(
PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor rse)
public <T> T query(
PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor<T> rse)
throws DataAccessException {
Assert.notNull(rse, "ResultSetExtractor must not be null");
logger.debug("Executing prepared SQL query");
return execute(psc, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
return execute(psc, new PreparedStatementCallback<T>() {
public T doInPreparedStatement(PreparedStatement ps) throws SQLException {
ResultSet rs = null;
try {
if (pss != null) {
@ -662,19 +657,19 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
});
}
public Object query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException {
public <T> T query(PreparedStatementCreator psc, ResultSetExtractor<T> rse) throws DataAccessException {
return query(psc, null, rse);
}
public Object query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse) throws DataAccessException {
public <T> T query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse) throws DataAccessException {
return query(new SimplePreparedStatementCreator(sql), pss, rse);
}
public Object query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse) throws DataAccessException {
public <T> T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor<T> rse) throws DataAccessException {
return query(sql, new ArgTypePreparedStatementSetter(args, argTypes), rse);
}
public Object query(String sql, Object[] args, ResultSetExtractor rse) throws DataAccessException {
public <T> T query(String sql, Object[] args, ResultSetExtractor<T> rse) throws DataAccessException {
return query(sql, new ArgPreparedStatementSetter(args), rse);
}
@ -694,103 +689,102 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
query(sql, new ArgPreparedStatementSetter(args), rch);
}
public List query(PreparedStatementCreator psc, RowMapper rowMapper) throws DataAccessException {
return (List) query(psc, new RowMapperResultSetExtractor(rowMapper));
public <T> List<T> query(PreparedStatementCreator psc, RowMapper<T> rowMapper) throws DataAccessException {
return query(psc, new RowMapperResultSetExtractor<T>(rowMapper));
}
public List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper) throws DataAccessException {
return (List) query(sql, pss, new RowMapperResultSetExtractor(rowMapper));
public <T> List<T> query(String sql, PreparedStatementSetter pss, RowMapper<T> rowMapper) throws DataAccessException {
return query(sql, pss, new RowMapperResultSetExtractor<T>(rowMapper));
}
public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper) throws DataAccessException {
return (List) query(sql, args, argTypes, new RowMapperResultSetExtractor(rowMapper));
public <T> List<T> query(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) throws DataAccessException {
return query(sql, args, argTypes, new RowMapperResultSetExtractor<T>(rowMapper));
}
public List query(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException {
return (List) query(sql, args, new RowMapperResultSetExtractor(rowMapper));
public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
return query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper));
}
public Object queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper)
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper)
throws DataAccessException {
List results = (List) query(sql, args, argTypes, new RowMapperResultSetExtractor(rowMapper, 1));
List<T> results = query(sql, args, argTypes, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return DataAccessUtils.requiredSingleResult(results);
}
public Object queryForObject(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException {
List results = (List) query(sql, args, new RowMapperResultSetExtractor(rowMapper, 1));
public <T> T queryForObject(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return DataAccessUtils.requiredSingleResult(results);
}
public Object queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType)
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType)
throws DataAccessException {
return queryForObject(sql, args, argTypes, getSingleColumnRowMapper(requiredType));
}
public Object queryForObject(String sql, Object[] args, Class requiredType) throws DataAccessException {
public <T> T queryForObject(String sql, Object[] args, Class<T> requiredType) throws DataAccessException {
return queryForObject(sql, args, getSingleColumnRowMapper(requiredType));
}
public Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return (Map) queryForObject(sql, args, argTypes, getColumnMapRowMapper());
public Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return queryForObject(sql, args, argTypes, getColumnMapRowMapper());
}
public Map queryForMap(String sql, Object[] args) throws DataAccessException {
return (Map) queryForObject(sql, args, getColumnMapRowMapper());
public Map<String, Object> queryForMap(String sql, Object[] args) throws DataAccessException {
return queryForObject(sql, args, getColumnMapRowMapper());
}
public long queryForLong(String sql, Object[] args, int[] argTypes) throws DataAccessException {
Number number = (Number) queryForObject(sql, args, argTypes, Long.class);
Number number = queryForObject(sql, args, argTypes, Long.class);
return (number != null ? number.longValue() : 0);
}
public long queryForLong(String sql, Object[] args) throws DataAccessException {
Number number = (Number) queryForObject(sql, args, Long.class);
Number number = queryForObject(sql, args, Long.class);
return (number != null ? number.longValue() : 0);
}
public int queryForInt(String sql, Object[] args, int[] argTypes) throws DataAccessException {
Number number = (Number) queryForObject(sql, args, argTypes, Integer.class);
Number number = queryForObject(sql, args, argTypes, Integer.class);
return (number != null ? number.intValue() : 0);
}
public int queryForInt(String sql, Object[] args) throws DataAccessException {
Number number = (Number) queryForObject(sql, args, Integer.class);
Number number = queryForObject(sql, args, Integer.class);
return (number != null ? number.intValue() : 0);
}
public List queryForList(String sql, Object[] args, int[] argTypes, Class elementType) throws DataAccessException {
public <T> List<T> queryForList(String sql, Object[] args, int[] argTypes, Class<T> elementType) throws DataAccessException {
return query(sql, args, argTypes, getSingleColumnRowMapper(elementType));
}
public List queryForList(String sql, Object[] args, Class elementType) throws DataAccessException {
public <T> List<T> queryForList(String sql, Object[] args, Class<T> elementType) throws DataAccessException {
return query(sql, args, getSingleColumnRowMapper(elementType));
}
public List queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException {
public List<Map<String, Object>> queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return query(sql, args, argTypes, getColumnMapRowMapper());
}
public List queryForList(String sql, Object[] args) throws DataAccessException {
public List<Map<String, Object>> queryForList(String sql, Object[] args) throws DataAccessException {
return query(sql, args, getColumnMapRowMapper());
}
public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return (SqlRowSet) query(sql, args, argTypes, new SqlRowSetResultSetExtractor());
return query(sql, args, argTypes, new SqlRowSetResultSetExtractor());
}
public SqlRowSet queryForRowSet(String sql, Object[] args) throws DataAccessException {
return (SqlRowSet) query(sql, args, new SqlRowSetResultSetExtractor());
return query(sql, args, new SqlRowSetResultSetExtractor());
}
protected int update(final PreparedStatementCreator psc, final PreparedStatementSetter pss)
throws DataAccessException {
logger.debug("Executing prepared SQL update");
Integer result = (Integer) execute(psc, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
return execute(psc, new PreparedStatementCallback<Integer>() {
public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
try {
if (pss != null) {
pss.setValues(ps);
@ -799,7 +793,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (logger.isDebugEnabled()) {
logger.debug("SQL update affected " + rows + " rows");
}
return new Integer(rows);
return rows;
}
finally {
if (pss instanceof ParameterDisposer) {
@ -808,7 +802,6 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
}
});
return result.intValue();
}
public int update(PreparedStatementCreator psc) throws DataAccessException {
@ -821,17 +814,17 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
Assert.notNull(generatedKeyHolder, "KeyHolder must not be null");
logger.debug("Executing SQL update and returning generated keys");
Integer result = (Integer) execute(psc, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
return execute(psc, new PreparedStatementCallback<Integer>() {
public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
int rows = ps.executeUpdate();
List generatedKeys = generatedKeyHolder.getKeyList();
List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
generatedKeys.clear();
ResultSet keys = ps.getGeneratedKeys();
if (keys != null) {
try {
RowMapper rowMapper = getColumnMapRowMapper();
RowMapperResultSetExtractor rse = new RowMapperResultSetExtractor(rowMapper, 1);
generatedKeys.addAll((List) rse.extractData(keys));
RowMapperResultSetExtractor<Map<String, Object>> rse =
new RowMapperResultSetExtractor<Map<String, Object>>(getColumnMapRowMapper(), 1);
generatedKeys.addAll(rse.extractData(keys));
}
finally {
JdbcUtils.closeResultSet(keys);
@ -840,10 +833,9 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (logger.isDebugEnabled()) {
logger.debug("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
}
return new Integer(rows);
return rows;
}
});
return result.intValue();
}
public int update(String sql, PreparedStatementSetter pss) throws DataAccessException {
@ -863,8 +855,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
logger.debug("Executing SQL batch update [" + sql + "]");
}
return (int[]) execute(sql, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
return execute(sql, new PreparedStatementCallback<int[]>() {
public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException {
try {
int batchSize = pss.getBatchSize();
InterruptibleBatchPreparedStatementSetter ipss =
@ -881,17 +873,17 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
return ps.executeBatch();
}
else {
List rowsAffected = new ArrayList();
List<Integer> rowsAffected = new ArrayList<Integer>();
for (int i = 0; i < batchSize; i++) {
pss.setValues(ps, i);
if (ipss != null && ipss.isBatchExhausted(i)) {
break;
}
rowsAffected.add(new Integer(ps.executeUpdate()));
rowsAffected.add(ps.executeUpdate());
}
int[] rowsAffectedArray = new int[rowsAffected.size()];
for (int i = 0; i < rowsAffectedArray.length; i++) {
rowsAffectedArray[i] = ((Integer) rowsAffected.get(i)).intValue();
rowsAffectedArray[i] = rowsAffected.get(i);
}
return rowsAffectedArray;
}
@ -910,7 +902,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
// Methods dealing with callable statements
//-------------------------------------------------------------------------
public Object execute(CallableStatementCreator csc, CallableStatementCallback action)
public <T> T execute(CallableStatementCreator csc, CallableStatementCallback<T> action)
throws DataAccessException {
Assert.notNull(csc, "CallableStatementCreator must not be null");
@ -933,7 +925,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (this.nativeJdbcExtractor != null) {
csToUse = this.nativeJdbcExtractor.getNativeCallableStatement(cs);
}
Object result = action.doInCallableStatement(csToUse);
T result = action.doInCallableStatement(csToUse);
handleWarnings(cs);
return result;
}
@ -960,16 +952,17 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
}
public Object execute(String callString, CallableStatementCallback action) throws DataAccessException {
public <T> T execute(String callString, CallableStatementCallback<T> action) throws DataAccessException {
return execute(new SimpleCallableStatementCreator(callString), action);
}
public Map call(CallableStatementCreator csc, List declaredParameters) throws DataAccessException {
final List updateCountParameters = new ArrayList();
final List resultSetParameters = new ArrayList();
final List callParameters = new ArrayList();
for (int i = 0; i < declaredParameters.size(); i++) {
SqlParameter parameter = (SqlParameter) declaredParameters.get(i);
public Map<String, Object> call(CallableStatementCreator csc, List<SqlParameter> declaredParameters)
throws DataAccessException {
final List<SqlParameter> updateCountParameters = new ArrayList<SqlParameter>();
final List<SqlParameter> resultSetParameters = new ArrayList<SqlParameter>();
final List<SqlParameter> callParameters = new ArrayList<SqlParameter>();
for (SqlParameter parameter : declaredParameters) {
if (parameter.isResultsParameter()) {
if (parameter instanceof SqlReturnResultSet) {
resultSetParameters.add(parameter);
@ -982,15 +975,15 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
callParameters.add(parameter);
}
}
return (Map) execute(csc, new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException {
return execute(csc, new CallableStatementCallback<Map<String, Object>>() {
public Map<String, Object> doInCallableStatement(CallableStatement cs) throws SQLException {
boolean retVal = cs.execute();
int updateCount = cs.getUpdateCount();
if (logger.isDebugEnabled()) {
logger.debug("CallableStatement.execute() returned '" + retVal + "'");
logger.debug("CallableStatement.getUpdateCount() returned " + updateCount);
}
Map returnedResults = createResultsMap();
Map<String, Object> returnedResults = createResultsMap();
if (retVal || updateCount != -1) {
returnedResults.putAll(extractReturnedResults(cs, updateCountParameters, resultSetParameters, updateCount));
}
@ -1007,11 +1000,11 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @param resultSetParameters Parameter list of declared resturn resultSet parameters for the stored procedure
* @return Map that contains returned results
*/
protected Map extractReturnedResults(
protected Map<String, Object> extractReturnedResults(
CallableStatement cs, List updateCountParameters, List resultSetParameters, int updateCount)
throws SQLException {
Map returnedResults = new HashMap();
Map<String, Object> returnedResults = new HashMap<String, Object>();
int rsIndex = 0;
int updateIndex = 0;
boolean moreResults;
@ -1037,14 +1030,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
if (updateCountParameters != null && updateCountParameters.size() > updateIndex) {
SqlReturnUpdateCount ucParam = (SqlReturnUpdateCount)updateCountParameters.get(updateIndex);
String declaredUcName = ucParam.getName();
returnedResults.put(declaredUcName, new Integer(updateCount));
returnedResults.put(declaredUcName, updateCount);
updateIndex++;
}
else {
if (!skipUndeclaredResults) {
String undeclaredUcName = RETURN_UPDATE_COUNT_PREFIX + (updateIndex + 1);
logger.info("Added default SqlReturnUpdateCount parameter named " + undeclaredUcName);
returnedResults.put(undeclaredUcName, new Integer(updateCount));
returnedResults.put(undeclaredUcName, updateCount);
updateIndex++;
}
}
@ -1066,11 +1059,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @param parameters parameter list for the stored procedure
* @return Map that contains returned results
*/
protected Map extractOutputParameters(CallableStatement cs, List parameters) throws SQLException {
Map returnedResults = new HashMap();
protected Map<String, Object> extractOutputParameters(CallableStatement cs, List<SqlParameter> parameters)
throws SQLException {
Map<String, Object> returnedResults = new HashMap<String, Object>();
int sqlColIndex = 1;
for (int i = 0; i < parameters.size(); i++) {
SqlParameter param = (SqlParameter) parameters.get(i);
for (SqlParameter param : parameters) {
if (param instanceof SqlOutParameter) {
SqlOutParameter outParam = (SqlOutParameter) param;
if (outParam.isReturnTypeSupported()) {
@ -1109,11 +1103,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @param param the corresponding stored procedure parameter
* @return Map that contains returned results
*/
protected Map processResultSet(ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException {
@SuppressWarnings("unchecked")
protected Map<String, Object> processResultSet(ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException {
if (rs == null) {
return Collections.EMPTY_MAP;
return Collections.emptyMap();
}
Map returnedResults = new HashMap();
Map<String, Object> returnedResults = new HashMap<String, Object>();
try {
ResultSet rsToUse = rs;
if (this.nativeJdbcExtractor != null) {
@ -1150,7 +1145,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @return the RowMapper to use
* @see ColumnMapRowMapper
*/
protected RowMapper getColumnMapRowMapper() {
protected RowMapper<Map<String, Object>> getColumnMapRowMapper() {
return new ColumnMapRowMapper();
}
@ -1160,8 +1155,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @return the RowMapper to use
* @see SingleColumnRowMapper
*/
protected RowMapper getSingleColumnRowMapper(Class requiredType) {
return new SingleColumnRowMapper(requiredType);
protected <T> RowMapper<T> getSingleColumnRowMapper(Class<T> requiredType) {
return new SingleColumnRowMapper<T>(requiredType);
}
/**
@ -1172,12 +1167,13 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* @see #setResultsMapCaseInsensitive
* @see org.springframework.core.CollectionFactory#createLinkedCaseInsensitiveMapIfPossible
*/
protected Map createResultsMap() {
@SuppressWarnings("unchecked")
protected Map<String, Object> createResultsMap() {
if (isResultsMapCaseInsensitive()) {
return CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(10);
return (Map<String, Object>) CollectionFactory.createLinkedCaseInsensitiveMapIfPossible(16);
}
else {
return new LinkedHashMap();
return new LinkedHashMap<String, Object>();
}
}
@ -1280,7 +1276,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
else if (method.getName().equals("hashCode")) {
// Use hashCode of PersistenceManager proxy.
return new Integer(System.identityHashCode(proxy));
return System.identityHashCode(proxy);
}
else if (method.getName().equals("close")) {
// Handle close method: suppress, not valid.
@ -1355,7 +1351,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
* <p>Uses a regular ResultSet, so we have to be careful when using it:
* We don't use it for navigating since this could lead to unpredictable consequences.
*/
private static class RowCallbackHandlerResultSetExtractor implements ResultSetExtractor {
private static class RowCallbackHandlerResultSetExtractor implements ResultSetExtractor<Object> {
private final RowCallbackHandler rch;

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 use this file except in compliance with the License.
@ -42,6 +42,6 @@ public interface ParameterMapper {
* parameter values (that is, there's no need to catch SQLException)
* @return Map of input parameters, keyed by name (never <code>null</code>)
*/
Map createMap(Connection con) throws SQLException;
Map<String, ?> createMap(Connection con) throws SQLException;
}

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");
* you may not use this file except in compliance with the License.
@ -40,7 +40,7 @@ import org.springframework.dao.DataAccessException;
* @see JdbcTemplate#execute(String, PreparedStatementCallback)
* @see JdbcTemplate#execute(PreparedStatementCreator, PreparedStatementCallback)
*/
public interface PreparedStatementCallback {
public interface PreparedStatementCallback<T> {
/**
* Gets called by <code>JdbcTemplate.execute</code> with an active JDBC
@ -75,6 +75,6 @@ public interface PreparedStatementCallback {
* @see JdbcTemplate#queryForObject(String, Object[], Class)
* @see JdbcTemplate#queryForList(String, Object[])
*/
Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException;
T doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException;
}

View File

@ -25,7 +25,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@ -50,7 +49,7 @@ public class PreparedStatementCreatorFactory {
private final String sql;
/** List of SqlParameter objects. May not be <code>null</code>. */
private final List declaredParameters;
private final List<SqlParameter> declaredParameters;
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
@ -69,7 +68,7 @@ public class PreparedStatementCreatorFactory {
*/
public PreparedStatementCreatorFactory(String sql) {
this.sql = sql;
this.declaredParameters = new LinkedList();
this.declaredParameters = new LinkedList<SqlParameter>();
}
/**
@ -88,7 +87,7 @@ public class PreparedStatementCreatorFactory {
* @param declaredParameters list of {@link SqlParameter} objects
* @see SqlParameter
*/
public PreparedStatementCreatorFactory(String sql, List declaredParameters) {
public PreparedStatementCreatorFactory(String sql, List<SqlParameter> declaredParameters) {
this.sql = sql;
this.declaredParameters = declaredParameters;
}
@ -148,7 +147,7 @@ public class PreparedStatementCreatorFactory {
* @param params list of parameters (may be <code>null</code>)
*/
public PreparedStatementSetter newPreparedStatementSetter(List params) {
return new PreparedStatementCreatorImpl(params != null ? params : Collections.EMPTY_LIST);
return new PreparedStatementCreatorImpl(params != null ? params : Collections.emptyList());
}
/**
@ -156,15 +155,15 @@ public class PreparedStatementCreatorFactory {
* @param params the parameter array (may be <code>null</code>)
*/
public PreparedStatementSetter newPreparedStatementSetter(Object[] params) {
return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.EMPTY_LIST);
return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.emptyList());
}
/**
* Return a new PreparedStatementCreator for the given parameters.
* @param params list of parameters (may be <code>null</code>)
*/
public PreparedStatementCreator newPreparedStatementCreator(List params) {
return new PreparedStatementCreatorImpl(params != null ? params : Collections.EMPTY_LIST);
public PreparedStatementCreator newPreparedStatementCreator(List<?> params) {
return new PreparedStatementCreatorImpl(params != null ? params : Collections.emptyList());
}
/**
@ -172,7 +171,7 @@ public class PreparedStatementCreatorFactory {
* @param params the parameter array (may be <code>null</code>)
*/
public PreparedStatementCreator newPreparedStatementCreator(Object[] params) {
return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.EMPTY_LIST);
return new PreparedStatementCreatorImpl(params != null ? Arrays.asList(params) : Collections.emptyList());
}
/**
@ -183,7 +182,7 @@ public class PreparedStatementCreatorFactory {
*/
public PreparedStatementCreator newPreparedStatementCreator(String sqlToUse, Object[] params) {
return new PreparedStatementCreatorImpl(
sqlToUse, params != null ? Arrays.asList(params) : Collections.EMPTY_LIST);
sqlToUse, params != null ? Arrays.asList(params) : Collections.emptyList());
}
@ -197,7 +196,7 @@ public class PreparedStatementCreatorFactory {
private final List parameters;
public PreparedStatementCreatorImpl(List parameters) {
public PreparedStatementCreatorImpl(List<?> parameters) {
this(sql, parameters);
}
@ -207,11 +206,11 @@ public class PreparedStatementCreatorFactory {
this.parameters = parameters;
if (this.parameters.size() != declaredParameters.size()) {
// account for named parameters being used multiple times
Set names = new HashSet();
Set<String> names = new HashSet<String>();
for (int i = 0; i < parameters.size(); i++) {
Object o = parameters.get(i);
if (o instanceof SqlParameterValue) {
names.add(((SqlParameterValue)o).getName());
Object param = parameters.get(i);
if (param instanceof SqlParameterValue) {
names.add(((SqlParameterValue) param).getName());
}
else {
names.add("Parameter #" + i);
@ -279,16 +278,14 @@ public class PreparedStatementCreatorFactory {
" given only " + declaredParameters.size() + " parameters");
}
declaredParameter = (SqlParameter) declaredParameters.get(i);
declaredParameter = declaredParameters.get(i);
}
if (in instanceof Collection && declaredParameter.getSqlType() != Types.ARRAY) {
Collection entries = (Collection) in;
for (Iterator it = entries.iterator(); it.hasNext();) {
Object entry = it.next();
for (Object entry : entries) {
if (entry instanceof Object[]) {
Object[] valueArray = ((Object[])entry);
for (int k = 0; k < valueArray.length; k++) {
Object argValue = valueArray[k];
for (Object argValue : valueArray) {
StatementCreatorUtils.setParameterValue(psToUse, sqlColIndx++, declaredParameter, argValue);
}
}
@ -313,9 +310,10 @@ public class PreparedStatementCreatorFactory {
@Override
public String toString() {
StringBuffer buf = new StringBuffer("PreparedStatementCreatorFactory.PreparedStatementCreatorImpl: sql=[");
buf.append(sql).append("]; parameters=").append(this.parameters);
return buf.toString();
StringBuilder sb = new StringBuilder();
sb.append("PreparedStatementCreatorFactory.PreparedStatementCreatorImpl: sql=[");
sb.append(sql).append("]; parameters=").append(this.parameters);
return sb.toString();
}
}

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");
* you may not use this file except in compliance with the License.
@ -46,7 +46,7 @@ import org.springframework.dao.DataAccessException;
* @see RowMapper
* @see org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor
*/
public interface ResultSetExtractor {
public interface ResultSetExtractor<T> {
/**
* Implementations must implement this method to process the entire ResultSet.
@ -58,6 +58,6 @@ public interface ResultSetExtractor {
* values or navigating (that is, there's no need to catch SQLException)
* @throws DataAccessException in case of custom exceptions
*/
Object extractData(ResultSet rs) throws SQLException, DataAccessException;
T extractData(ResultSet rs) throws SQLException, DataAccessException;
}

View File

@ -108,7 +108,7 @@ public class ResultSetSupportingSqlParameter extends SqlParameter {
* Return the ResultSetExtractor held by this parameter, if any.
*/
public ResultSetExtractor getResultSetExtractor() {
return resultSetExtractor;
return this.resultSetExtractor;
}
/**

View File

@ -45,7 +45,7 @@ import java.sql.SQLException;
* @see ResultSetExtractor
* @see org.springframework.jdbc.object.MappingSqlQuery
*/
public interface RowMapper {
public interface RowMapper<T> {
/**
* Implementations must implement this method to map each row of data
@ -57,7 +57,7 @@ public interface RowMapper {
* @throws SQLException if a SQLException is encountered getting
* column values (that is, there's no need to catch SQLException)
*/
Object mapRow(ResultSet rs, int rowNum) throws SQLException;
T mapRow(ResultSet rs, int rowNum) throws SQLException;
}

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 use this file except in compliance with the License.
@ -57,9 +57,9 @@ import org.springframework.util.Assert;
* @see JdbcTemplate
* @see org.springframework.jdbc.object.MappingSqlQuery
*/
public class RowMapperResultSetExtractor implements ResultSetExtractor {
public class RowMapperResultSetExtractor<T> implements ResultSetExtractor<List<T>> {
private final RowMapper rowMapper;
private final RowMapper<T> rowMapper;
private final int rowsExpected;
@ -68,7 +68,7 @@ public class RowMapperResultSetExtractor implements ResultSetExtractor {
* Create a new RowMapperResultSetExtractor.
* @param rowMapper the RowMapper which creates an object for each row
*/
public RowMapperResultSetExtractor(RowMapper rowMapper) {
public RowMapperResultSetExtractor(RowMapper<T> rowMapper) {
this(rowMapper, 0);
}
@ -78,15 +78,15 @@ public class RowMapperResultSetExtractor implements ResultSetExtractor {
* @param rowsExpected the number of expected rows
* (just used for optimized collection handling)
*/
public RowMapperResultSetExtractor(RowMapper rowMapper, int rowsExpected) {
public RowMapperResultSetExtractor(RowMapper<T> rowMapper, int rowsExpected) {
Assert.notNull(rowMapper, "RowMapper is required");
this.rowMapper = rowMapper;
this.rowsExpected = rowsExpected;
}
public Object extractData(ResultSet rs) throws SQLException {
List results = (this.rowsExpected > 0 ? new ArrayList(this.rowsExpected) : new ArrayList());
public List<T> extractData(ResultSet rs) throws SQLException {
List<T> results = (this.rowsExpected > 0 ? new ArrayList<T>(this.rowsExpected) : new ArrayList<T>());
int rowNum = 0;
while (rs.next()) {
results.add(this.rowMapper.mapRow(rs, rowNum++));

View File

@ -39,9 +39,9 @@ import org.springframework.util.NumberUtils;
* @see JdbcTemplate#queryForList(String, Class)
* @see JdbcTemplate#queryForObject(String, Class)
*/
public class SingleColumnRowMapper implements RowMapper {
public class SingleColumnRowMapper<T> implements RowMapper<T> {
private Class requiredType;
private Class<T> requiredType;
/**
@ -55,7 +55,7 @@ public class SingleColumnRowMapper implements RowMapper {
* Create a new SingleColumnRowMapper.
* @param requiredType the type that each result object is expected to match
*/
public SingleColumnRowMapper(Class requiredType) {
public SingleColumnRowMapper(Class<T> requiredType) {
this.requiredType = requiredType;
}
@ -64,7 +64,7 @@ public class SingleColumnRowMapper implements RowMapper {
* <p>If not specified, the column value will be exposed as
* returned by the JDBC driver.
*/
public void setRequiredType(Class requiredType) {
public void setRequiredType(Class<T> requiredType) {
this.requiredType = requiredType;
}
@ -78,7 +78,8 @@ public class SingleColumnRowMapper implements RowMapper {
* @see #getColumnValue(java.sql.ResultSet, int, Class)
* @see #convertValueToRequiredType(Object, Class)
*/
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
@SuppressWarnings("unchecked")
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
// Validate column count.
ResultSetMetaData rsmd = rs.getMetaData();
int nrOfColumns = rsmd.getColumnCount();
@ -91,7 +92,7 @@ public class SingleColumnRowMapper implements RowMapper {
if (result != null && this.requiredType != null && !this.requiredType.isInstance(result)) {
// Extracted value does not match already: try to convert it.
try {
return convertValueToRequiredType(result, this.requiredType);
return (T) convertValueToRequiredType(result, this.requiredType);
}
catch (IllegalArgumentException ex) {
throw new TypeMismatchDataAccessException(
@ -99,7 +100,7 @@ public class SingleColumnRowMapper implements RowMapper {
rsmd.getColumnTypeName(1) + "': " + ex.getMessage());
}
}
return result;
return (T) result;
}
/**

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");
* you may not use this file except in compliance with the License.
@ -74,7 +74,7 @@ public class SqlParameter {
*/
public SqlParameter(int sqlType, int scale) {
this.sqlType = sqlType;
this.scale = new Integer(scale);
this.scale = scale;
}
/**
@ -109,7 +109,7 @@ public class SqlParameter {
public SqlParameter(String name, int sqlType, int scale) {
this.name = name;
this.sqlType = sqlType;
this.scale = new Integer(scale);
this.scale = scale;
}
/**
@ -177,11 +177,11 @@ public class SqlParameter {
* Convert a list of JDBC types, as defined in <code>java.sql.Types</code>,
* to a List of SqlParameter objects as used in this package.
*/
public static List sqlTypesToAnonymousParameterList(int[] types) {
List result = new LinkedList();
public static List<SqlParameter> sqlTypesToAnonymousParameterList(int[] types) {
List<SqlParameter> result = new LinkedList<SqlParameter>();
if (types != null) {
for (int i = 0; i < types.length; i++) {
result.add(new SqlParameter(types[i]));
for (int type : types) {
result.add(new SqlParameter(type));
}
}
return result;

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");
* you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.jdbc.core;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import com.sun.rowset.CachedRowSetImpl;
@ -32,9 +31,7 @@ import org.springframework.jdbc.support.rowset.SqlRowSet;
*
* <p>The default implementation uses a standard JDBC CachedRowSet underneath.
* This means that JDBC RowSet support needs to be available at runtime:
* by default, Sun's <code>com.sun.rowset.CachedRowSetImpl</code> class is
* used, which is part of JDK 1.5+ and also available separately as part of
* Sun's JDBC RowSet Implementations download (rowset.jar).
* by default, Sun's <code>com.sun.rowset.CachedRowSetImpl</code> class.
*
* @author Juergen Hoeller
* @since 1.2
@ -43,9 +40,9 @@ import org.springframework.jdbc.support.rowset.SqlRowSet;
* @see JdbcTemplate#queryForRowSet(String)
* @see javax.sql.rowset.CachedRowSet
*/
public class SqlRowSetResultSetExtractor implements ResultSetExtractor {
public class SqlRowSetResultSetExtractor implements ResultSetExtractor<SqlRowSet> {
public Object extractData(ResultSet rs) throws SQLException {
public SqlRowSet extractData(ResultSet rs) throws SQLException {
return createSqlRowSet(rs);
}
@ -71,9 +68,7 @@ public class SqlRowSetResultSetExtractor implements ResultSetExtractor {
* Create a new CachedRowSet instance, to be populated by
* the <code>createSqlRowSet</code> implementation.
* <p>The default implementation creates a new instance of
* Sun's <code>com.sun.rowset.CachedRowSetImpl</code> class,
* which is part of JDK 1.5+ and also available separately
* as part of Sun's JDBC RowSet Implementations download.
* Sun's <code>com.sun.rowset.CachedRowSetImpl</code> class.
* @return a new CachedRowSet instance
* @throws SQLException if thrown by JDBC methods
* @see #createSqlRowSet

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");
* you may not use this file except in compliance with the License.
@ -33,7 +33,7 @@ import org.springframework.dao.DataAccessException;
* @since 16.03.2004
* @see JdbcTemplate#execute(StatementCallback)
*/
public interface StatementCallback {
public interface StatementCallback<T> {
/**
* Gets called by <code>JdbcTemplate.execute</code> with an active JDBC
@ -68,6 +68,6 @@ public interface StatementCallback {
* @see JdbcTemplate#queryForObject(String, Class)
* @see JdbcTemplate#queryForRowSet(String)
*/
Object doInStatement(Statement stmt) throws SQLException, DataAccessException;
T doInStatement(Statement stmt) throws SQLException, DataAccessException;
}

View File

@ -61,32 +61,32 @@ public abstract class StatementCreatorUtils {
private static final Log logger = LogFactory.getLog(StatementCreatorUtils.class);
private static Map javaTypeToSqlTypeMap = new HashMap(32);
private static Map<Class, Integer> javaTypeToSqlTypeMap = new HashMap<Class, Integer>(32);
static {
/* JDBC 3.0 only - not compatible with e.g. MySQL at present
javaTypeToSqlTypeMap.put(boolean.class, new Integer(Types.BOOLEAN));
javaTypeToSqlTypeMap.put(Boolean.class, new Integer(Types.BOOLEAN));
*/
javaTypeToSqlTypeMap.put(byte.class, new Integer(Types.TINYINT));
javaTypeToSqlTypeMap.put(Byte.class, new Integer(Types.TINYINT));
javaTypeToSqlTypeMap.put(short.class, new Integer(Types.SMALLINT));
javaTypeToSqlTypeMap.put(Short.class, new Integer(Types.SMALLINT));
javaTypeToSqlTypeMap.put(int.class, new Integer(Types.INTEGER));
javaTypeToSqlTypeMap.put(Integer.class, new Integer(Types.INTEGER));
javaTypeToSqlTypeMap.put(long.class, new Integer(Types.BIGINT));
javaTypeToSqlTypeMap.put(Long.class, new Integer(Types.BIGINT));
javaTypeToSqlTypeMap.put(BigInteger.class, new Integer(Types.BIGINT));
javaTypeToSqlTypeMap.put(float.class, new Integer(Types.FLOAT));
javaTypeToSqlTypeMap.put(Float.class, new Integer(Types.FLOAT));
javaTypeToSqlTypeMap.put(double.class, new Integer(Types.DOUBLE));
javaTypeToSqlTypeMap.put(Double.class, new Integer(Types.DOUBLE));
javaTypeToSqlTypeMap.put(BigDecimal.class, new Integer(Types.DECIMAL));
javaTypeToSqlTypeMap.put(java.sql.Date.class, new Integer(Types.DATE));
javaTypeToSqlTypeMap.put(java.sql.Time.class, new Integer(Types.TIME));
javaTypeToSqlTypeMap.put(java.sql.Timestamp.class, new Integer(Types.TIMESTAMP));
javaTypeToSqlTypeMap.put(Blob.class, new Integer(Types.BLOB));
javaTypeToSqlTypeMap.put(Clob.class, new Integer(Types.CLOB));
javaTypeToSqlTypeMap.put(byte.class, Types.TINYINT);
javaTypeToSqlTypeMap.put(Byte.class, Types.TINYINT);
javaTypeToSqlTypeMap.put(short.class, Types.SMALLINT);
javaTypeToSqlTypeMap.put(Short.class, Types.SMALLINT);
javaTypeToSqlTypeMap.put(int.class, Types.INTEGER);
javaTypeToSqlTypeMap.put(Integer.class, Types.INTEGER);
javaTypeToSqlTypeMap.put(long.class, Types.BIGINT);
javaTypeToSqlTypeMap.put(Long.class, Types.BIGINT);
javaTypeToSqlTypeMap.put(BigInteger.class, Types.BIGINT);
javaTypeToSqlTypeMap.put(float.class, Types.FLOAT);
javaTypeToSqlTypeMap.put(Float.class, Types.FLOAT);
javaTypeToSqlTypeMap.put(double.class, Types.DOUBLE);
javaTypeToSqlTypeMap.put(Double.class, Types.DOUBLE);
javaTypeToSqlTypeMap.put(BigDecimal.class, Types.DECIMAL);
javaTypeToSqlTypeMap.put(java.sql.Date.class, Types.DATE);
javaTypeToSqlTypeMap.put(java.sql.Time.class, Types.TIME);
javaTypeToSqlTypeMap.put(java.sql.Timestamp.class, Types.TIMESTAMP);
javaTypeToSqlTypeMap.put(Blob.class, Types.BLOB);
javaTypeToSqlTypeMap.put(Clob.class, Types.CLOB);
}
@ -96,9 +96,9 @@ public abstract class StatementCreatorUtils {
* @return the corresponding SQL type, or <code>null</code> if none found
*/
public static int javaTypeToSqlParameterType(Class javaType) {
Integer sqlType = (Integer) javaTypeToSqlTypeMap.get(javaType);
Integer sqlType = javaTypeToSqlTypeMap.get(javaType);
if (sqlType != null) {
return sqlType.intValue();
return sqlType;
}
if (Number.class.isAssignableFrom(javaType)) {
return Types.NUMERIC;
@ -273,7 +273,7 @@ public abstract class StatementCreatorUtils {
ps.setBigDecimal(paramIndex, (BigDecimal) inValue);
}
else if (scale != null) {
ps.setObject(paramIndex, inValue, sqlType, scale.intValue());
ps.setObject(paramIndex, inValue, sqlType, scale);
}
else {
ps.setObject(paramIndex, inValue, sqlType);
@ -394,8 +394,7 @@ public abstract class StatementCreatorUtils {
*/
public static void cleanupParameters(Collection paramValues) {
if (paramValues != null) {
for (Iterator it = paramValues.iterator(); it.hasNext();) {
Object inValue = it.next();
for (Object inValue : paramValues) {
if (inValue instanceof DisposableSqlTypeValue) {
((DisposableSqlTypeValue) inValue).cleanup();
}

View File

@ -69,7 +69,7 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource {
* Create a new MapSqlParameterSource based on a Map.
* @param values a Map holding existing parameter values (can be <code>null</code>)
*/
public MapSqlParameterSource(Map<String, Object> values) {
public MapSqlParameterSource(Map<String, ?> values) {
addValues(values);
}
@ -128,9 +128,9 @@ public class MapSqlParameterSource extends AbstractSqlParameterSource {
* @return a reference to this parameter source,
* so it's possible to chain several calls together
*/
public MapSqlParameterSource addValues(Map<String, Object> values) {
public MapSqlParameterSource addValues(Map<String, ?> values) {
if (values != null) {
for (Map.Entry<String, Object> entry : values.entrySet()) {
for (Map.Entry<String, ?> entry : values.entrySet()) {
this.values.put(entry.getKey(), entry.getValue());
if (entry.getValue() instanceof SqlParameterValue) {
SqlParameterValue value = (SqlParameterValue) entry.getValue();

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");
* you may not use this file except in compliance with the License.
@ -67,7 +67,7 @@ public interface NamedParameterJdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback action)
<T> T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback<T> action)
throws DataAccessException;
/**
@ -85,7 +85,7 @@ public interface NamedParameterJdbcOperations {
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException if there is any problem
*/
Object execute(String sql, Map paramMap, PreparedStatementCallback action)
<T> T execute(String sql, Map<String, Object> paramMap, PreparedStatementCallback<T> action)
throws DataAccessException;
/**
@ -98,7 +98,7 @@ public interface NamedParameterJdbcOperations {
* @return an arbitrary result object, as returned by the ResultSetExtractor
* @throws DataAccessException if the query fails
*/
Object query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse)
<T> T query(String sql, SqlParameterSource paramSource, ResultSetExtractor<T> rse)
throws DataAccessException;
/**
@ -112,7 +112,8 @@ public interface NamedParameterJdbcOperations {
* @return an arbitrary result object, as returned by the ResultSetExtractor
* @throws org.springframework.dao.DataAccessException if the query fails
*/
Object query(String sql, Map paramMap, ResultSetExtractor rse) throws DataAccessException;
<T> T query(String sql, Map<String, Object> paramMap, ResultSetExtractor<T> rse)
throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
@ -136,7 +137,7 @@ public interface NamedParameterJdbcOperations {
* @param rch object that will extract results, one row at a time
* @throws org.springframework.dao.DataAccessException if the query fails
*/
void query(String sql, Map paramMap, RowCallbackHandler rch) throws DataAccessException;
void query(String sql, Map<String, Object> paramMap, RowCallbackHandler rch) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list
@ -148,7 +149,7 @@ public interface NamedParameterJdbcOperations {
* @return the result List, containing mapped objects
* @throws org.springframework.dao.DataAccessException if the query fails
*/
List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper)
<T> List<T> query(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
throws DataAccessException;
/**
@ -162,7 +163,8 @@ public interface NamedParameterJdbcOperations {
* @return the result List, containing mapped objects
* @throws org.springframework.dao.DataAccessException if the query fails
*/
List query(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException;
<T> List<T> query(String sql, Map<String, Object> paramMap, RowMapper<T> rowMapper)
throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list
@ -177,7 +179,7 @@ public interface NamedParameterJdbcOperations {
* one column in that row
* @throws org.springframework.dao.DataAccessException if the query fails
*/
Object queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper)
<T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
throws DataAccessException;
/**
@ -194,7 +196,8 @@ public interface NamedParameterJdbcOperations {
* one column in that row
* @throws org.springframework.dao.DataAccessException if the query fails
*/
Object queryForObject(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException;
<T> T queryForObject(String sql, Map<String, Object> paramMap, RowMapper<T> rowMapper)
throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -211,7 +214,7 @@ public interface NamedParameterJdbcOperations {
* @throws org.springframework.dao.DataAccessException if the query fails
* @see org.springframework.jdbc.core.JdbcTemplate#queryForObject(String, Class)
*/
Object queryForObject(String sql, SqlParameterSource paramSource, Class requiredType)
<T> T queryForObject(String sql, SqlParameterSource paramSource, Class<T> requiredType)
throws DataAccessException;
/**
@ -230,7 +233,8 @@ public interface NamedParameterJdbcOperations {
* @throws org.springframework.dao.DataAccessException if the query fails
* @see org.springframework.jdbc.core.JdbcTemplate#queryForObject(String, Class)
*/
Object queryForObject(String sql, Map paramMap, Class requiredType) throws DataAccessException;
<T> T queryForObject(String sql, Map<String, Object> paramMap, Class<T> requiredType)
throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -247,7 +251,7 @@ public interface NamedParameterJdbcOperations {
* @see org.springframework.jdbc.core.JdbcTemplate#queryForMap(String)
* @see org.springframework.jdbc.core.ColumnMapRowMapper
*/
Map queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException;
Map<String, Object> queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -268,7 +272,7 @@ public interface NamedParameterJdbcOperations {
* @see org.springframework.jdbc.core.JdbcTemplate#queryForMap(String)
* @see org.springframework.jdbc.core.ColumnMapRowMapper
*/
Map queryForMap(String sql, Map paramMap) throws DataAccessException;
Map<String, Object> queryForMap(String sql, Map<String, Object> paramMap) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -301,7 +305,7 @@ public interface NamedParameterJdbcOperations {
* @throws org.springframework.dao.DataAccessException if the query fails
* @see org.springframework.jdbc.core.JdbcTemplate#queryForLong(String)
*/
long queryForLong(String sql, Map paramMap) throws DataAccessException;
long queryForLong(String sql, Map<String, Object> paramMap) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -332,7 +336,7 @@ public interface NamedParameterJdbcOperations {
* @throws org.springframework.dao.DataAccessException if the query fails
* @see org.springframework.jdbc.core.JdbcTemplate#queryForInt(String)
*/
int queryForInt(String sql, Map paramMap) throws DataAccessException;
int queryForInt(String sql, Map<String, Object> paramMap) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -348,7 +352,7 @@ public interface NamedParameterJdbcOperations {
* @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String, Class)
* @see org.springframework.jdbc.core.SingleColumnRowMapper
*/
List queryForList(String sql, SqlParameterSource paramSource, Class elementType)
<T> List<T> queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
throws DataAccessException;
/**
@ -366,7 +370,8 @@ public interface NamedParameterJdbcOperations {
* @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String, Class)
* @see org.springframework.jdbc.core.SingleColumnRowMapper
*/
List queryForList(String sql, Map paramMap, Class elementType) throws DataAccessException;
<T> List<T> queryForList(String sql, Map<String, Object> paramMap, Class<T> elementType)
throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -381,7 +386,7 @@ public interface NamedParameterJdbcOperations {
* @throws org.springframework.dao.DataAccessException if the query fails
* @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String)
*/
List queryForList(String sql, SqlParameterSource paramSource) throws DataAccessException;
List<Map<String, Object>> queryForList(String sql, SqlParameterSource paramSource) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -397,7 +402,7 @@ public interface NamedParameterJdbcOperations {
* @throws org.springframework.dao.DataAccessException if the query fails
* @see org.springframework.jdbc.core.JdbcTemplate#queryForList(String)
*/
List queryForList(String sql, Map paramMap) throws DataAccessException;
List<Map<String, Object>> queryForList(String sql, Map<String, Object> paramMap) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a
@ -438,7 +443,7 @@ public interface NamedParameterJdbcOperations {
* @see org.springframework.jdbc.core.SqlRowSetResultSetExtractor
* @see javax.sql.rowset.CachedRowSet
*/
SqlRowSet queryForRowSet(String sql, Map paramMap) throws DataAccessException;
SqlRowSet queryForRowSet(String sql, Map<String, Object> paramMap) throws DataAccessException;
/**
* Issue an update via a prepared statement, binding the given arguments.
@ -457,7 +462,7 @@ public interface NamedParameterJdbcOperations {
* @return the number of rows affected
* @throws org.springframework.dao.DataAccessException if there is any problem issuing the update
*/
int update(String sql, Map paramMap) throws DataAccessException;
int update(String sql, Map<String, Object> paramMap) throws DataAccessException;
/**
* Issue an update via a prepared statement, binding the given arguments,
@ -485,8 +490,7 @@ public interface NamedParameterJdbcOperations {
* @see MapSqlParameterSource
* @see org.springframework.jdbc.support.GeneratedKeyHolder
*/
int update(
String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
int update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
throws DataAccessException;
}

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");
* you may not use this file except in compliance with the License.
@ -64,7 +64,7 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations
private final JdbcOperations classicJdbcTemplate;
/** Map of original SQL String to ParsedSql representation */
private final Map parsedSqlCache = new HashMap();
private final Map<String, ParsedSql> parsedSqlCache = new HashMap<String, ParsedSql>();
/**
@ -97,23 +97,27 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations
}
public Object execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback action)
public <T> T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback<T> action)
throws DataAccessException {
return getJdbcOperations().execute(getPreparedStatementCreator(sql, paramSource), action);
}
public Object execute(String sql, Map paramMap, PreparedStatementCallback action) throws DataAccessException {
public <T> T execute(String sql, Map<String, Object> paramMap, PreparedStatementCallback<T> action)
throws DataAccessException {
return execute(sql, new MapSqlParameterSource(paramMap), action);
}
public Object query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse)
public <T> T query(String sql, SqlParameterSource paramSource, ResultSetExtractor<T> rse)
throws DataAccessException {
return getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rse);
}
public Object query(String sql, Map paramMap, ResultSetExtractor rse) throws DataAccessException {
public <T> T query(String sql, Map<String, Object> paramMap, ResultSetExtractor<T> rse)
throws DataAccessException {
return query(sql, new MapSqlParameterSource(paramMap), rse);
}
@ -123,90 +127,105 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations
getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rch);
}
public void query(String sql, Map paramMap, RowCallbackHandler rch) throws DataAccessException {
public void query(String sql, Map<String, Object> paramMap, RowCallbackHandler rch)
throws DataAccessException {
query(sql, new MapSqlParameterSource(paramMap), rch);
}
public List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper)
public <T> List<T> query(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
throws DataAccessException {
return getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper);
}
public List query(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException {
public <T> List<T> query(String sql, Map<String, Object> paramMap, RowMapper<T> rowMapper)
throws DataAccessException {
return query(sql, new MapSqlParameterSource(paramMap), rowMapper);
}
public Object queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper)
public <T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
throws DataAccessException {
List results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper);
List<T> results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper);
return DataAccessUtils.requiredSingleResult(results);
}
public Object queryForObject(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException {
public <T> T queryForObject(String sql, Map<String, Object> paramMap, RowMapper<T>rowMapper)
throws DataAccessException {
return queryForObject(sql, new MapSqlParameterSource(paramMap), rowMapper);
}
public Object queryForObject(String sql, SqlParameterSource paramSource, Class requiredType)
public <T> T queryForObject(String sql, SqlParameterSource paramSource, Class<T> requiredType)
throws DataAccessException {
return queryForObject(sql, paramSource, new SingleColumnRowMapper(requiredType));
return queryForObject(sql, paramSource, new SingleColumnRowMapper<T>(requiredType));
}
public Object queryForObject(String sql, Map paramMap, Class requiredType) throws DataAccessException {
return queryForObject(sql, paramMap, new SingleColumnRowMapper(requiredType));
public <T> T queryForObject(String sql, Map<String, Object> paramMap, Class<T> requiredType)
throws DataAccessException {
return queryForObject(sql, paramMap, new SingleColumnRowMapper<T>(requiredType));
}
public Map queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException {
return (Map) queryForObject(sql, paramSource, new ColumnMapRowMapper());
public Map<String, Object> queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException {
return queryForObject(sql, paramSource, new ColumnMapRowMapper());
}
public Map queryForMap(String sql, Map paramMap) throws DataAccessException {
return (Map) queryForObject(sql, paramMap, new ColumnMapRowMapper());
public Map<String, Object> queryForMap(String sql, Map<String, Object> paramMap) throws DataAccessException {
return queryForObject(sql, paramMap, new ColumnMapRowMapper());
}
public long queryForLong(String sql, SqlParameterSource paramSource) throws DataAccessException {
Number number = (Number) queryForObject(sql, paramSource, Number.class);
Number number = queryForObject(sql, paramSource, Number.class);
return (number != null ? number.longValue() : 0);
}
public long queryForLong(String sql, Map paramMap) throws DataAccessException {
public long queryForLong(String sql, Map<String, Object> paramMap) throws DataAccessException {
return queryForLong(sql, new MapSqlParameterSource(paramMap));
}
public int queryForInt(String sql, SqlParameterSource paramSource) throws DataAccessException {
Number number = (Number) queryForObject(sql, paramSource, Number.class);
Number number = queryForObject(sql, paramSource, Number.class);
return (number != null ? number.intValue() : 0);
}
public int queryForInt(String sql, Map paramMap) throws DataAccessException {
public int queryForInt(String sql, Map<String, Object> paramMap) throws DataAccessException {
return queryForInt(sql, new MapSqlParameterSource(paramMap));
}
public List queryForList(String sql, SqlParameterSource paramSource, Class elementType)
public <T> List<T> queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
throws DataAccessException {
return query(sql, paramSource, new SingleColumnRowMapper(elementType));
return query(sql, paramSource, new SingleColumnRowMapper<T>(elementType));
}
public List queryForList(String sql, Map paramMap, Class elementType) throws DataAccessException {
public <T> List<T> queryForList(String sql, Map<String, Object> paramMap, Class<T> elementType)
throws DataAccessException {
return queryForList(sql, new MapSqlParameterSource(paramMap), elementType);
}
public List queryForList(String sql, SqlParameterSource paramSource) throws DataAccessException {
public List<Map<String, Object>> queryForList(String sql, SqlParameterSource paramSource)
throws DataAccessException {
return query(sql, paramSource, new ColumnMapRowMapper());
}
public List queryForList(String sql, Map paramMap) throws DataAccessException {
public List<Map<String, Object>> queryForList(String sql, Map<String, Object> paramMap)
throws DataAccessException {
return queryForList(sql, new MapSqlParameterSource(paramMap));
}
public SqlRowSet queryForRowSet(String sql, SqlParameterSource paramSource) throws DataAccessException {
return (SqlRowSet) getJdbcOperations().query(
return getJdbcOperations().query(
getPreparedStatementCreator(sql, paramSource), new SqlRowSetResultSetExtractor());
}
public SqlRowSet queryForRowSet(String sql, Map paramMap) throws DataAccessException {
public SqlRowSet queryForRowSet(String sql, Map<String, Object> paramMap) throws DataAccessException {
return queryForRowSet(sql, new MapSqlParameterSource(paramMap));
}
@ -214,7 +233,7 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations
return getJdbcOperations().update(getPreparedStatementCreator(sql, paramSource));
}
public int update(String sql, Map paramMap) throws DataAccessException {
public int update(String sql, Map<String, Object> paramMap) throws DataAccessException {
return update(sql, new MapSqlParameterSource(paramMap));
}
@ -266,7 +285,7 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations
*/
protected ParsedSql getParsedSql(String sql) {
synchronized (this.parsedSqlCache) {
ParsedSql parsedSql = (ParsedSql) this.parsedSqlCache.get(sql);
ParsedSql parsedSql = this.parsedSqlCache.get(sql);
if (parsedSql == null) {
parsedSql = NamedParameterUtils.parseSqlStatement(sql);
this.parsedSqlCache.put(sql, parsedSql);

View File

@ -191,7 +191,7 @@ public abstract class NamedParameterUtils {
*/
public static String substituteNamedParameters(ParsedSql parsedSql, SqlParameterSource paramSource) {
String originalSql = parsedSql.getOriginalSql();
StringBuffer actualSql = new StringBuffer();
StringBuilder actualSql = new StringBuilder();
List paramNames = parsedSql.getParameterNames();
int lastIndex = 0;
for (int i = 0; i < paramNames.size(); i++) {
@ -379,7 +379,7 @@ public abstract class NamedParameterUtils {
* @param paramMap the Map of parameters
* @return the array of values
*/
public static Object[] buildValueArray(String sql, Map paramMap) {
public static Object[] buildValueArray(String sql, Map<String, ?> paramMap) {
ParsedSql parsedSql = parseSqlStatement(sql);
return buildValueArray(parsedSql, new MapSqlParameterSource(paramMap), null);
}

View File

@ -16,9 +16,6 @@
package org.springframework.jdbc.core.simple;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
/**
@ -49,25 +46,9 @@ import org.springframework.jdbc.core.BeanPropertyRowMapper;
* @since 2.5
* @see ParameterizedRowMapper
*/
public class ParameterizedBeanPropertyRowMapper<T> extends BeanPropertyRowMapper
public class ParameterizedBeanPropertyRowMapper<T> extends BeanPropertyRowMapper<T>
implements ParameterizedRowMapper<T> {
/**
* Create a new ParameterizedBeanPropertyRowMapper.
* <p>Generally prefer the {@link #newInstance(Class)} method instead,
* which avoids the need for specifying the mapped type twice.
* @see #setMappedClass
*/
public ParameterizedBeanPropertyRowMapper() {
}
@Override
@SuppressWarnings("unchecked")
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
return (T) super.mapRow(rs, rowNumber);
}
/**
* Static factory method to create a new ParameterizedBeanPropertyRowMapper
* (with the mapped class specified only once).

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");
* you may not use this file except in compliance with the License.
@ -16,28 +16,18 @@
package org.springframework.jdbc.core.simple;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
/**
* Extension of the {@link org.springframework.jdbc.core.RowMapper} interface,
* adding type parameterization. Uses Java 5 covariant return types to override
* the return type of the {@link #mapRow} method to be the type parameter
* <code>T</code>.
* adding type parameterization. As of Spring 3.0, this is equivalent to
* using the RowMapper interface directly.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.jdbc.core.simple.SimpleJdbcOperations
*/
public interface ParameterizedRowMapper<T> extends RowMapper {
/**
* Implementations should return the object representation of
* the current row in the supplied {@link ResultSet}.
* @see org.springframework.jdbc.core.RowMapper#mapRow
*/
T mapRow(ResultSet rs, int rowNum) throws SQLException;
public interface ParameterizedRowMapper<T> extends RowMapper<T> {
}

View File

@ -16,9 +16,6 @@
package org.springframework.jdbc.core.simple;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.SingleColumnRowMapper;
/**
@ -36,25 +33,9 @@ import org.springframework.jdbc.core.SingleColumnRowMapper;
* @author Juergen Hoeller
* @since 2.5.2
*/
public class ParameterizedSingleColumnRowMapper<T> extends SingleColumnRowMapper
public class ParameterizedSingleColumnRowMapper<T> extends SingleColumnRowMapper<T>
implements ParameterizedRowMapper<T> {
/**
* Create a new ParameterizedSingleColumnRowMapper.
* <p>Generally prefer the {@link #newInstance(Class)} method instead,
* which avoids the need for specifying the mapped type twice.
* @see #setRequiredType
*/
public ParameterizedSingleColumnRowMapper() {
}
@Override
@SuppressWarnings("unchecked")
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
return (T) super.mapRow(rs, rowNumber);
}
/**
* Static factory method to create a new ParameterizedSingleColumnRowMapper
* (with the required type specified only once).

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");
* you may not use this file except in compliance with the License.
@ -58,9 +58,9 @@ public interface SimpleJdbcOperations {
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* and a map containing the arguments.
* @param sql the SQL query to run.
* @param args the map containing the arguments for the query.
* @param args the map containing the arguments for the query
*/
int queryForInt(String sql, Map args) throws DataAccessException;
int queryForInt(String sql, Map<String, Object> args) throws DataAccessException;
/**
* Query for an <code>int</code> passing in a SQL query
@ -77,7 +77,7 @@ public interface SimpleJdbcOperations {
* using the standard '?' placeholders for parameters
* and a variable number of arguments.
* @param sql the SQL query to run.
* @param args the variable number of arguments for the query.
* @param args the variable number of arguments for the query
*/
int queryForInt(String sql, Object... args) throws DataAccessException;
@ -87,9 +87,9 @@ public interface SimpleJdbcOperations {
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* and a map containing the arguments.
* @param sql the SQL query to run.
* @param args the map containing the arguments for the query.
* @param args the map containing the arguments for the query
*/
long queryForLong(String sql, Map args) throws DataAccessException;
long queryForLong(String sql, Map<String, Object> args) throws DataAccessException;
/**
* Query for an <code>long</code> passing in a SQL query
@ -97,7 +97,7 @@ public interface SimpleJdbcOperations {
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* and a <code>SqlParameterSource</code> containing the arguments.
* @param sql the SQL query to run.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query
*/
long queryForLong(String sql, SqlParameterSource args) throws DataAccessException;
@ -106,7 +106,7 @@ public interface SimpleJdbcOperations {
* using the standard '?' placeholders for parameters
* and a variable number of arguments.
* @param sql the SQL query to run.
* @param args the variable number of arguments for the query.
* @param args the variable number of arguments for the query
*/
long queryForLong(String sql, Object... args) throws DataAccessException;
@ -114,22 +114,22 @@ public interface SimpleJdbcOperations {
* Query for an object of type <code>T</code> identified by the supplied @{@link Class}.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param requiredType the required type of the return value.
* @param args the map containing the arguments for the query.
* @param sql the SQL query to run
* @param requiredType the required type of the return value
* @param args the map containing the arguments for the query
* @see JdbcOperations#queryForObject(String, Class)
* @see JdbcOperations#queryForObject(String, Object[], Class)
*/
<T> T queryForObject(String sql, Class<T> requiredType, Map args)
<T> T queryForObject(String sql, Class<T> requiredType, Map<String, Object> args)
throws DataAccessException;
/**
* Query for an object of type <code>T</code> identified by the supplied @{@link Class}.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param requiredType the required type of the return value.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query.
* @param sql the SQL query to run
* @param requiredType the required type of the return value
* @param args the <code>SqlParameterSource</code> containing the arguments for the query
* @see JdbcOperations#queryForObject(String, Class)
* @see JdbcOperations#queryForObject(String, Object[], Class)
*/
@ -139,9 +139,9 @@ public interface SimpleJdbcOperations {
/**
* Query for an object of type <code>T</code> identified by the supplied @{@link Class}.
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL query to run.
* @param requiredType the required type of the return value.
* @param args the variable number of arguments for the query.
* @param sql the SQL query to run
* @param requiredType the required type of the return value
* @param args the variable number of arguments for the query
* @see JdbcOperations#queryForObject(String, Class)
* @see JdbcOperations#queryForObject(String, Object[], Class)
*/
@ -153,13 +153,13 @@ public interface SimpleJdbcOperations {
* {@link ParameterizedRowMapper} to the query results to the object.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param sql the SQL query to run
* @param rm the @{@link ParameterizedRowMapper} to use for result mapping
* @param args the map containing the arguments for the query.
* @param args the map containing the arguments for the query
* @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper)
* @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper)
*/
<T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Map args)
<T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Map<String, Object> args)
throws DataAccessException;
/**
@ -167,9 +167,9 @@ public interface SimpleJdbcOperations {
* {@link ParameterizedRowMapper} to the query results to the object.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param sql the SQL query to run
* @param rm the @{@link ParameterizedRowMapper} to use for result mapping
* @param args the <code>SqlParameterSource</code> containing the arguments for the query.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query
* @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper)
* @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper)
*/
@ -180,9 +180,9 @@ public interface SimpleJdbcOperations {
* Query for an object of type <code>T</code> using the supplied
* {@link ParameterizedRowMapper} to the query results to the object.
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL query to run.
* @param sql the SQL query to run
* @param rm the @{@link ParameterizedRowMapper} to use for result mapping
* @param args the variable number of arguments for the query.
* @param args the variable number of arguments for the query
* @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper)
* @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper)
*/
@ -194,13 +194,13 @@ public interface SimpleJdbcOperations {
* the supplied {@link ParameterizedRowMapper} to the query results to the object.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param sql the SQL query to run
* @param rm the @{@link ParameterizedRowMapper} to use for result mapping
* @param args the map containing the arguments for the query.
* @param args the map containing the arguments for the query
* @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper)
* @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper)
*/
<T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Map args)
<T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Map<String, Object> args)
throws DataAccessException;
/**
@ -208,9 +208,9 @@ public interface SimpleJdbcOperations {
* the supplied {@link ParameterizedRowMapper} to the query results to the object.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param sql the SQL query to run
* @param rm the @{@link ParameterizedRowMapper} to use for result mapping
* @param args the <code>SqlParameterSource</code> containing the arguments for the query.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query
* @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper)
* @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper)
*/
@ -221,9 +221,9 @@ public interface SimpleJdbcOperations {
* Query for a {@link List} of <code>Objects</code> of type <code>T</code> using
* the supplied {@link ParameterizedRowMapper} to the query results to the object.
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL query to run.
* @param sql the SQL query to run
* @param rm the @{@link ParameterizedRowMapper} to use for result mapping
* @param args the variable number of arguments for the query.
* @param args the variable number of arguments for the query
* @see JdbcOperations#queryForObject(String, org.springframework.jdbc.core.RowMapper)
* @see JdbcOperations#queryForObject(String, Object[], org.springframework.jdbc.core.RowMapper)
*/
@ -233,25 +233,25 @@ public interface SimpleJdbcOperations {
/**
* Execute the supplied query with the supplied arguments.
* <p>The query is expected to be a single row query; the result row will be
* mapped to a Map (one entry for each column, using the column name as the key).
* mapped to a Map<String, Object> (one entry for each column, using the column name as the key).
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param args the map containing the arguments for the query.
* @param sql the SQL query to run
* @param args the map containing the arguments for the query
* @see JdbcOperations#queryForMap(String)
* @see JdbcOperations#queryForMap(String, Object[])
*/
Map<String, Object> queryForMap(String sql, Map args)
Map<String, Object> queryForMap(String sql, Map<String, Object> args)
throws DataAccessException;
/**
* Execute the supplied query with the supplied arguments.
* <p>The query is expected to be a single row query; the result row will be
* mapped to a Map (one entry for each column, using the column name as the key).
* mapped to a Map<String, Object> (one entry for each column, using the column name as the key).
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query.
* @param sql the SQL query to run
* @param args the <code>SqlParameterSource</code> containing the arguments for the query
* @see JdbcOperations#queryForMap(String)
* @see JdbcOperations#queryForMap(String, Object[])
*/
@ -261,10 +261,10 @@ public interface SimpleJdbcOperations {
/**
* Execute the supplied query with the (optional) supplied arguments.
* <p>The query is expected to be a single row query; the result row will be
* mapped to a Map (one entry for each column, using the column name as the key).
* mapped to a Map<String, Object> (one entry for each column, using the column name as the key).
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL query to run.
* @param args the variable number of arguments for the query.
* @param sql the SQL query to run
* @param args the variable number of arguments for the query
* @see JdbcOperations#queryForMap(String)
* @see JdbcOperations#queryForMap(String, Object[])
*/
@ -277,12 +277,12 @@ public interface SimpleJdbcOperations {
* as described in {@link #queryForMap}
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param args the map containing the arguments for the query.
* @param sql the SQL query to run
* @param args the map containing the arguments for the query
* @see JdbcOperations#queryForList(String)
* @see JdbcOperations#queryForList(String, Object[])
*/
List<Map<String, Object>> queryForList(String sql, Map args)
List<Map<String, Object>> queryForList(String sql, Map<String, Object> args)
throws DataAccessException;
/**
@ -291,8 +291,8 @@ public interface SimpleJdbcOperations {
* as described in {@link #queryForMap}
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL query to run.
* @param args the <code>SqlParameterSource</code> containing the arguments for the query.
* @param sql the SQL query to run
* @param args the <code>SqlParameterSource</code> containing the arguments for the query
* @see JdbcOperations#queryForList(String)
* @see JdbcOperations#queryForList(String, Object[])
*/
@ -304,8 +304,8 @@ public interface SimpleJdbcOperations {
* <p>Each element in the returned {@link List} is constructed as a {@link Map}
* as described in {@link #queryForMap}
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL query to run.
* @param args the variable number of arguments for the query.
* @param sql the SQL query to run
* @param args the variable number of arguments for the query
* @see JdbcOperations#queryForList(String)
* @see JdbcOperations#queryForList(String, Object[])
*/
@ -316,20 +316,20 @@ public interface SimpleJdbcOperations {
* Execute the supplied SQL statement with (optional) supplied arguments.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL statement to execute.
* @param args the map containing the arguments for the query.
* @return the numbers of rows affected by the update.
* @param sql the SQL statement to execute
* @param args the map containing the arguments for the query
* @return the numbers of rows affected by the update
* @see NamedParameterJdbcOperations#update(String, Map)
*/
int update(String sql, Map args) throws DataAccessException;
int update(String sql, Map<String, Object> args) throws DataAccessException;
/**
* Execute the supplied SQL statement with supplied arguments.
* Uses sql with the named parameter support provided by the
* {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate}
* @param sql the SQL statement to execute.
* @param args the <code>SqlParameterSource</code> containing the arguments for the statement.
* @return the numbers of rows affected by the update.
* @param sql the SQL statement to execute
* @param args the <code>SqlParameterSource</code> containing the arguments for the statement
* @return the numbers of rows affected by the update
* @see NamedParameterJdbcOperations#update(String, SqlParameterSource)
*/
int update(String sql, SqlParameterSource args) throws DataAccessException;
@ -337,9 +337,9 @@ public interface SimpleJdbcOperations {
/**
* Execute the supplied SQL statement with supplied arguments.
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL statement to execute.
* @param args the variable number of arguments for the query.
* @return the numbers of rows affected by the update.
* @param sql the SQL statement to execute
* @param args the variable number of arguments for the query
* @return the numbers of rows affected by the update
* @see JdbcOperations#update(String)
* @see JdbcOperations#update(String, Object[])
*/
@ -348,27 +348,27 @@ public interface SimpleJdbcOperations {
/**
* Executes a batch using the supplied SQL statement with the batch of supplied arguments.
* Uses sql with the named parameter support.
* @param sql the SQL statement to execute.
* @param batchValues the array of Maps containing the batch of arguments for the query.
* @return an array containing the numbers of rows affected by each update in the batch.
* @param sql the SQL statement to execute
* @param batchValues the array of Maps containing the batch of arguments for the query
* @return an array containing the numbers of rows affected by each update in the batch
*/
public int[] batchUpdate(String sql, Map[] batchValues);
public int[] batchUpdate(String sql, Map<String, Object>[] batchValues);
/**
* Execute a batch using the supplied SQL statement with the batch of supplied arguments.
* Uses sql with the named parameter support.
* @param sql the SQL statement to execute.
* @param batchArgs the array of {@link SqlParameterSource} containing the batch of arguments for the query.
* @return an array containing the numbers of rows affected by each update in the batch.
* @param sql the SQL statement to execute
* @param batchArgs the array of {@link SqlParameterSource} containing the batch of arguments for the query
* @return an array containing the numbers of rows affected by each update in the batch
*/
public int[] batchUpdate(String sql, SqlParameterSource[] batchArgs);
/**
* Execute a batch using the supplied SQL statement with the batch of supplied arguments.
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL statement to execute.
* @param batchArgs the List of Object arrays containing the batch of arguments for the query.
* @return an array containing the numbers of rows affected by each update in the batch.
* @param sql the SQL statement to execute
* @param batchArgs the List of Object arrays containing the batch of arguments for the query
* @return an array containing the numbers of rows affected by each update in the batch
*/
public int[] batchUpdate(String sql, List<Object[]> batchArgs);
@ -376,10 +376,10 @@ public interface SimpleJdbcOperations {
* Execute a batch using the supplied SQL statement with the batch of supplied arguments.
* Uses sql with the standard '?' placeholders for parameters
* @param sql the SQL statement to execute.
* @param batchArgs the List of Object arrays containing the batch of arguments for the query.
* @param batchArgs the List of Object arrays containing the batch of arguments for the query
* @param argTypes SQL types of the arguments
* (constants from <code>java.sql.Types</code>)
* @return an array containing the numbers of rows affected by each update in the batch.
* @return an array containing the numbers of rows affected by each update in the batch
*/
public int[] batchUpdate(String sql, List<Object[]> batchArgs, int[] argTypes);

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");
* you may not use this file except in compliance with the License.
@ -107,7 +107,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations {
}
public int queryForInt(String sql, Map args) throws DataAccessException {
public int queryForInt(String sql, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().queryForInt(sql, args);
}
@ -121,7 +121,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations {
getJdbcOperations().queryForInt(sql, getArguments(args)));
}
public long queryForLong(String sql, Map args) throws DataAccessException {
public long queryForLong(String sql, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().queryForLong(sql, args);
}
@ -136,61 +136,61 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations {
}
@SuppressWarnings("unchecked")
public <T> T queryForObject(String sql, Class<T> requiredType, Map args) throws DataAccessException {
return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType);
public <T> T queryForObject(String sql, Class<T> requiredType, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType);
}
@SuppressWarnings("unchecked")
public <T> T queryForObject(String sql, Class<T> requiredType, SqlParameterSource args)
throws DataAccessException {
return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType);
return getNamedParameterJdbcOperations().queryForObject(sql, args, requiredType);
}
@SuppressWarnings("unchecked")
public <T> T queryForObject(String sql, Class<T> requiredType, Object... args) throws DataAccessException {
return (T) (ObjectUtils.isEmpty(args) ?
return (ObjectUtils.isEmpty(args) ?
getJdbcOperations().queryForObject(sql, requiredType) :
getJdbcOperations().queryForObject(sql, getArguments(args), requiredType));
}
@SuppressWarnings("unchecked")
public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Map args) throws DataAccessException {
return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, rm);
public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().queryForObject(sql, args, rm);
}
@SuppressWarnings("unchecked")
public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, SqlParameterSource args)
throws DataAccessException {
return (T) getNamedParameterJdbcOperations().queryForObject(sql, args, rm);
return getNamedParameterJdbcOperations().queryForObject(sql, args, rm);
}
@SuppressWarnings("unchecked")
public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Object... args) throws DataAccessException {
return (T) (ObjectUtils.isEmpty(args) ?
return (ObjectUtils.isEmpty(args) ?
getJdbcOperations().queryForObject(sql, rm):
getJdbcOperations().queryForObject(sql, getArguments(args), rm));
}
@SuppressWarnings("unchecked")
public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Map args) throws DataAccessException {
return (List<T>) getNamedParameterJdbcOperations().query(sql, args, rm);
public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().query(sql, args, rm);
}
@SuppressWarnings("unchecked")
public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, SqlParameterSource args)
throws DataAccessException {
return (List<T>) getNamedParameterJdbcOperations().query(sql, args, rm);
return getNamedParameterJdbcOperations().query(sql, args, rm);
}
@SuppressWarnings("unchecked")
public <T> List<T> query(String sql, ParameterizedRowMapper<T> rm, Object... args) throws DataAccessException {
return (List<T>) (ObjectUtils.isEmpty(args) ?
return (ObjectUtils.isEmpty(args) ?
getJdbcOperations().query(sql, rm) :
getJdbcOperations().query(sql, getArguments(args), rm));
}
@SuppressWarnings("unchecked")
public Map<String, Object> queryForMap(String sql, Map args) throws DataAccessException {
public Map<String, Object> queryForMap(String sql, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().queryForMap(sql, args);
}
@ -208,7 +208,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations {
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> queryForList(String sql, Map args) throws DataAccessException {
public List<Map<String, Object>> queryForList(String sql, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().queryForList(sql, args);
}
@ -225,7 +225,7 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations {
getJdbcOperations().queryForList(sql, getArguments(args)));
}
public int update(String sql, Map args) throws DataAccessException {
public int update(String sql, Map<String, Object> args) throws DataAccessException {
return getNamedParameterJdbcOperations().update(sql, args);
}
@ -247,10 +247,10 @@ public class SimpleJdbcTemplate implements SimpleJdbcOperations {
return doExecuteBatchUpdate(sql, batchArgs, argTypes);
}
public int[] batchUpdate(String sql, Map[] batchValues) {
public int[] batchUpdate(String sql, Map<String, Object>[] batchValues) {
SqlParameterSource[] batchArgs = new SqlParameterSource[batchValues.length];
int i = 0;
for (Map values : batchValues) {
for (Map<String, Object> values : batchValues) {
batchArgs[i] = new MapSqlParameterSource(values);
i++;
}

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 use this file except in compliance with the License.
@ -35,7 +35,7 @@ import org.springframework.jdbc.core.SqlTypeValue;
* <pre class="code">proc.declareParameter(new SqlParameter("myarray", Types.ARRAY, "NUMBERS"));
* ...
*
* Map in = new HashMap();
* Map&lt;String, Object&gt; in = new HashMap&lt;String, Object&gt;();
* in.put("myarray", new AbstractSqlTypeValue() {
* public Object createTypeValue(Connection con, int sqlType, String typeName) throws SQLException {
* oracle.sql.ArrayDescriptor desc = new oracle.sql.ArrayDescriptor(typeName, con);

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