INT-828, INT-829 Message mapping and method resolution are now both managed with SpEL support. INT-925 is resolved by this commit as well, since the EvaluationContext is reused for all invocations within a handler. This also appears to make the problem in INT-915 obsolete, and it lays the groundwork for INT-174 at the message-handling level.

This commit is contained in:
Mark Fisher
2009-12-22 12:51:45 +00:00
parent 59783244f1
commit 7c6e207adc
6 changed files with 394 additions and 252 deletions

View File

@@ -17,215 +17,386 @@
package org.springframework.integration.handler;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.expression.MapAccessor;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.StandardTypeConverter;
import org.springframework.integration.annotation.Header;
import org.springframework.integration.annotation.Headers;
import org.springframework.integration.annotation.Payload;
import org.springframework.integration.core.Message;
import org.springframework.integration.core.MessagingException;
import org.springframework.integration.message.MessageHandlingException;
import org.springframework.integration.util.DefaultMethodInvoker;
import org.springframework.integration.util.MethodInvoker;
import org.springframework.integration.util.ClassUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
/**
* A base or helper class for any Messaging component that acts as an adapter
* by invoking a "plain" (not Message-aware) method on a given target object.
* The target Object is mandatory, and either a {@link Method} reference, a
* 'methodName', or an Annotation type must be provided.
*
* @author Mark Fisher
* @author Marius Bogoevici
* @see ArgumentArrayMessageMapper
* @since 2.0
*/
public class MethodInvokingMessageProcessor implements MessageProcessor {
protected static final Log logger = LogFactory.getLog(MethodInvokingMessageProcessor.class);
private final Log logger = LogFactory.getLog(this.getClass());
private volatile Object object;
private final Object targetObject;
private final HandlerMethodResolver methodResolver;
private volatile boolean requiresReply;
private final ConcurrentMap<Method, ArgumentArrayMessageMapper> messageMappers =
new ConcurrentHashMap<Method, ArgumentArrayMessageMapper>();
private final Map<Class<?>, HandlerMethod> handlerMethods;
private final Map<Method, MethodInvoker> invokers = new HashMap<Method, MethodInvoker>();
private final Set<Method> methodsExpectingMessage = new HashSet<Method>();
private final EvaluationContext evaluationContext;
public MethodInvokingMessageProcessor(Object object, Method method) {
Assert.notNull(object, "object must not be null");
public MethodInvokingMessageProcessor(Object targetObject, Method method) {
this(targetObject, null, method);
}
public MethodInvokingMessageProcessor(Object targetObject, String methodName) {
this(targetObject, null, methodName);
}
public MethodInvokingMessageProcessor(Object targetObject, String methodName, boolean requiresReply) {
this(targetObject, null, methodName, requiresReply);
}
public MethodInvokingMessageProcessor(Object targetObject, Class<? extends Annotation> annotationType) {
this(targetObject, annotationType, (String) null);
}
/*
* Private constructors for internal use
*/
private MethodInvokingMessageProcessor(Object targetObject, Class<? extends Annotation> annotationType, Method method) {
Assert.notNull(method, "method must not be null");
this.object = object;
this.methodResolver = new StaticHandlerMethodResolver(method);
HandlerMethod handlerMethod = new HandlerMethod(method);
this.targetObject = targetObject;
this.handlerMethods = Collections.<Class<?>, HandlerMethod>singletonMap(handlerMethod.getTargetParameterType(), handlerMethod);
this.evaluationContext = this.createEvaluationContext(targetObject);
}
public MethodInvokingMessageProcessor(Object object, Class<? extends Annotation> annotationType) {
Assert.notNull(object, "object must not be null");
Assert.notNull(annotationType, "annotation type must not be null");
this.object = object;
this.methodResolver = this.createResolverForAnnotation(annotationType);
private MethodInvokingMessageProcessor(Object targetObject, Class<? extends Annotation> annotationType, String methodName) {
this(targetObject, annotationType, methodName, false);
}
public MethodInvokingMessageProcessor(Object object, String methodName) {
this(object, methodName, false);
}
public MethodInvokingMessageProcessor(Object object, String methodName, boolean requiresReturnValue) {
Assert.notNull(object, "object must not be null");
Assert.notNull(methodName, "methodName must not be null");
this.object = object;
this.methodResolver = this.createResolverForMethodName(methodName, requiresReturnValue);
private MethodInvokingMessageProcessor(Object targetObject, Class<? extends Annotation> annotationType, String methodName, boolean requiresReply) {
this.targetObject = targetObject;
this.requiresReply = requiresReply;
this.handlerMethods = this.findHandlerMethodsForTarget(targetObject, annotationType, methodName, requiresReply);
this.evaluationContext = this.createEvaluationContext(targetObject);
}
private EvaluationContext createEvaluationContext(Object targetObject) {
StandardEvaluationContext context = new StandardEvaluationContext();
// TODO: Add a filtering MethodResolver (may soon be supported by SpEL) to enable:
// 1) exclusion of void-returning methods if requiresReply is true
// 2) limiting to annotated methods if at least one is present
context.addPropertyAccessor(new MapAccessor());
// TODO: Enable configuration of an integration ConversionService bean to be used here,
// but then fallback to this same default if no such bean has been defined.
ConversionService conversionService = ConversionServiceFactory.createDefaultConversionService();
context.setTypeConverter(new StandardTypeConverter(conversionService));
context.setVariable("target", targetObject);
return context;
}
public Object processMessage(Message<?> message) {
Assert.notNull(message, "message must not be null");
if (message.getPayload() == null) {
if (logger.isDebugEnabled()) {
logger.debug("received null payload");
EvaluationException evaluationException = null;
List<HandlerMethod> candidates = this.findHandlerMethodsForMessage(message);
for (HandlerMethod candidate : candidates) {
try {
Object result = candidate.getExpression().getValue(this.evaluationContext, message);
if (this.requiresReply) {
// TODO: remove this if SpEL is modified to throw an EvaluationException instead
// e.g. we can invoke getValue(this.evaluationContext, message, candidate.getReturnType);
Assert.notNull(result, "Expression evaluation result was null, but this processor requires a reply.");
}
return result;
}
catch (EvaluationException e) {
if (evaluationException == null) {
// keep the first exception
evaluationException = e;
}
}
return null;
}
Method method = this.methodResolver.resolveHandlerMethod(message);
Object[] args = null;
try {
if (this.methodsExpectingMessage.contains(method)) {
args = new Object[] { message };
}
else {
args = this.resolveMessageMapper(method).fromMessage(message);
}
return this.invokeMethod(method, args, message);
}
catch (InvocationTargetException e) {
if (e.getCause() != null && e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new MessageHandlingException(message,
"method '" + method + "' threw an Exception.", e.getCause());
}
catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new MessageHandlingException(message, "Failed to invoke method '"
+ method + "' with arguments: " + ObjectUtils.nullSafeToString(args), e);
if (evaluationException == null) {
throw new MessageHandlingException(message, "Failed to find a suitable Message-handling " +
"method on target of type [" + targetObject.getClass() + "].");
}
throw new MessageHandlingException(message, "Failed to process Message.", evaluationException);
}
private Object invokeMethod(Method method, Object[] args, Message<?> message) throws Exception {
Object result = null;
MethodInvoker invoker = null;
try {
invoker = this.invokers.get(method);
if (invoker == null) {
invoker = new DefaultMethodInvoker(this.object, method);
this.invokers.put(method, invoker);
}
try {
result = invoker.invokeMethod(args);
}
catch (NoSuchMethodException e) {
// fallback to replace the payload argument with headers if possible
boolean foundFallbackCandidate = false;
for (int i = 0; i < args.length; i++) {
if (message != null && message.getPayload().equals(args[i])
&& Map.class.isAssignableFrom(method.getParameterTypes()[i])) {
if (foundFallbackCandidate) {
// more than one, throw an Exception
throw new MessageHandlingException(message, "Failed to resolve ambiguity " +
"amongst multiple non-annotated candidates for matching Message headers.", e);
}
args[i] = message.getHeaders();
foundFallbackCandidate = true;
private Map<Class<?>, HandlerMethod> findHandlerMethodsForTarget(final Object targetObject,
final Class<? extends Annotation> annotationType, final String methodName, final boolean requiresReply) {
final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>();
final Map<Class<?>, HandlerMethod> fallbackMethods = new HashMap<Class<?>, HandlerMethod>();
final AtomicReference<Class<?>> ambiguousFallbackType = new AtomicReference<Class<?>>();
ReflectionUtils.doWithMethods(targetObject.getClass(), new MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
boolean matchesAnnotation = false;
if (method.isBridge()) {
return;
}
if (isMethodDefinedOnObjectClass(method)) {
return;
}
if (!Modifier.isPublic(method.getModifiers())) {
return;
}
if (requiresReply && void.class.equals(method.getReturnType())) {
return;
}
if (methodName != null && !methodName.equals(method.getName())) {
return;
}
if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) {
matchesAnnotation = true;
}
HandlerMethod handlerMethod = null;
try {
handlerMethod = new HandlerMethod(method);
}
catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Method [" + method + "] is not eligible for Message handling.", e);
}
}
if (foundFallbackCandidate) {
result = invoker.invokeMethod(args);
Class<?> targetParameterType = handlerMethod.getTargetParameterType();
if (matchesAnnotation || annotationType == null) {
Assert.isTrue(!candidateMethods.containsKey(targetParameterType),
"Found more than one method match for type [" + targetParameterType + "]");
candidateMethods.put(targetParameterType, handlerMethod);
}
else {
if (fallbackMethods.containsKey(targetParameterType)) {
// we need to check for duplicate type matches,
// but only if we end up falling back
// and we'll only keep track of the first one
ambiguousFallbackType.compareAndSet(null, targetParameterType);
}
fallbackMethods.put(targetParameterType, handlerMethod);
}
}
});
if (!candidateMethods.isEmpty()) {
return candidateMethods;
}
catch (IllegalArgumentException e) {
try {
if (message != null) {
result = invoker.invokeMethod(message);
this.methodsExpectingMessage.add(method);
Assert.notEmpty(fallbackMethods, "Target object [" + this.targetObject +
"] has no eligible methods for handling Messages.");
Assert.isNull(ambiguousFallbackType.get(),
"Found more than one method match for type [" + ambiguousFallbackType + "]");
return fallbackMethods;
}
private List<HandlerMethod> findHandlerMethodsForMessage(Message<?> message) {
final Class<?> payloadType = message.getPayload().getClass();
HandlerMethod closestMatch = this.findClosestMatch(payloadType);
if (closestMatch != null) {
return Collections.singletonList(closestMatch);
}
return new ArrayList<HandlerMethod>(this.handlerMethods.values());
}
private HandlerMethod findClosestMatch(Class<?> payloadType) {
Set<Class<?>> candidates = this.handlerMethods.keySet();
Class<?> match = null;
if (candidates != null && !candidates.isEmpty()) {
match = ClassUtils.findClosestMatch(payloadType, candidates, true);
}
return (match != null) ? this.handlerMethods.get(match) : null;
}
private static boolean isMethodDefinedOnObjectClass(Method method) {
if (method == null) {
return false;
}
if (method.getDeclaringClass().equals(Object.class)) {
return true;
}
if (ReflectionUtils.isEqualsMethod(method) ||
ReflectionUtils.isHashCodeMethod(method) ||
ReflectionUtils.isToStringMethod(method) ||
AopUtils.isFinalizeMethod(method)) {
return true;
}
return (method.getName().equals("clone") && method.getParameterTypes().length == 0);
}
/**
* Helper class for generating and exposing metadata for a candidate handler method.
* The metadata includes the SpEL expression and the expected payload type.
*/
private static class HandlerMethod {
private static final SpelExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER =
new LocalVariableTableParameterNameDiscoverer();
private final Method method;
private final Expression expression;
private volatile Class<?> targetParameterType;
HandlerMethod(Method method) {
this.method = method;
this.expression = this.generateExpression(method);
}
Expression getExpression() {
return this.expression;
}
Class<?> getTargetParameterType() {
return this.targetParameterType;
}
public String toString() {
return this.method.toString();
}
private Expression generateExpression(Method method) {
StringBuilder sb = new StringBuilder("#target." + method.getName() + "(");
Class<?>[] parameterTypes = method.getParameterTypes();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
boolean hasUnqualifiedMapParameter = false;
for (int i = 0; i < parameterTypes.length; i++) {
if (i != 0) {
sb.append(", ");
}
Class<?> parameterType = parameterTypes[i];
Annotation mappingAnnotation = findMappingAnnotation(parameterAnnotations[i]);
if (mappingAnnotation != null) {
Class<? extends Annotation> annotationType = mappingAnnotation.annotationType();
if (annotationType.equals(Payload.class)) {
sb.append("payload");
String qualifierExpression = ((Payload) mappingAnnotation).value();
if (StringUtils.hasText(qualifierExpression)) {
sb.append("." + qualifierExpression);
}
this.setExclusiveTargetParameterType(parameterType);
}
else if (annotationType.equals(Headers.class)) {
Assert.isTrue(Map.class.isAssignableFrom(parameterType),
"The @Headers annotation can only be applied to a Map-typed parameter.");
sb.append("headers");
}
else if (annotationType.equals(Header.class)) {
Header headerAnnotation = (Header) mappingAnnotation;
String headerName = this.determineHeaderName(headerAnnotation, new MethodParameter(method, i));
String headerExpression = "headers." + headerName;
if (headerAnnotation.required()) {
sb.append(headerExpression);
}
else {
sb.append("headers[" + headerName + "] != null ? " + headerExpression + " : null");
}
}
}
else if (Message.class.isAssignableFrom(parameterType)) {
sb.append("#root");
this.setExclusiveTargetParameterType(Message.class);
}
else if (Map.class.isAssignableFrom(parameterType)) {
if (Properties.class.isAssignableFrom(parameterType)) {
sb.append("payload instanceof T(java.util.Map) or " +
"(payload instanceof T(String) and payload.contains('=')) ? payload : headers");
}
else {
sb.append("(payload instanceof T(java.util.Map) ? payload : headers)");
}
Assert.isTrue(!hasUnqualifiedMapParameter,
"Found more than one Map typed parameter without any qualification. " +
"Consider using @Payload or @Headers on at least one of the parameters.");
hasUnqualifiedMapParameter = true;
}
else {
sb.append("payload");
this.setExclusiveTargetParameterType(parameterType);
}
}
catch (NoSuchMethodException e2) {
throw new MessageHandlingException(message, "unable to resolve method for args: "
+ StringUtils.arrayToCommaDelimitedString(args));
if (hasUnqualifiedMapParameter) {
if (targetParameterType != null && Map.class.isAssignableFrom(this.targetParameterType)) {
throw new IllegalArgumentException(
"Unable to determine payload matching parameter due to ambiguous Map typed parameters. " +
"Consider adding the @Payload and or @Headers annotations as appropriate.");
}
}
sb.append(")");
if (this.targetParameterType == null) {
this.targetParameterType = Message.class;
}
return EXPRESSION_PARSER.parseExpression(sb.toString());
}
return result;
}
private HandlerMethodResolver createResolverForMethodName(String methodName, boolean requiresReturnValue) {
List<Method> methodsWithName = new ArrayList<Method>();
Method[] defaultCandidateMethods = HandlerMethodUtils.getCandidateHandlerMethods(this.object);
for (Method method : defaultCandidateMethods) {
if (method.getName().equals(methodName)
&& (!requiresReturnValue || !Void.TYPE.equals(method.getReturnType()))) {
methodsWithName.add(method);
private Annotation findMappingAnnotation(Annotation[] annotations) {
if (annotations == null || annotations.length == 0) {
return null;
}
Annotation match = null;
for (Annotation annotation : annotations) {
Class<? extends Annotation> type = annotation.annotationType();
if (type.equals(Payload.class) || type.equals(Header.class) || type.equals(Headers.class)) {
if (match != null) {
throw new MessagingException("At most one parameter annotation can be provided for message mapping, " +
"but found two: [" + match.annotationType().getName() + "] and [" + annotation.annotationType().getName() + "]");
}
match = annotation;
}
}
return match;
}
Assert.notEmpty(methodsWithName, "Failed to find any valid Message-handling methods named '"
+ methodName + "' on target class [" + this.object.getClass() + "].");
if (methodsWithName.size() == 1) {
return new StaticHandlerMethodResolver(methodsWithName.get(0));
}
return new PayloadTypeMatchingHandlerMethodResolver(methodsWithName.toArray(new Method[methodsWithName.size()]));
}
private HandlerMethodResolver createResolverForAnnotation(Class<? extends Annotation> annotationType) {
List<Method> methodsWithAnnotation = new ArrayList<Method>();
Method[] defaultCandidateMethods = HandlerMethodUtils.getCandidateHandlerMethods(this.object);
for (Method method : defaultCandidateMethods) {
Annotation annotation = AnnotationUtils.getAnnotation(method, annotationType);
if (annotation != null) {
methodsWithAnnotation.add(method);
}
private String determineHeaderName(Header headerAnnotation, MethodParameter methodParameter) {
methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER);
String valueAttribute = headerAnnotation.value();
String headerName = StringUtils.hasText(valueAttribute) ? valueAttribute : methodParameter.getParameterName();
Assert.notNull(headerName, "Cannot determine header name. Possible reasons: -debug is " +
"disabled or header name is not explicitly provided via @Header annotation.");
return headerName;
}
Method[] candidateMethods = (methodsWithAnnotation.size() == 0) ? null
: methodsWithAnnotation.toArray(new Method[methodsWithAnnotation.size()]);
if (candidateMethods == null) {
if (logger.isInfoEnabled()) {
logger.info("Failed to find any valid Message-handling methods with annotation ["
+ annotationType + "] on target class [" + this.object.getClass() + "]. "
+ "Method-resolution will be applied to all eligible methods.");
}
candidateMethods = defaultCandidateMethods;
}
if (candidateMethods.length == 1) {
return new StaticHandlerMethodResolver(candidateMethods[0]);
}
return new PayloadTypeMatchingHandlerMethodResolver(candidateMethods);
}
private ArgumentArrayMessageMapper resolveMessageMapper(Method method) {
ArgumentArrayMessageMapper mapper = this.messageMappers.get(method);
if (mapper == null) {
mapper = new ArgumentArrayMessageMapper(method);
ArgumentArrayMessageMapper existingMapper = this.messageMappers.putIfAbsent(method, mapper);
if (existingMapper != null) {
// throw away the one just created, since one was created in the meantime
mapper = existingMapper;
}
private synchronized void setExclusiveTargetParameterType(Class<?> targetParameterType) {
Assert.isNull(this.targetParameterType, "Found more than one parameter type candidate: [" +
this.targetParameterType + "] and [" + targetParameterType + "]");
this.targetParameterType = targetParameterType;
}
return mapper;
}
}