AnnotationSimpMessageHandler.java 11.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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.
 */

17
package org.springframework.messaging.simp.handler;
18 19 20 21

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
22
import java.util.Collection;
23 24 25 26
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
R
Rossen Stoyanchev 已提交
27
import java.util.concurrent.ConcurrentHashMap;
28 29 30 31 32 33 34 35

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.messaging.Message;
R
Rossen Stoyanchev 已提交
36
import org.springframework.messaging.MessageChannel;
37 38 39 40
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.support.MessageBodyArgumentResolver;
import org.springframework.messaging.handler.annotation.support.MessageExceptionHandlerMethodResolver;
import org.springframework.messaging.handler.method.InvocableMessageHandlerMethod;
41
import org.springframework.messaging.handler.method.MessageArgumentResolverComposite;
42 43 44 45
import org.springframework.messaging.handler.method.MessageReturnValueHandlerComposite;
import org.springframework.messaging.simp.MessageHolder;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
46 47 48 49
import org.springframework.messaging.simp.annotation.SubscribeEvent;
import org.springframework.messaging.simp.annotation.UnsubscribeEvent;
import org.springframework.messaging.simp.annotation.support.MessageSendingReturnValueHandler;
import org.springframework.messaging.simp.annotation.support.PrincipalMessageArgumentResolver;
50
import org.springframework.messaging.support.converter.MessageConverter;
51
import org.springframework.stereotype.Controller;
52
import org.springframework.util.Assert;
53 54 55 56 57 58 59 60 61 62
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils.MethodFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.HandlerMethodSelector;


/**
 * @author Rossen Stoyanchev
 * @since 4.0
 */
63
public class AnnotationSimpMessageHandler extends AbstractSimpMessageHandler
64 65
		implements ApplicationContextAware, InitializingBean {

66
	private final MessageChannel outboundChannel;
67

68
	private MessageConverter<?> messageConverter;
69 70 71 72 73 74 75 76 77

	private ApplicationContext applicationContext;

	private Map<MappingInfo, HandlerMethod> messageMethods = new HashMap<MappingInfo, HandlerMethod>();

	private Map<MappingInfo, HandlerMethod> subscribeMethods = new HashMap<MappingInfo, HandlerMethod>();

	private Map<MappingInfo, HandlerMethod> unsubscribeMethods = new HashMap<MappingInfo, HandlerMethod>();

R
Rossen Stoyanchev 已提交
78 79 80
	private final Map<Class<?>, MessageExceptionHandlerMethodResolver> exceptionHandlerCache =
			new ConcurrentHashMap<Class<?>, MessageExceptionHandlerMethodResolver>(64);

81
	private MessageArgumentResolverComposite argumentResolvers = new MessageArgumentResolverComposite();
82

83
	private MessageReturnValueHandlerComposite returnValueHandlers = new MessageReturnValueHandlerComposite();
84 85


86 87 88 89
	/**
	 * @param inboundChannel a channel for processing incoming messages from clients
	 * @param outboundChannel a channel for messages going out to clients
	 */
90
	public AnnotationSimpMessageHandler(MessageChannel outboundChannel) {
91 92
		Assert.notNull(outboundChannel, "outboundChannel is required");
		this.outboundChannel = outboundChannel;
93
	}
94

95 96 97 98 99
	/**
	 * TODO: multiple converters with 'content-type' header
	 */
	public void setMessageConverter(MessageConverter<?> converter) {
		this.messageConverter = converter;
100 101 102 103 104 105 106
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

107
	@Override
108 109
	protected Collection<SimpMessageType> getSupportedMessageTypes() {
		return Arrays.asList(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE, SimpMessageType.UNSUBSCRIBE);
110 111
	}

112 113
	@Override
	public void afterPropertiesSet() {
A
Andy Wilkinson 已提交
114

R
Rossen Stoyanchev 已提交
115
		initHandlerMethods();
A
Andy Wilkinson 已提交
116

117
		this.argumentResolvers.addResolver(new PrincipalMessageArgumentResolver());
118
		this.argumentResolvers.addResolver(new MessageBodyArgumentResolver(this.messageConverter));
A
Andy Wilkinson 已提交
119

120 121
		this.returnValueHandlers.addHandler(
				new MessageSendingReturnValueHandler(this.outboundChannel, this.messageConverter));
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	}

	protected void initHandlerMethods() {
		String[] beanNames = this.applicationContext.getBeanNamesForType(Object.class);
		for (String beanName : beanNames) {
			if (isHandler(this.applicationContext.getType(beanName))){
				detectHandlerMethods(beanName);
			}
		}
	}

	protected boolean isHandler(Class<?> beanType) {
		return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) ||
				(AnnotationUtils.findAnnotation(beanType, MessageMapping.class) != null));
	}

	protected void detectHandlerMethods(Object handler) {

		Class<?> handlerType = (handler instanceof String) ?
				this.applicationContext.getType((String) handler) : handler.getClass();

		final Class<?> userType = ClassUtils.getUserClass(handlerType);

		initHandlerMethods(handler, userType, MessageMapping.class,
				new MessageMappingInfoCreator(), this.messageMethods);

		initHandlerMethods(handler, userType, SubscribeEvent.class,
				new SubscribeMappingInfoCreator(), this.subscribeMethods);

		initHandlerMethods(handler, userType, UnsubscribeEvent.class,
				new UnsubscribeMappingInfoCreator(), this.unsubscribeMethods);
	}

	private <A extends Annotation> void initHandlerMethods(Object handler, Class<?> handlerType,
156
			final Class<A> annotationType, MappingInfoCreator<A> mappingInfoCreator,
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
			Map<MappingInfo, HandlerMethod> handlerMethods) {

		Set<Method> messageMethods = HandlerMethodSelector.selectMethods(handlerType, new MethodFilter() {
			@Override
			public boolean matches(Method method) {
				return AnnotationUtils.findAnnotation(method, annotationType) != null;
			}
		});

		for (Method method : messageMethods) {
			A annotation = AnnotationUtils.findAnnotation(method, annotationType);
			HandlerMethod hm = createHandlerMethod(handler, method);
			handlerMethods.put(mappingInfoCreator.create(annotation), hm);
		}
	}

	protected HandlerMethod createHandlerMethod(Object handler, Method method) {
		HandlerMethod handlerMethod;
		if (handler instanceof String) {
			String beanName = (String) handler;
			handlerMethod = new HandlerMethod(beanName, this.applicationContext, method);
		}
		else {
			handlerMethod = new HandlerMethod(handler, method);
		}
		return handlerMethod;
	}

	@Override
186
	public void handlePublish(Message<?> message) {
187
		handleMessageInternal(message, this.messageMethods);
188 189 190
	}

	@Override
191
	public void handleSubscribe(Message<?> message) {
192
		handleMessageInternal(message, this.subscribeMethods);
193 194 195
	}

	@Override
196
	public void handleUnsubscribe(Message<?> message) {
197
		handleMessageInternal(message, this.unsubscribeMethods);
198 199
	}

200
	private void handleMessageInternal(final Message<?> message, Map<MappingInfo, HandlerMethod> handlerMethods) {
201

202
		SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
203
		String destination = headers.getDestination();
204 205 206 207 208 209 210 211

		HandlerMethod match = getHandlerMethod(destination, handlerMethods);
		if (match == null) {
			return;
		}

		HandlerMethod handlerMethod = match.createWithResolvedBean();

R
Rossen Stoyanchev 已提交
212
		// TODO: avoid re-creating invocableHandlerMethod
213
		InvocableMessageHandlerMethod invocableHandlerMethod = new InvocableMessageHandlerMethod(handlerMethod);
214 215 216
		invocableHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);

		try {
R
Rossen Stoyanchev 已提交
217 218
			MessageHolder.setMessage(message);

219 220 221 222 223 224 225 226 227
			Object value = invocableHandlerMethod.invoke(message);

			MethodParameter returnType = handlerMethod.getReturnType();
			if (void.class.equals(returnType.getParameterType())) {
				return;
			}

			this.returnValueHandlers.handleReturnValue(value, returnType, message);
		}
R
Rossen Stoyanchev 已提交
228 229 230 231 232 233
		catch (Exception ex) {
			invokeExceptionHandler(message, handlerMethod, ex);
		}
		catch (Throwable ex) {
			// TODO
			ex.printStackTrace();
234
		}
R
Rossen Stoyanchev 已提交
235 236 237
		finally {
			MessageHolder.reset();
		}
238 239
	}

240
	private void invokeExceptionHandler(Message<?> message, HandlerMethod handlerMethod, Exception ex) {
R
Rossen Stoyanchev 已提交
241

242
		InvocableMessageHandlerMethod invocableHandlerMethod;
R
Rossen Stoyanchev 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255
		Class<?> beanType = handlerMethod.getBeanType();
		MessageExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
		if (resolver == null) {
			resolver = new MessageExceptionHandlerMethodResolver(beanType);
			this.exceptionHandlerCache.put(beanType, resolver);
		}

		Method method = resolver.resolveMethod(ex);
		if (method == null) {
			logger.error("Unhandled exception", ex);
			return;
		}

256
		invocableHandlerMethod = new InvocableMessageHandlerMethod(handlerMethod.getBean(), method);
R
Rossen Stoyanchev 已提交
257 258 259 260 261 262 263 264 265 266 267
		invocableHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);

		try {
			invocableHandlerMethod.invoke(message, ex);
		}
		catch (Throwable t) {
			logger.error("Error while handling exception", t);
			return;
		}
	}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	protected HandlerMethod getHandlerMethod(String destination, Map<MappingInfo, HandlerMethod> handlerMethods) {
		for (MappingInfo key : handlerMethods.keySet()) {
			for (String mappingDestination : key.getDestinations()) {
				if (destination.equals(mappingDestination)) {
					return handlerMethods.get(key);
				}
			}
		}
		return null;
	}


	private static class MappingInfo {

		private final List<String> destinations;


		public MappingInfo(List<String> destinations) {
			this.destinations = destinations;
		}

		public List<String> getDestinations() {
			return this.destinations;
		}

		@Override
		public String toString() {
			return "MappingInfo [destinations=" + this.destinations + "]";
		}
	}

	private interface MappingInfoCreator<A extends Annotation> {

		MappingInfo create(A annotation);
	}

	private static class MessageMappingInfoCreator implements MappingInfoCreator<MessageMapping> {

		@Override
		public MappingInfo create(MessageMapping annotation) {
			return new MappingInfo(Arrays.asList(annotation.value()));
		}
	}

	private static class SubscribeMappingInfoCreator implements MappingInfoCreator<SubscribeEvent> {

		@Override
		public MappingInfo create(SubscribeEvent annotation) {
			return new MappingInfo(Arrays.asList(annotation.value()));
		}
	}

	private static class UnsubscribeMappingInfoCreator implements MappingInfoCreator<UnsubscribeEvent> {

		@Override
		public MappingInfo create(UnsubscribeEvent annotation) {
			return new MappingInfo(Arrays.asList(annotation.value()));
		}
	}

}