INT-1243 (refactoring publishing-interceptor) Step 1: removed "headers" attribute from @Publisher and <publisher> element's <method> sub-element; using a Map now instead of a comma-delimited string of key=value pairs

This commit is contained in:
Mark Fisher
2010-07-19 22:55:38 +00:00
parent 90c6b58501
commit b7877feab1
17 changed files with 163 additions and 90 deletions

View File

@@ -17,6 +17,7 @@
package org.springframework.integration.aop;
import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
@@ -80,7 +81,7 @@ public abstract class AbstractExpressionSource implements ExpressionSource {
public abstract String[] getArgumentVariableNames(Method method);
public abstract String[] getHeaderExpressions(Method method);
public abstract Map<String, String> getHeaderExpressions(Method method);
public abstract String getChannelName(Method method);

View File

@@ -17,6 +17,7 @@
package org.springframework.integration.aop;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Strategy for determining the expression string and evaluation context
@@ -43,10 +44,11 @@ interface ExpressionSource {
String getPayloadExpression(Method method);
/**
* Returns the array of expression strings to be evaluated for any headers
* that should be set on the published Message.
* Returns the map of expression strings to be evaluated for any headers
* that should be set on the published Message. The keys in the Map are
* header names, the values are the expression strings.
*/
String[] getHeaderExpressions(Method method);
Map<String, String> getHeaderExpressions(Method method);
/**
* Returns the variable name to be associated with the intercepted

View File

@@ -88,13 +88,14 @@ public class MessagePublishingInterceptor implements MethodInterceptor {
String[] argumentNames = this.expressionSource.getArgumentVariableNames(method);
context.setVariable(this.expressionSource.getMethodNameVariableName(method), method.getName());
if (invocation.getArguments().length > 0 && argumentNames != null) {
int index = 0;
Map<String, Object> argumentMap = new HashMap<String, Object>();
for (String argumentName : argumentNames) {
if (invocation.getArguments().length <= index) {
for (int i = 0; i < argumentNames.length; i++) {
if (invocation.getArguments().length <= i) {
break;
}
argumentMap.put(argumentName, invocation.getArguments()[index++]);
Object argValue = invocation.getArguments()[i];
argumentMap.put("" + i, argValue);
argumentMap.put(argumentNames[i], argValue);
}
context.setVariable(this.expressionSource.getArgumentMapVariableName(method), argumentMap);
}
@@ -146,14 +147,17 @@ public class MessagePublishingInterceptor implements MethodInterceptor {
private Map<String, Object> evaluateHeaders(Method method, StandardEvaluationContext context)
throws ParseException, EvaluationException {
String[] headerExpressionStrings = this.expressionSource.getHeaderExpressions(method);
if (headerExpressionStrings != null) {
Map<String, String> headerExpressionMap = this.expressionSource.getHeaderExpressions(method);
if (headerExpressionMap != null) {
Map<String, Object> headers = new HashMap<String, Object>();
context.setRootObject(headers);
for (String headerExpression : headerExpressionStrings) {
for (Map.Entry<String, String> headerExpressionEntry : headerExpressionMap.entrySet()) {
String headerExpression = headerExpressionEntry.getValue();
if (StringUtils.hasText(headerExpression)) {
Expression expression = this.parser.parseExpression(headerExpression);
expression.getValue(context);
Object result = expression.getValue(context);
if (result != null) {
headers.put(headerExpressionEntry.getKey(), result);
}
}
}
if (headers.size() > 0) {

View File

@@ -19,11 +19,14 @@ package org.springframework.integration.aop;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.integration.annotation.Header;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -62,8 +65,24 @@ public class MethodAnnotationExpressionSource implements ExpressionSource {
return this.getAnnotationValue(method, "payload", String.class);
}
public String[] getHeaderExpressions(Method method) {
return this.getAnnotationValue(method, "headers", String[].class);
public Map<String, String> getHeaderExpressions(Method method) {
Map<String, String> headerExpressions = new HashMap<String, String>();
String[] parameterNames = this.parameterNameDiscoverer.getParameterNames(method);
Annotation[][] annotationArray = method.getParameterAnnotations();
for (int i = 0; i < annotationArray.length; i++) {
Annotation[] parameterAnnotations = annotationArray[i];
for (Annotation currentAnnotation : parameterAnnotations) {
if (Header.class.equals(currentAnnotation.annotationType())) {
Header headerAnnotation = (Header) currentAnnotation;
String name = headerAnnotation.value();
if (!StringUtils.hasText(name)) {
name = parameterNames[i];
}
headerExpressions.put(name, "#" + this.getArgumentMapVariableName(method) + "['" + i + "']");
}
}
}
return headerExpressions;
}
public String getMethodNameVariableName(Method method) {

View File

@@ -31,7 +31,7 @@ public class MethodNameMappingExpressionSource extends AbstractExpressionSource
private final Map<String, String> payloadExpressionMap;
private volatile Map<String, String[]> headerExpressionMap = Collections.emptyMap();
private volatile Map<String, Map<String, String>> headerExpressionMap = Collections.emptyMap();
private volatile Map<String, String> channelMap = Collections.emptyMap();
@@ -47,7 +47,7 @@ public class MethodNameMappingExpressionSource extends AbstractExpressionSource
this.argumentVariableNameMap = argumentVariableNameMap;
}
public void setHeaderExpressionMap(Map<String, String[]> headerExpressionMap) {
public void setHeaderExpressionMap(Map<String, Map<String, String>> headerExpressionMap) {
this.headerExpressionMap = headerExpressionMap;
}
@@ -75,8 +75,8 @@ public class MethodNameMappingExpressionSource extends AbstractExpressionSource
return null;
}
public String[] getHeaderExpressions(Method method) {
for (Map.Entry<String, String[]> entry : this.headerExpressionMap.entrySet()) {
public Map<String, String> getHeaderExpressions(Method method) {
for (Map.Entry<String, Map<String, String>> entry : this.headerExpressionMap.entrySet()) {
if (PatternMatchUtils.simpleMatch(entry.getKey(), method.getName())) {
return entry.getValue();
}

View File

@@ -40,12 +40,6 @@ public @interface Publisher {
*/
String payload() default "";
/**
* String representations of Spel Expressions to evaluate for adding any
* headers to the Message. Optional.
*/
String[] headers() default "";
/**
* Name of the Message Channel to which Messages will be published.
*/

View File

@@ -17,6 +17,7 @@
package org.springframework.integration.aop;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Simple implementation of {@link ExpressionSource} that allows for
@@ -32,7 +33,7 @@ public class SimpleExpressionSource extends AbstractExpressionSource {
private volatile String payloadExpression;
private volatile String[] headerExpressions;
private volatile Map<String, String> headerExpressions;
public void setChannelName(String channelName) {
@@ -53,12 +54,12 @@ public class SimpleExpressionSource extends AbstractExpressionSource {
return this.payloadExpression;
}
public void setHeaderExpressions(String[] headerExpressions) {
public void setHeaderExpressions(Map<String, String> headerExpressions) {
this.headerExpressions = headerExpressions;
}
@Override
public String[] getHeaderExpressions(Method method) {
public Map<String, String> getHeaderExpressions(Method method) {
return this.headerExpressions;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.config.xml;
import java.util.HashMap;
@@ -35,65 +36,83 @@ import org.w3c.dom.Element;
/**
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since 2.0
*/
public class PublisherParser extends AbstractBeanDefinitionParser {
/**
*
*/
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder rootBuilder = BeanDefinitionBuilder.genericBeanDefinition(
IntegrationNamespaceUtils.BASE_PACKAGE + ".aop.MessagePublishingInterceptor");
BeanDefinitionBuilder spelSourceBuilder = BeanDefinitionBuilder.genericBeanDefinition(MethodNameMappingExpressionSource.class.getName());
Map<String, Map<?,?>> mappings = this.getMappings(element, element.getAttribute("default-channel"), parserContext);
BeanDefinitionBuilder spelSourceBilder = BeanDefinitionBuilder.genericBeanDefinition(MethodNameMappingExpressionSource.class.getName());
Map<String, Map<?,?>> mappings = this.getMappings(element, element.getAttribute("default-channel"));
spelSourceBilder.addConstructorArgValue(mappings.get("payload"));
if (mappings.get("headers") != null){
spelSourceBilder.addPropertyValue("headerExpressionMap", mappings.get("headers"));
spelSourceBuilder.addConstructorArgValue(mappings.get("payload"));
if (mappings.get("headers") != null) {
spelSourceBuilder.addPropertyValue("headerExpressionMap", mappings.get("headers"));
}
BeanDefinitionBuilder chResolverBuilder = BeanDefinitionBuilder.genericBeanDefinition(MapBasedChannelResolver.class.getName());
if (mappings.get("channels") != null){
spelSourceBilder.addPropertyValue("channelMap", mappings.get("channels"));
spelSourceBuilder.addPropertyValue("channelMap", mappings.get("channels"));
chResolverBuilder.addConstructorArgValue(mappings.get("resolvableChannels"));
}
String chResolverName =
BeanDefinitionReaderUtils.registerWithGeneratedName(chResolverBuilder.getBeanDefinition(), parserContext.getRegistry());
BeanDefinitionReaderUtils.registerWithGeneratedName(chResolverBuilder.getBeanDefinition(), parserContext.getRegistry());
String defaultChannel = StringUtils.hasText(element.getAttribute("default-channel")) ?
element.getAttribute("default-channel") : IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME;
String spelSourceName =
BeanDefinitionReaderUtils.registerWithGeneratedName(spelSourceBilder.getBeanDefinition(), parserContext.getRegistry());
rootBuilder.addConstructorArgReference(spelSourceName);
rootBuilder.addPropertyReference("channelResolver", chResolverName);
rootBuilder.addPropertyReference("defaultChannel", defaultChannel);
rootBuilder.addConstructorArgValue(spelSourceBuilder.getBeanDefinition());
rootBuilder.addPropertyReference("channelResolver", chResolverName);
rootBuilder.addPropertyReference("defaultChannel", defaultChannel);
return rootBuilder.getBeanDefinition();
}
@SuppressWarnings("unchecked")
private Map<String,Map<?,?>> getMappings(Element element, String defaultChannel){
private Map<String,Map<?,?>> getMappings(Element element, String defaultChannel, ParserContext parserContext) {
List<Element> mappings = DomUtils.getChildElementsByTagName(element, "method");
Map<String, Map<?,?>> interceptorMappings = new HashMap<String, Map<?,?>>();
Map<String, String> payloadExpressionMap = new HashMap<String, String>();
Map<String, String[]> headersExpressionMap = new HashMap<String, String[]>();
Map<String, Map<String, String>> headersExpressionMap = new HashMap<String, Map<String, String>>();
Map<String, String> channelMap = new HashMap<String, String>();
ManagedMap resolvableChannelMap = new ManagedMap();
if (mappings != null && mappings.size() > 0){
if (mappings != null && mappings.size() > 0) {
for (Element mapping : mappings) {
// set payloadMap
String methodPattern = StringUtils.hasText(mapping.getAttribute("pattern")) ?
mapping.getAttribute("pattern") : "*" ;
mapping.getAttribute("pattern") : "*";
String payloadExpression = StringUtils.hasText(mapping.getAttribute("payload")) ?
mapping.getAttribute("payload") : "#return" ;
mapping.getAttribute("payload") : "#return";
payloadExpressionMap.put(methodPattern, payloadExpression);
// set headersMap
String headersExpression = mapping.getAttribute("headers");
if (StringUtils.hasText(headersExpression)){
headersExpressionMap.put(methodPattern, StringUtils.commaDelimitedListToStringArray(headersExpression));
List<Element> headerElements = DomUtils.getChildElementsByTagName(mapping, "header");
Map<String, String> headerExpressions = new HashMap<String, String>();
for (Element headerElement : headerElements) {
String name = headerElement.getAttribute("name");
if (!StringUtils.hasText(name)) {
parserContext.getReaderContext().error("the 'name' attribute is required on the <header> element",
parserContext.extractSource(headerElement));
continue;
}
String value = headerElement.getAttribute("value");
String expression = headerElement.getAttribute("expression");
boolean hasValue = StringUtils.hasText(value);
boolean hasExpression = StringUtils.hasText(expression);
if (!(hasValue ^ hasExpression)) {
parserContext.getReaderContext().error("exactly one of 'value' or 'expression' is required on the <header> element",
parserContext.extractSource(headerElement));
continue;
}
if (hasValue) {
expression = "'" + value + "'";
}
headerExpressions.put(name, expression);
}
if (headerExpressions.size() > 0) {
headersExpressionMap.put(methodPattern, headerExpressions);
}
// set channelMap
String tmpChannel = mapping.getAttribute("channel");
String channel = StringUtils.hasText(tmpChannel) ? tmpChannel : defaultChannel;
@@ -101,19 +120,18 @@ public class PublisherParser extends AbstractBeanDefinitionParser {
resolvableChannelMap.put(channel, new RuntimeBeanReference(channel));
}
}
if (payloadExpressionMap.size() == 0){
if (payloadExpressionMap.size() == 0) {
payloadExpressionMap.put("*", "#return");
}
}
interceptorMappings.put("payload", payloadExpressionMap);
if (headersExpressionMap.size() > 0){
if (headersExpressionMap.size() > 0) {
interceptorMappings.put("headers", headersExpressionMap);
}
if (channelMap.size() > 0){
if (channelMap.size() > 0) {
interceptorMappings.put("channels", channelMap);
interceptorMappings.put("resolvableChannels", resolvableChannelMap);
}
return interceptorMappings;
}
}

View File

@@ -2259,9 +2259,17 @@ Name of the header whose value to use.
<xsd:sequence>
<xsd:element name="method" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence minOccurs="0" maxOccurs="unbounded">
<xsd:element name="header">
<xsd:complexType>
<xsd:attribute name="name" type="xsd:string" use="required"/>
<xsd:attribute name="value" type="xsd:string"/>
<xsd:attribute name="expression" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="pattern" type="xsd:string" />
<xsd:attribute name="payload" type="xsd:string" />
<xsd:attribute name="headers" type="xsd:string" />
<xsd:attribute name="channel" type="xsd:string">
<xsd:annotation>
<xsd:appinfo>

View File

@@ -22,6 +22,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.Header;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.Message;
import org.springframework.test.context.ContextConfiguration;
@@ -47,12 +48,12 @@ public class AnnotationConfigRegistrationTests {
@Test // INT-1200
public void verifyInterception() {
String name = testBean.setName("John", "Doe");
String name = testBean.setName("John", "Doe", 123);
Assert.assertNotNull(name);
Message<?> message = testChannel.receive(0);
Assert.assertNotNull(message);
Assert.assertEquals("John DoeDoe", message.getPayload());
Assert.assertEquals("123", message.getHeaders().get("x"));
Assert.assertEquals(123, message.getHeaders().get("x"));
}
@Test
@@ -68,8 +69,8 @@ public class AnnotationConfigRegistrationTests {
public static class TestBean {
@Publisher(channel="testChannel", payload="#return + #args.lname", headers="x='123'")
public String setName(String fname, String lname){
@Publisher(channel="testChannel", payload="#return + #args.lname")
public String setName(String fname, String lname, @Header("x") int num) {
return fname + " " + lname;
}

View File

@@ -22,6 +22,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.Header;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.Message;
import org.springframework.test.context.ContextConfiguration;
@@ -29,6 +30,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Oleg Zhurakousky
* @author Mark Fisher
* @since 2.0
*/
@ContextConfiguration
@@ -43,20 +45,35 @@ public class MessagePublishingAnnotationUsageTests {
@Test
public void demoMessagePublishingInterceptor() {
String name = testBean.setName("John", "Doe");
public void headerWithExplicitName() {
String name = testBean.setName1("John", "Doe");
Assert.assertNotNull(name);
Message<?> message = channel.receive(1000);
Assert.assertNotNull(message);
Assert.assertEquals("John Doe", message.getPayload());
Assert.assertEquals("123", message.getHeaders().get("bar"));
Assert.assertEquals("Doe", message.getHeaders().get("last"));
}
@Test
public void headerWithImplicitName() {
String name = testBean.setName2("John", "Doe");
Assert.assertNotNull(name);
Message<?> message = channel.receive(1000);
Assert.assertNotNull(message);
Assert.assertEquals("John Doe", message.getPayload());
Assert.assertEquals("Doe", message.getHeaders().get("lname"));
}
public static class TestBean {
@Publisher(channel="testChannel", payload="#return", headers="bar='123'")
public String setName(String fname, String lname){
@Publisher(channel="testChannel", payload="#return")
public String setName1(String fname, @Header("last") String lname) {
return fname + " " + lname;
}
@Publisher(channel="testChannel", payload="#return")
public String setName2(String fname, @Header String lname) {
return fname + " " + lname;
}
}

View File

@@ -71,12 +71,14 @@ public class MessagePublishingInterceptorTests {
Map<String, String> channelMap = new HashMap<String, String>();
channelMap.put("test", "c");
source.setChannelMap(channelMap);
Map<String, String[]> headerExpressionMap = new HashMap<String, String[]>();
headerExpressionMap.put("test", new String[]{"bar=#return","name='oleg'"});
Map<String, Map<String, String>> headerExpressionMap = new HashMap<String, Map<String, String>>();
Map<String, String> headerExpressions = new HashMap<String, String>();
headerExpressions.put("bar", "#return");
headerExpressions.put("name", "'oleg'");
headerExpressionMap.put("test", headerExpressions);
source.setHeaderExpressionMap(headerExpressionMap);
MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor(source);
interceptor.setChannelResolver(channelResolver);
ProxyFactory pf = new ProxyFactory(new TestBeanImpl());
@@ -106,6 +108,7 @@ public class MessagePublishingInterceptorTests {
}
private static class TestExpressionSource implements ExpressionSource {
public String getMethodNameVariableName(Method method) {
@@ -132,7 +135,7 @@ public class MessagePublishingInterceptorTests {
return "#r";
}
public String[] getHeaderExpressions(Method method) {
public Map<String, String> getHeaderExpressions(Method method) {
return null;
}

View File

@@ -30,7 +30,9 @@
</constructor-arg>
<property name="headerExpressionMap">
<map>
<entry key="setName" value="foo='bar'" />
<entry key="setName">
<map><entry key="foo" value="'bar'"/></map>
</entry>
</map>
</property>
<property name="channelMap">

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2009 the original author or authors.
* Copyright 2002-2010 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.

View File

@@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.lang.reflect.Method;
import java.util.Map;
import org.junit.Test;
@@ -39,10 +40,9 @@ public class MethodAnnotationExpressionSourceTests {
assertEquals(2, source.getArgumentVariableNames(method).length);
assertEquals("arg1", source.getArgumentVariableNames(method)[0]);
assertEquals("arg2", source.getArgumentVariableNames(method)[1]);
String[] headerStrings = source.getHeaderExpressions(method);
assertNotNull(headerStrings);
assertEquals(1, headerStrings.length);
assertEquals("", headerStrings[0]);
Map<String, String> headerMap = source.getHeaderExpressions(method);
assertNotNull(headerMap);
assertEquals(0, headerMap.size());
assertEquals(ExpressionSource.DEFAULT_ARGUMENT_MAP_VARIABLE_NAME, source.getArgumentMapVariableName(method));
assertEquals(ExpressionSource.DEFAULT_EXCEPTION_VARIABLE_NAME, source.getExceptionVariableName(method));
assertEquals(ExpressionSource.DEFAULT_RETURN_VALUE_VARIABLE_NAME, source.getReturnValueVariableName(method));
@@ -83,7 +83,7 @@ public class MethodAnnotationExpressionSourceTests {
public void methodWithExpressionAnnotationOnly(String arg1, int arg2) {
}
@Publisher(payload="#return", channel="foo", headers="bar=123")
@Publisher(payload="#return", channel="foo")
public void methodWithChannelAndReturnAsPayload() {
}

View File

@@ -24,6 +24,7 @@ import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.integration.annotation.Header;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.Message;
@@ -66,8 +67,8 @@ public class PublisherExpressionTests {
static class TestBeanImpl implements TestBean {
@Publisher(payload="#return", headers="foo=#args.foo")
public String test(String foo) {
@Publisher(payload="#return")
public String test(@Header("foo") String foo) {
return "hello";
}
}

View File

@@ -21,7 +21,9 @@
</aop:config>
<publisher id="interceptor" default-channel="defaultChannel">
<method pattern="echo" payload="'Echoing: ' + #return" headers="foo='bar'" channel="echoChannel"/>
<method pattern="echo" payload="'Echoing: ' + #return" channel="echoChannel">
<header name="foo" value="bar"/>
</method>
<method pattern="echoDef*" payload="#return"/>
</publisher>