Support @PathVariable in annotated message handling methods

Prior to this commit, @SubscribeEvent @UnsubscribeEvent and
@MessageMapping annotated message handling methods
could only match a strict message destination.

This commit adds a @PathVariable annotation and
updates the message matching/handling process, since
message handling methods can now match PathMatcher-like
destinations and get path variables injected in parameters.

Issue: SPR-10949
This commit is contained in:
Brian Clozel
2013-10-16 16:13:01 +02:00
committed by Rossen Stoyanchev
parent efa86e80d8
commit fb586da673
5 changed files with 392 additions and 5 deletions

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2013 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.messaging.handler.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation which indicates that a method parameter should be bound to a path template
* variable. Supported for {@link org.springframework.messaging.simp.annotation.SubscribeEvent},
* {@link org.springframework.messaging.simp.annotation.UnsubscribeEvent},
* {@link org.springframework.messaging.handler.annotation.MessageMapping}
* annotated handler methods.
*
* <p>A {@code @PathVariable} template variable is always required and does not have
* a default value to fall back on.
*
* @author Brian Clozel
* @see org.springframework.messaging.simp.annotation.SubscribeEvent
* @see org.springframework.messaging.simp.annotation.UnsubscribeEvent
* @see org.springframework.messaging.handler.annotation.MessageMapping
* @since 4.0
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
/** The path template variable to bind to. */
String value() default "";
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2013 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.messaging.handler.annotation.support;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.ConversionService;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.PathVariable;
import org.springframework.messaging.handler.annotation.ValueConstants;
import org.springframework.messaging.simp.handler.AnnotationMethodMessageHandler;
import java.util.Map;
/**
* Resolves method parameters annotated with {@link PathVariable @PathVariable}.
*
* <p>A @{@link PathVariable} is a named value that gets resolved from a path
* template variable that matches the Message destination header.
* It is always required and does not have a default value to fall back on.
*
* @author Brian Clozel
* @see org.springframework.messaging.handler.annotation.PathVariable
* @see org.springframework.messaging.MessageHeaders
* @since 4.0
*/
public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {
public PathVariableMethodArgumentResolver(ConversionService cs, ConfigurableBeanFactory beanFactory) {
super(cs, beanFactory);
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(PathVariable.class);
}
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
PathVariable annotation = parameter.getParameterAnnotation(PathVariable.class);
return new PathVariableNamedValueInfo(annotation);
}
@Override
protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name) throws Exception {
Map<String, String> pathTemplateVars =
(Map<String, String>) message.getHeaders().get(AnnotationMethodMessageHandler.PATH_TEMPLATE_VARIABLES_HEADER);
return (pathTemplateVars != null) ? pathTemplateVars.get(name) : null;
}
@Override
protected void handleMissingValue(String name, MethodParameter parameter, Message<?> message) {
throw new MessageHandlingException(message, "Missing path template variable '" + name +
"' for method parameter type [" + parameter.getParameterType() + "]");
}
private static class PathVariableNamedValueInfo extends NamedValueInfo {
private PathVariableNamedValueInfo(PathVariable annotation) {
super(annotation.value(), true, ValueConstants.DEFAULT_NONE);
}
}
}

View File

@@ -21,6 +21,8 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -50,6 +52,7 @@ import org.springframework.messaging.handler.annotation.support.HeaderMethodArgu
import org.springframework.messaging.handler.annotation.support.HeadersMethodArgumentResolver;
import org.springframework.messaging.handler.annotation.support.MessageMethodArgumentResolver;
import org.springframework.messaging.handler.annotation.support.PayloadArgumentResolver;
import org.springframework.messaging.handler.annotation.support.PathVariableMethodArgumentResolver;
import org.springframework.messaging.handler.method.HandlerMethod;
import org.springframework.messaging.handler.method.HandlerMethodArgumentResolver;
import org.springframework.messaging.handler.method.HandlerMethodArgumentResolverComposite;
@@ -67,25 +70,35 @@ import org.springframework.messaging.simp.annotation.support.PrincipalMethodArgu
import org.springframework.messaging.simp.annotation.support.SendToMethodReturnValueHandler;
import org.springframework.messaging.simp.annotation.support.SubscriptionMethodReturnValueHandler;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.converter.ByteArrayMessageConverter;
import org.springframework.messaging.support.converter.CompositeMessageConverter;
import org.springframework.messaging.support.converter.MessageConverter;
import org.springframework.messaging.support.converter.StringMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.util.ReflectionUtils.MethodFilter;
/**
* @author Rossen Stoyanchev
* @author Brian Clozel
* @since 4.0
*/
public class AnnotationMethodMessageHandler implements MessageHandler, ApplicationContextAware, InitializingBean {
public static final String PATH_TEMPLATE_VARIABLES_HEADER = "Spring-PathTemplateVariables";
public static final String BEST_MATCHING_PATTERN_HEADER = "Spring-BestMatchingPattern";
private static final Log logger = LogFactory.getLog(AnnotationMethodMessageHandler.class);
private final PathMatcher pathMatcher = new AntPathMatcher();
private final SimpMessageSendingOperations brokerTemplate;
private final SimpMessageSendingOperations webSocketResponseTemplate;
@@ -242,6 +255,7 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
// Annotation-based argument resolution
this.argumentResolvers.addResolver(new HeaderMethodArgumentResolver(this.conversionService, beanFactory));
this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver());
this.argumentResolvers.addResolver(new PathVariableMethodArgumentResolver(this.conversionService, beanFactory));
// Type-based argument resolution
this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver());
@@ -363,7 +377,7 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
return;
}
HandlerMethod match = getHandlerMethod(lookupPath, handlerMethods);
MappingInfoMatch match = matchMappingInfo(lookupPath, handlerMethods);
if (match == null) {
if (logger.isTraceEnabled()) {
logger.trace("No matching method, lookup path " + lookupPath);
@@ -371,13 +385,16 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
return;
}
HandlerMethod handlerMethod = match.createWithResolvedBean();
HandlerMethod handlerMethod = match.handlerMethod.createWithResolvedBean();
InvocableHandlerMethod invocableHandlerMethod = new InvocableHandlerMethod(handlerMethod);
invocableHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);
try {
headers.setDestination(lookupPath);
headers.setHeader(BEST_MATCHING_PATTERN_HEADER,match.mappingDestination);
headers.setHeader(PATH_TEMPLATE_VARIABLES_HEADER,
pathMatcher.extractUriTemplateVariables(match.mappingDestination,lookupPath));
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
Object returnValue = invocableHandlerMethod.invoke(message);
@@ -444,17 +461,52 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
}
}
protected HandlerMethod getHandlerMethod(String destination, Map<MappingInfo, HandlerMethod> handlerMethods) {
protected MappingInfoMatch matchMappingInfo(String destination,
Map<MappingInfo, HandlerMethod> handlerMethods) {
List<MappingInfoMatch> matches = new ArrayList<MappingInfoMatch>(4);
for (MappingInfo key : handlerMethods.keySet()) {
for (String mappingDestination : key.getDestinations()) {
if (destination.equals(mappingDestination)) {
return handlerMethods.get(key);
if (this.pathMatcher.match(mappingDestination, destination)) {
matches.add(new MappingInfoMatch(mappingDestination,
handlerMethods.get(key)));
}
}
}
if(!matches.isEmpty()) {
Comparator<MappingInfoMatch> comparator = getMappingInfoMatchComparator(destination, this.pathMatcher);
Collections.sort(matches, comparator);
if (logger.isTraceEnabled()) {
logger.trace("Found " + matches.size() + " matching mapping(s) for [" + destination + "] : " + matches);
}
MappingInfoMatch bestMatch = matches.get(0);
if (matches.size() > 1) {
MappingInfoMatch secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException(
"Ambiguous handler methods mapped for Message destination '" + destination + "': {" +
m1 + ", " + m2 + "}");
}
}
return bestMatch;
}
return null;
}
private Comparator<MappingInfoMatch> getMappingInfoMatchComparator(String destination,
PathMatcher pathMatcher) {
return new Comparator<MappingInfoMatch>() {
@Override
public int compare(MappingInfoMatch one, MappingInfoMatch other) {
Comparator<String> patternComparator = pathMatcher.getPatternComparator(destination);
return patternComparator.compare(one.mappingDestination,other.mappingDestination);
}
};
}
private static class MappingInfo {
@@ -493,4 +545,14 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
}
}
private static class MappingInfoMatch {
private final String mappingDestination;
private final HandlerMethod handlerMethod;
public MappingInfoMatch(String destination, HandlerMethod handlerMethod) {
this.mappingDestination = destination;
this.handlerMethod = handlerMethod;
}
}
}