INT-656 Added fallback for Map typed arguments when payload does not match at runtime. Fallback attempts to match headers if no ambiguities exist.

This commit is contained in:
Mark Fisher
2009-07-02 15:48:06 +00:00
parent 3675f8dd1b
commit eea4aacfd3
4 changed files with 493 additions and 22 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,9 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageHandlingException;
@@ -37,9 +40,6 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 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.
@@ -48,6 +48,7 @@ import org.apache.commons.logging.LogFactory;
*
* @author Mark Fisher
* @author Marius Bogoevici
* @see MethodParameterMessageMapper
*/
public class MessageMappingMethodInvoker {
@@ -130,7 +131,28 @@ public class MessageMappingMethodInvoker {
invoker = new DefaultMethodInvoker(this.object, method);
this.invokers.put(method, invoker);
}
result = invoker.invokeMethod(args);
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;
}
}
if (foundFallbackCandidate) {
result = invoker.invokeMethod(args);
}
}
}
catch (IllegalArgumentException e) {
try {
@@ -158,6 +180,22 @@ public class MessageMappingMethodInvoker {
else {
args = new Object[] { mappingResult };
}
if (args.length > 1 && message != null && message.getPayload() instanceof Map) {
int mapArgCount = 0;
boolean resolvedMapArg = false;
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
if (arg instanceof Map && Map.class.isAssignableFrom(method.getParameterTypes()[i])) {
mapArgCount++;
if (arg.equals(message.getPayload())) {
// resolved if there is exactly one match
resolvedMapArg = !resolvedMapArg;
}
}
}
Assert.isTrue(resolvedMapArg || mapArgCount <= 1,
"Unable to resolve argument for Map-typed payload on method [" + method + "].");
}
return args;
}

View File

@@ -63,12 +63,13 @@ import org.springframework.util.StringUtils;
* expecting multiple headers (with or without the @Headers annotation).
* <p/>
* If a Map or Properties object is expected, and the payload is not itself
* assignable to that type, then the MessageHeaders' values will be passed in
* the case of a Map-typed parameter, or the MessageHeaders' String-based values
* will be passed in the case of a Properties-typed parameter. In these cases
* multiple unannotated parameters are legal. If, however, the actual payload
* type is a Map or Properties instance, then this ambiguity cannot be
* resolved. For that reason, it is recommended to use the explicit
* assignable to that type or capable of being converted to that type, then
* the MessageHeaders' values will be passed in the case of a Map-typed
* parameter, or the MessageHeaders' String-based values will be passed in the
* case of a Properties-typed parameter. In these cases multiple unannotated
* parameters are legal. If, however, the actual payload type is a Map or
* Properties instance, then this ambiguity cannot be resolved. For that
* reason, it is highly recommended to use the explicit
* {@link Headers @Headers} annotation whenever possible.
* <p/>
* Some examples of legal method signatures:<br/>
@@ -215,7 +216,7 @@ public class MethodParameterMessageMapper implements InboundMessageMapper<Object
MethodParameterMetadata metadata = this.parameterMetadata[i];
Class<?> expectedType = metadata.getParameterType();
Header headerAnnotation = metadata.getHeaderAnnotation();
if (metadata == payloadParameterMetadata) {
if (metadata == this.payloadParameterMetadata) {
args[i] = message.getPayload();
}
else if (headerAnnotation != null) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author 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,6 +17,7 @@
package org.springframework.integration.util;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -78,12 +79,19 @@ public class DefaultMethodInvoker implements MethodInvoker {
convertedArgs[i] = converter.convertIfNecessary(args[i], paramTypes[i]);
}
catch (TypeMismatchException e) {
throw new IllegalArgumentException("Failed to convert argument type.", e);
if (Map.class.isAssignableFrom(paramTypes[i])) {
// may be able to fallback to Message Headers for this argument
convertedArgs[i] = args[i];
}
else {
throw new IllegalArgumentException("Failed to convert argument type.", e);
}
}
}
this.method.setAccessible(true);
if (this.logger.isDebugEnabled()) {
logger.debug("invoking method '" + this.method.getName() + "' with arguments " + ObjectUtils.nullSafeToString(convertedArgs));
logger.debug("Invoking method [" + this.method + "] with arguments [" +
ObjectUtils.nullSafeToString(convertedArgs) + "]");
}
try {
return this.method.invoke(this.object, convertedArgs);
@@ -93,6 +101,10 @@ public class DefaultMethodInvoker implements MethodInvoker {
helper.setTargetObject(this.object);
helper.setTargetMethod(this.method.getName());
helper.setArguments(convertedArgs);
if (logger.isDebugEnabled()) {
logger.debug("Attempting fallback based on method name [" + this.method.getName() +
"] with arguments [" + ObjectUtils.nullSafeToString(convertedArgs) + "]");
}
helper.prepare();
this.method = helper.getPreparedMethod();
return this.method.invoke(this.object, convertedArgs);