org.springframework.messaging.handler.HandlerMethod Java Examples

The following examples show how to use org.springframework.messaging.handler.HandlerMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Find an {@code @MessageExceptionHandler} method for the given exception.
 * The default implementation searches methods in the class hierarchy of the
 * HandlerMethod first and if not found, it continues searching for additional
 * {@code @MessageExceptionHandler} methods among the configured
 * {@linkplain org.springframework.messaging.handler.MessagingAdviceBean
 * MessagingAdviceBean}, if any.
 * @param handlerMethod the method where the exception was raised
 * @param exception the raised exception
 * @return a method to handle the exception, or {@code null}
 * @since 4.2
 */
protected InvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
	if (logger.isDebugEnabled()) {
		logger.debug("Searching methods to handle " + exception.getClass().getSimpleName());
	}
	Class<?> beanType = handlerMethod.getBeanType();
	AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
	if (resolver == null) {
		resolver = createExceptionHandlerMethodResolverFor(beanType);
		this.exceptionHandlerCache.put(beanType, resolver);
	}
	Method method = resolver.resolveMethod(exception);
	if (method != null) {
		return new InvocableHandlerMethod(handlerMethod.getBean(), method);
	}
	for (MessagingAdviceBean advice : this.exceptionHandlerAdviceCache.keySet()) {
		if (advice.isApplicableToBeanType(beanType)) {
			resolver = this.exceptionHandlerAdviceCache.get(advice);
			method = resolver.resolveMethod(exception);
			if (method != null) {
				return new InvocableHandlerMethod(advice.resolveBean(), method);
			}
		}
	}
	return null;
}
 
Example #2
Source File: AbstractMethodMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Register a handler method and its unique mapping.
 * @param handler the bean name of the handler or the handler instance
 * @param method the method to register
 * @param mapping the mapping conditions associated with the handler method
 * @throws IllegalStateException if another method was already registered
 * under the same mapping
 */
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
	Assert.notNull(mapping, "Mapping must not be null");
	HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
	HandlerMethod oldHandlerMethod = this.handlerMethods.get(mapping);

	if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
		throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean() +
				"' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '" +
				oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
	}

	this.handlerMethods.put(mapping, newHandlerMethod);

	for (String pattern : getDirectLookupDestinations(mapping)) {
		this.destinationLookup.add(pattern, mapping);
	}
}
 
Example #3
Source File: AbstractMethodMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected void processHandlerMethodException(HandlerMethod handlerMethod, Exception exception, Message<?> message) {
	InvocableHandlerMethod invocable = getExceptionHandlerMethod(handlerMethod, exception);
	if (invocable == null) {
		logger.error("Unhandled exception from message handler method", exception);
		return;
	}
	invocable.setMessageMethodArgumentResolvers(this.argumentResolvers);
	if (logger.isDebugEnabled()) {
		logger.debug("Invoking " + invocable.getShortLogMessage());
	}
	try {
		Throwable cause = exception.getCause();
		Object returnValue = (cause != null ?
				invocable.invoke(message, exception, cause, handlerMethod) :
				invocable.invoke(message, exception, handlerMethod));
		MethodParameter returnType = invocable.getReturnType();
		if (void.class == returnType.getParameterType()) {
			return;
		}
		this.returnValueHandlers.handleReturnValue(returnValue, returnType, message);
	}
	catch (Throwable ex2) {
		logger.error("Error while processing handler method exception", ex2);
	}
}
 
Example #4
Source File: SimpAnnotationMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleMatch(SimpMessageMappingInfo mapping, HandlerMethod handlerMethod,
		String lookupDestination, Message<?> message) {

	Set<String> patterns = mapping.getDestinationConditions().getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable());
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}

	try {
		SimpAttributesContextHolder.setAttributesFromMessage(message);
		super.handleMatch(mapping, handlerMethod, lookupDestination, message);
	}
	finally {
		SimpAttributesContextHolder.resetAttributes();
	}
}
 
Example #5
Source File: AbstractMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Register a handler method and its unique mapping.
 * @param handler the bean name of the handler or the handler instance
 * @param method the method to register
 * @param mapping the mapping conditions associated with the handler method
 * @throws IllegalStateException if another method was already registered
 * under the same mapping
 */
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
	Assert.notNull(mapping, "Mapping must not be null");
	HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
	HandlerMethod oldHandlerMethod = this.handlerMethods.get(mapping);

	if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
		throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean() +
				"' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '" +
				oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
	}

	this.handlerMethods.put(mapping, newHandlerMethod);
	if (logger.isInfoEnabled()) {
		logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod);
	}

	for (String pattern : getDirectLookupDestinations(mapping)) {
		this.destinationLookup.add(pattern, mapping);
	}
}
 
Example #6
Source File: AbstractMethodMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Register a handler method and its unique mapping.
 * <p><strong>Note:</strong> This method is protected and can be invoked by
 * sub-classes. Keep in mind however that the registration is not protected
 * for concurrent use, and is expected to be done on startup.
 * @param handler the bean name of the handler or the handler instance
 * @param method the method to register
 * @param mapping the mapping conditions associated with the handler method
 * @throws IllegalStateException if another method was already registered
 * under the same mapping
 */
protected final void registerHandlerMethod(Object handler, Method method, T mapping) {
	Assert.notNull(mapping, "Mapping must not be null");
	HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
	HandlerMethod oldHandlerMethod = this.handlerMethods.get(mapping);

	if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
		throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean() +
				"' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '" +
				oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
	}

	this.handlerMethods.put(mapping, newHandlerMethod);

	for (String pattern : getDirectLookupMappings(mapping)) {
		this.destinationLookup.add(pattern, mapping);
	}
}
 
Example #7
Source File: AbstractMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected void processHandlerMethodException(HandlerMethod handlerMethod, Exception ex, Message<?> message) {
	InvocableHandlerMethod invocable = getExceptionHandlerMethod(handlerMethod, ex);
	if (invocable == null) {
		logger.error("Unhandled exception", ex);
		return;
	}
	invocable.setMessageMethodArgumentResolvers(this.argumentResolvers);
	if (logger.isDebugEnabled()) {
		logger.debug("Invoking " + invocable.getShortLogMessage());
	}
	try {
		Object returnValue = invocable.invoke(message, ex, handlerMethod);
		MethodParameter returnType = invocable.getReturnType();
		if (void.class == returnType.getParameterType()) {
			return;
		}
		this.returnValueHandlers.handleReturnValue(returnValue, returnType, message);
	}
	catch (Throwable ex2) {
		logger.error("Error while processing handler method exception", ex2);
	}
}
 
Example #8
Source File: AbstractMethodMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected void processHandlerMethodException(HandlerMethod handlerMethod, Exception exception, Message<?> message) {
	InvocableHandlerMethod invocable = getExceptionHandlerMethod(handlerMethod, exception);
	if (invocable == null) {
		logger.error("Unhandled exception from message handler method", exception);
		return;
	}
	invocable.setMessageMethodArgumentResolvers(this.argumentResolvers);
	if (logger.isDebugEnabled()) {
		logger.debug("Invoking " + invocable.getShortLogMessage());
	}
	try {
		Throwable cause = exception.getCause();
		Object returnValue = (cause != null ?
				invocable.invoke(message, exception, cause, handlerMethod) :
				invocable.invoke(message, exception, handlerMethod));
		MethodParameter returnType = invocable.getReturnType();
		if (void.class == returnType.getParameterType()) {
			return;
		}
		this.returnValueHandlers.handleReturnValue(returnValue, returnType, message);
	}
	catch (Throwable ex2) {
		logger.error("Error while processing handler method exception", ex2);
	}
}
 
Example #9
Source File: InvocableHelper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public Mono<Void> handleMessage(HandlerMethod handlerMethod, Message<?> message) {
	InvocableHandlerMethod invocable = initMessageMappingMethod(handlerMethod);
	if (logger.isDebugEnabled()) {
		logger.debug("Invoking " + invocable.getShortLogMessage());
	}
	return invocable.invoke(message)
			.switchIfEmpty(Mono.defer(() -> handleReturnValue(null, invocable, message)))
			.flatMap(returnValue -> handleReturnValue(returnValue, invocable, message))
			.onErrorResume(ex -> {
				InvocableHandlerMethod exHandler = initExceptionHandlerMethod(handlerMethod, ex);
				if (exHandler == null) {
					return Mono.error(ex);
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Invoking " + exHandler.getShortLogMessage());
				}
				return exHandler.invoke(message, ex)
						.switchIfEmpty(Mono.defer(() -> handleReturnValue(null, exHandler, message)))
						.flatMap(returnValue -> handleReturnValue(returnValue, exHandler, message));
			});
}
 
Example #10
Source File: AbstractMethodMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Register a handler method and its unique mapping.
 * @param handler the bean name of the handler or the handler instance
 * @param method the method to register
 * @param mapping the mapping conditions associated with the handler method
 * @throws IllegalStateException if another method was already registered
 * under the same mapping
 */
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
	Assert.notNull(mapping, "Mapping must not be null");
	HandlerMethod newHandlerMethod = createHandlerMethod(handler, method);
	HandlerMethod oldHandlerMethod = this.handlerMethods.get(mapping);

	if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) {
		throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean() +
				"' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '" +
				oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped.");
	}

	this.handlerMethods.put(mapping, newHandlerMethod);
	if (logger.isTraceEnabled()) {
		logger.trace("Mapped \"" + mapping + "\" onto " + newHandlerMethod);
	}

	for (String pattern : getDirectLookupDestinations(mapping)) {
		this.destinationLookup.add(pattern, mapping);
	}
}
 
Example #11
Source File: SimpAnnotationMethodMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void handleMatch(SimpMessageMappingInfo mapping, HandlerMethod handlerMethod,
		String lookupDestination, Message<?> message) {

	Set<String> patterns = mapping.getDestinationConditions().getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required");
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}

	try {
		SimpAttributesContextHolder.setAttributesFromMessage(message);
		super.handleMatch(mapping, handlerMethod, lookupDestination, message);
	}
	finally {
		SimpAttributesContextHolder.resetAttributes();
	}
}
 
Example #12
Source File: MessageMappingMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> handleMatch(CompositeMessageCondition mapping, HandlerMethod handlerMethod, Message<?> message) {
	Set<String> patterns = mapping.getCondition(DestinationPatternsMessageCondition.class).getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		String destination = getDestination(message);
		Assert.state(destination != null, "Missing destination header");
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, destination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required");
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}
	return super.handleMatch(mapping, handlerMethod, message);
}
 
Example #13
Source File: SimpAnnotationMethodMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void handleMatch(SimpMessageMappingInfo mapping, HandlerMethod handlerMethod,
		String lookupDestination, Message<?> message) {

	Set<String> patterns = mapping.getDestinationConditions().getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required");
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}

	try {
		SimpAttributesContextHolder.setAttributesFromMessage(message);
		super.handleMatch(mapping, handlerMethod, lookupDestination, message);
	}
	finally {
		SimpAttributesContextHolder.resetAttributes();
	}
}
 
Example #14
Source File: MethodMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void registeredMappings() {
	TestMethodMessageHandler messageHandler = initMethodMessageHandler(TestController.class);
	Map<String, HandlerMethod> mappings = messageHandler.getHandlerMethods();

	assertEquals(5, mappings.keySet().size());
	assertThat(mappings.keySet(), Matchers.containsInAnyOrder(
			"/handleMessage", "/handleMessageWithArgument", "/handleMessageWithError",
			"/handleMessageMatch1", "/handleMessageMatch2"));
}
 
Example #15
Source File: AbstractMethodMessageHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Find an {@code @MessageExceptionHandler} method for the given exception.
 * The default implementation searches methods in the class hierarchy of the
 * HandlerMethod first and if not found, it continues searching for additional
 * {@code @MessageExceptionHandler} methods among the configured
 * {@linkplain org.springframework.messaging.handler.MessagingAdviceBean
 * MessagingAdviceBean}, if any.
 * @param handlerMethod the method where the exception was raised
 * @param exception the raised exception
 * @return a method to handle the exception, or {@code null}
 * @since 4.2
 */
@Nullable
protected InvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
	if (logger.isDebugEnabled()) {
		logger.debug("Searching methods to handle " + exception.getClass().getSimpleName());
	}
	Class<?> beanType = handlerMethod.getBeanType();
	AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
	if (resolver == null) {
		resolver = createExceptionHandlerMethodResolverFor(beanType);
		this.exceptionHandlerCache.put(beanType, resolver);
	}
	Method method = resolver.resolveMethod(exception);
	if (method != null) {
		return new InvocableHandlerMethod(handlerMethod.getBean(), method);
	}
	for (MessagingAdviceBean advice : this.exceptionHandlerAdviceCache.keySet()) {
		if (advice.isApplicableToBeanType(beanType)) {
			resolver = this.exceptionHandlerAdviceCache.get(advice);
			method = resolver.resolveMethod(exception);
			if (method != null) {
				return new InvocableHandlerMethod(advice.resolveBean(), method);
			}
		}
	}
	return null;
}
 
Example #16
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void exceptionWithHandlerMethodArg() {
	Message<?> message = createMessage("/pre/illegalState");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("illegalState", handlerMethod.getMethod().getName());
}
 
Example #17
Source File: MethodMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void registeredMappings() {

	Map<String, HandlerMethod> handlerMethods = this.messageHandler.getHandlerMethods();

	assertNotNull(handlerMethods);
	assertThat(handlerMethods.keySet(), Matchers.hasSize(3));
}
 
Example #18
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void exceptionAsCause() {
	Message<?> message = createMessage("/pre/illegalStateCause");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("illegalStateCause", handlerMethod.getMethod().getName());
}
 
Example #19
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void errorAsMessageHandlingException() {
	Message<?> message = createMessage("/pre/error");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleErrorWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("errorAsThrowable", handlerMethod.getMethod().getName());
}
 
Example #20
Source File: MethodMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void registeredMappings() {

	Map<String, HandlerMethod> handlerMethods = this.messageHandler.getHandlerMethods();

	assertNotNull(handlerMethods);
	assertThat(handlerMethods.keySet(), Matchers.hasSize(3));
}
 
Example #21
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptionWithHandlerMethodArg() {
	Message<?> message = createMessage("/pre/illegalState");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("illegalState", handlerMethod.getMethod().getName());
}
 
Example #22
Source File: MethodMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void registeredMappings() {

	Map<String, HandlerMethod> handlerMethods = this.messageHandler.getHandlerMethods();

	assertNotNull(handlerMethods);
	assertThat(handlerMethods.keySet(), Matchers.hasSize(3));
}
 
Example #23
Source File: QueueMessageHandler.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
protected void processHandlerMethodException(HandlerMethod handlerMethod,
		Exception ex, Message<?> message) {
	InvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(
			handlerMethod, ex);
	if (exceptionHandlerMethod != null) {
		super.processHandlerMethodException(handlerMethod, ex, message);
	}
	else {
		this.logger.error("An exception occurred while invoking the handler method",
				ex);
	}
	throw new MessagingException(
			"An exception occurred while invoking the handler method", ex);
}
 
Example #24
Source File: SimpleMessageListenerContainerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testWithDefaultTaskExecutorAndOneHandler() throws Exception {
	int testedMaxNumberOfMessages = 10;

	Map<QueueMessageHandler.MappingInformation, HandlerMethod> messageHandlerMethods = Collections
			.singletonMap(new QueueMessageHandler.MappingInformation(
					Collections.singleton("testQueue"),
					SqsMessageDeletionPolicy.ALWAYS), null);

	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();

	QueueMessageHandler mockedHandler = mock(QueueMessageHandler.class);
	AmazonSQSAsync mockedSqs = mock(AmazonSQSAsync.class, withSettings().stubOnly());

	when(mockedSqs.getQueueAttributes(any(GetQueueAttributesRequest.class)))
			.thenReturn(new GetQueueAttributesResult());
	when(mockedSqs.getQueueUrl(any(GetQueueUrlRequest.class)))
			.thenReturn(new GetQueueUrlResult().withQueueUrl("testQueueUrl"));
	when(mockedHandler.getHandlerMethods()).thenReturn(messageHandlerMethods);

	container.setMaxNumberOfMessages(testedMaxNumberOfMessages);
	container.setAmazonSqs(mockedSqs);
	container.setMessageHandler(mockedHandler);

	container.afterPropertiesSet();

	int expectedPoolMaxSize = messageHandlerMethods.size()
			* (testedMaxNumberOfMessages + 1);

	ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) container
			.getTaskExecutor();
	assertThat(taskExecutor).isNotNull();
	assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(expectedPoolMaxSize);
}
 
Example #25
Source File: AbstractMethodMessageHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private Match<T> getHandlerMethod(Message<?> message) {
	List<Match<T>> matches = new ArrayList<>();

	String destination = getDestination(message);
	List<T> mappingsByUrl = destination != null ? this.destinationLookup.get(destination) : null;
	if (mappingsByUrl != null) {
		addMatchesToCollection(mappingsByUrl, message, matches);
	}
	if (matches.isEmpty()) {
		// No direct hits, go through all mappings
		Set<T> allMappings = this.handlerMethods.keySet();
		addMatchesToCollection(allMappings, message, matches);
	}
	if (matches.isEmpty()) {
		handleNoMatch(destination, message);
		return null;
	}
	Comparator<Match<T>> comparator = new MatchComparator(getMappingComparator(message));
	matches.sort(comparator);
	if (logger.isTraceEnabled()) {
		logger.trace("Found " + matches.size() + " handler methods: " + matches);
	}
	Match<T> bestMatch = matches.get(0);
	if (matches.size() > 1) {
		Match<T> secondBestMatch = matches.get(1);
		if (comparator.compare(bestMatch, secondBestMatch) == 0) {
			HandlerMethod m1 = bestMatch.handlerMethod;
			HandlerMethod m2 = secondBestMatch.handlerMethod;
			throw new IllegalStateException("Ambiguous handler methods mapped for destination '" +
					destination + "': {" + m1.getShortLogMessage() + ", " + m2.getShortLogMessage() + "}");
		}
	}
	return bestMatch;
}
 
Example #26
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void errorAsMessageHandlingException() {
	Message<?> message = createMessage("/pre/error");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleErrorWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("errorAsThrowable", handlerMethod.getMethod().getName());
}
 
Example #27
Source File: InvocableHelper.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create {@link InvocableHandlerMethod} with the configured arg resolvers.
 * @param handlerMethod the target handler method to invoke
 * @return the created instance
 */

public InvocableHandlerMethod initMessageMappingMethod(HandlerMethod handlerMethod) {
	InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
	invocable.setArgumentResolvers(this.argumentResolvers.getResolvers());
	return invocable;
}
 
Example #28
Source File: InvocableHelper.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Find an exception handling method for the given exception.
 * <p>The default implementation searches methods in the class hierarchy of
 * the HandlerMethod first and if not found, it continues searching for
 * additional handling methods registered via
 * {@link #registerExceptionHandlerAdvice}.
 * @param handlerMethod the method where the exception was raised
 * @param ex the exception raised or signaled
 * @return a method to handle the exception, or {@code null}
 */
@Nullable
public InvocableHandlerMethod initExceptionHandlerMethod(HandlerMethod handlerMethod, Throwable ex) {
	if (logger.isDebugEnabled()) {
		logger.debug("Searching for methods to handle " + ex.getClass().getSimpleName());
	}
	Class<?> beanType = handlerMethod.getBeanType();
	AbstractExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
	if (resolver == null) {
		resolver = this.exceptionMethodResolverFactory.apply(beanType);
		this.exceptionHandlerCache.put(beanType, resolver);
	}
	InvocableHandlerMethod exceptionHandlerMethod = null;
	Method method = resolver.resolveMethod(ex);
	if (method != null) {
		exceptionHandlerMethod = new InvocableHandlerMethod(handlerMethod.getBean(), method);
	}
	else {
		for (MessagingAdviceBean advice : this.exceptionHandlerAdviceCache.keySet()) {
			if (advice.isApplicableToBeanType(beanType)) {
				resolver = this.exceptionHandlerAdviceCache.get(advice);
				method = resolver.resolveMethod(ex);
				if (method != null) {
					exceptionHandlerMethod = new InvocableHandlerMethod(advice.resolveBean(), method);
					break;
				}
			}
		}
	}
	if (exceptionHandlerMethod != null) {
		logger.debug("Found exception handler " + exceptionHandlerMethod.getShortLogMessage());
		exceptionHandlerMethod.setArgumentResolvers(this.argumentResolvers.getResolvers());
	}
	else {
		logger.error("No exception handling method", ex);
	}
	return exceptionHandlerMethod;
}
 
Example #29
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void exceptionAsCause() {
	Message<?> message = createMessage("/pre/illegalStateCause");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("illegalStateCause", handlerMethod.getMethod().getName());
}
 
Example #30
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void exceptionWithHandlerMethodArg() {
	Message<?> message = createMessage("/pre/illegalState");
	this.messageHandler.registerHandler(this.testController);
	this.messageHandler.handleMessage(message);

	assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method);
	HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod");
	assertNotNull(handlerMethod);
	assertEquals("illegalState", handlerMethod.getMethod().getName());
}