Java Code Examples for org.springframework.messaging.MessageHandler#handleMessage()

The following examples show how to use org.springframework.messaging.MessageHandler#handleMessage() . 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: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodWithStringParameterCallExceptionHandler() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  applicationContext.refresh();

  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);

  IncomingMessageHandler messageListener =
      applicationContext.getBean(IncomingMessageHandler.class);
  messageListener.setExceptionHandlerCalled(false);
  try {
    messageHandler.handleMessage(buildMessage(exceptionQueue, message));
  } catch (Exception e) {
    // ignore
  }
  assertTrue(messageListener.isExceptionHandlerCalled());
  assertEquals(message, messageListener.getLastReceivedMessage());
}
 
Example 2
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodHavingMultipleQueueNames() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  applicationContext.refresh();

  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);

  IncomingMessageHandler messageListener =
      applicationContext.getBean(IncomingMessageHandler.class);
  messageListener.setExceptionHandlerCalled(false);
  messageHandler.handleMessage(buildMessage(slowQueue, message));
  assertEquals(message, messageListener.getLastReceivedMessage());
  messageListener.setLastReceivedMessage(null);
  messageHandler.handleMessage(buildMessage(smartQueue, message + message));
  assertEquals(message + message, messageListener.getLastReceivedMessage());
}
 
Example 3
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_methodAnnotatedWithSqsListenerAnnotation_methodInvokedForIncomingMessage() {
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("incomingMessageHandler",
			IncomingMessageHandler.class);
	applicationContext.registerSingleton("queueMessageHandler",
			QueueMessageHandler.class);
	applicationContext.refresh();

	MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
	messageHandler.handleMessage(MessageBuilder.withPayload("testContent")
			.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receive").build());

	IncomingMessageHandler messageListener = applicationContext
			.getBean(IncomingMessageHandler.class);
	assertThat(messageListener.getLastReceivedMessage()).isEqualTo("testContent");
}
 
Example 4
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodHavingNameFromPropertyFile() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("messageHandler", MessageHandlersWithProperty.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  Map<String, Object> map = new HashMap<>();
  map.put("slow.queue.name", slowQueue);
  map.put("smart.queue.name", smartQueue);
  applicationContext
      .getEnvironment()
      .getPropertySources()
      .addLast(new MapPropertySource("test", map));

  applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
  applicationContext.refresh();
  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
  MessageHandlersWithProperty messageListener =
      applicationContext.getBean(MessageHandlersWithProperty.class);
  messageHandler.handleMessage(buildMessage(slowQueue, message));
  assertEquals(message, messageListener.getLastReceivedMessage());
  messageListener.setLastReceivedMessage(null);
  messageHandler.handleMessage(buildMessage(smartQueue, message + message));
  assertEquals(message + message, messageListener.getLastReceivedMessage());
}
 
Example 5
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodHavingNameFromPropertyFileWithExpression() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton(
      "messageHandler", MessageHandlerWithExpressionProperty.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);

  applicationContext
      .getEnvironment()
      .getPropertySources()
      .addLast(new MapPropertySource("test", Collections.singletonMap("queueName", slowQueue)));

  applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
  applicationContext.refresh();
  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
  MessageHandlerWithExpressionProperty messageListener =
      applicationContext.getBean(MessageHandlerWithExpressionProperty.class);
  messageHandler.handleMessage(buildMessage(slowQueue, message));
  assertEquals(message, messageListener.getLastReceivedMessage());
}
 
Example 6
Source File: RepublishUnitTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadRepublishSetting() throws IOException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection conn = mock(Connection.class);
	given(cf.createConnection()).willReturn(conn);
	Channel channel = mock(Channel.class);
	given(channel.isOpen()).willReturn(true);
	given(channel.exchangeDeclarePassive("DLX")).willThrow(new IOException());
	given(conn.createChannel(false)).willReturn(channel);
	RabbitProperties props = new RabbitProperties();
	RabbitMessageChannelBinder binder = new RabbitMessageChannelBinder(cf, props, null);
	RabbitConsumerProperties extension = new RabbitConsumerProperties();
	ExtendedConsumerProperties<RabbitConsumerProperties> bindingProps =
			new ExtendedConsumerProperties<RabbitConsumerProperties>(extension);
	MessageHandler handler = binder.getErrorMessageHandler(mock(ConsumerDestination.class), "foo", bindingProps);
	ErrorMessage message = new ErrorMessage(new RuntimeException("test"),
			Collections.singletonMap(IntegrationMessageHeaderAccessor.SOURCE_DATA,
					new Message("foo".getBytes(), new MessageProperties())));
	handler.handleMessage(message);
	handler.handleMessage(message);
	verify(channel, times(1)).exchangeDeclarePassive("DLX");
	verify(channel, never()).basicPublish(any(), any(), eq(false), any(), any());
}
 
Example 7
Source File: StompBrokerRelayMessageHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void handleInboundMessage(Message<?> message) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	if (accessor != null && StompCommand.MESSAGE.equals(accessor.getCommand())) {
		String destination = accessor.getDestination();
		if (destination == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Got message on \"system\" connection, with no destination: " +
						accessor.getDetailedLogMessage(message.getPayload()));
			}
			return;
		}
		if (!getSystemSubscriptions().containsKey(destination)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Got message on \"system\" connection with no handler: " +
						accessor.getDetailedLogMessage(message.getPayload()));
			}
			return;
		}
		try {
			MessageHandler handler = getSystemSubscriptions().get(destination);
			handler.handleMessage(message);
		}
		catch (Throwable ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error while handling message on \"system\" connection.", ex);
			}
		}
	}
}
 
Example 8
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void receiveAndReplayMessage_withExceptionThrownInSendTo_shouldCallExceptionHandler() {
	// Arrange
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("incomingMessageHandler",
			IncomingMessageHandler.class);
	applicationContext.registerBeanDefinition("queueMessageHandler",
			getQueueMessageHandlerBeanDefinition());
	applicationContext.refresh();

	MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
	doThrow(new RuntimeException()).when(this.messageTemplate)
			.convertAndSend(anyString(), Optional.ofNullable(any()));
	IncomingMessageHandler messageListener = applicationContext
			.getBean(IncomingMessageHandler.class);
	messageListener.setExceptionHandlerCalled(false);

	// Act
	try {
		messageHandler.handleMessage(MessageBuilder.withPayload("testContent")
				.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receiveAndReply")
				.build());
	}
	catch (MessagingException e) {
		// ignore
	}

	// Assert
	assertThat(messageListener.isExceptionHandlerCalled()).isTrue();
}
 
Example 9
Source File: DefaultPollableMessageSource.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
private void doHandleMessage(MessageHandler handler, Message<?> message) {
	try {
		handler.handleMessage(message);
	}
	catch (Throwable t) { // NOSONAR
		throw new MessageHandlingException(message, t);
	}
}
 
Example 10
Source File: TracingMethodMessageHandlerAdapter.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
void wrapMethodMessageHandler(Message<?> message, MessageHandler messageHandler,
		BiConsumer<Span, Message<?>> messageSpanTagger) {
	MessageConsumerRequest request = new MessageConsumerRequest(message, this.getter);
	TraceContextOrSamplingFlags extracted = extractAndClearHeaders(request);

	Span consumerSpan = tracer.nextSpan(extracted);
	Span listenerSpan = tracer.newChild(consumerSpan.context());

	if (!consumerSpan.isNoop()) {
		consumerSpan.name("next-message").kind(CONSUMER);
		if (messageSpanTagger != null) {
			messageSpanTagger.accept(consumerSpan, message);
		}

		// incur timestamp overhead only once
		long timestamp = tracing.clock(consumerSpan.context())
				.currentTimeMicroseconds();
		consumerSpan.start(timestamp);
		long consumerFinish = timestamp + 1L; // save a clock reading
		consumerSpan.finish(consumerFinish);

		// not using scoped span as we want to start with a pre-configured time
		listenerSpan.name("on-message").start(consumerFinish);
	}

	try (Tracer.SpanInScope ws = tracer.withSpanInScope(listenerSpan)) {
		messageHandler.handleMessage(message);
	}
	catch (Throwable t) {
		listenerSpan.error(t);
		throw t;
	}
	finally {
		listenerSpan.finish();
	}
}
 
Example 11
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Override
protected MessageHandler getPolledConsumerErrorMessageHandler(
		ConsumerDestination destination, String group,
		ExtendedConsumerProperties<RabbitConsumerProperties> properties) {
	MessageHandler handler = getErrorMessageHandler(destination, group, properties);
	if (handler != null) {
		return handler;
	}
	final MessageHandler superHandler = super.getErrorMessageHandler(destination,
			group, properties);
	return message -> {
		Message amqpMessage = (Message) message.getHeaders()
				.get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE);
		if (!(message instanceof ErrorMessage)) {
			logger.error("Expected an ErrorMessage, not a "
					+ message.getClass().toString() + " for: " + message);
		}
		else if (amqpMessage == null) {
			if (superHandler != null) {
				superHandler.handleMessage(message);
			}
		}
		else {
			if (message.getPayload() instanceof MessagingException) {
				AcknowledgmentCallback ack = StaticMessageHeaderAccessor
						.getAcknowledgmentCallback(
								((MessagingException) message.getPayload())
										.getFailedMessage());
				if (ack != null) {
					if (properties.getExtension().isRequeueRejected()) {
						ack.acknowledge(Status.REQUEUE);
					}
					else {
						ack.acknowledge(Status.REJECT);
					}
				}
			}
		}
	};
}
 
Example 12
Source File: KafkaMessageChannelBinder.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Override
protected MessageHandler getPolledConsumerErrorMessageHandler(
		ConsumerDestination destination, String group,
		ExtendedConsumerProperties<KafkaConsumerProperties> properties) {
	if (properties.getExtension().isEnableDlq()) {
		return getErrorMessageHandler(destination, group, properties);
	}
	final MessageHandler superHandler = super.getErrorMessageHandler(destination,
			group, properties);
	return (message) -> {
		ConsumerRecord<?, ?> record = (ConsumerRecord<?, ?>) message.getHeaders()
				.get(KafkaHeaders.RAW_DATA);
		if (!(message instanceof ErrorMessage)) {
			logger.error("Expected an ErrorMessage, not a "
					+ message.getClass().toString() + " for: " + message);
		}
		else if (record == null) {
			if (superHandler != null) {
				superHandler.handleMessage(message);
			}
		}
		else {
			if (message.getPayload() instanceof MessagingException) {
				AcknowledgmentCallback ack = StaticMessageHeaderAccessor
						.getAcknowledgmentCallback(
								((MessagingException) message.getPayload())
										.getFailedMessage());
				if (ack != null) {
					if (isAutoCommitOnError(properties)) {
						ack.acknowledge(AcknowledgmentCallback.Status.REJECT);
					}
					else {
						ack.acknowledge(AcknowledgmentCallback.Status.REQUEUE);
					}
				}
			}
		}
	};
}
 
Example 13
Source File: StompBrokerRelayMessageHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleInboundMessage(Message<?> message) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	if (StompCommand.MESSAGE.equals(accessor.getCommand())) {
		String destination = accessor.getDestination();
		if (destination == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Got message on \"system\" connection, with no destination: " +
						accessor.getDetailedLogMessage(message.getPayload()));
			}
			return;
		}
		if (!getSystemSubscriptions().containsKey(destination)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Got message on \"system\" connection with no handler: " +
						accessor.getDetailedLogMessage(message.getPayload()));
			}
			return;
		}
		try {
			MessageHandler handler = getSystemSubscriptions().get(destination);
			handler.handleMessage(message);
		}
		catch (Throwable ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error while handling message on \"system\" connection.", ex);
			}
		}
	}
}
 
Example 14
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodWithStringParameterIsInvoked() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  applicationContext.refresh();
  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
  messageHandler.handleMessage(buildMessage(testQueue, message));
  IncomingMessageHandler messageListener =
      applicationContext.getBean(IncomingMessageHandler.class);
  assertEquals(message, messageListener.getLastReceivedMessage());
}
 
Example 15
Source File: StompBrokerRelayMessageHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void handleInboundMessage(Message<?> message) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	if (accessor != null && StompCommand.MESSAGE.equals(accessor.getCommand())) {
		String destination = accessor.getDestination();
		if (destination == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Got message on \"system\" connection, with no destination: " +
						accessor.getDetailedLogMessage(message.getPayload()));
			}
			return;
		}
		if (!getSystemSubscriptions().containsKey(destination)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Got message on \"system\" connection with no handler: " +
						accessor.getDetailedLogMessage(message.getPayload()));
			}
			return;
		}
		try {
			MessageHandler handler = getSystemSubscriptions().get(destination);
			handler.handleMessage(message);
		}
		catch (Throwable ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error while handling message on \"system\" connection.", ex);
			}
		}
	}
}
 
Example 16
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodHavingSpelGettingEvaluated() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("spelMessageHandler", SpelMessageHandler.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  applicationContext.refresh();
  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
  SpelMessageHandler messageListener = applicationContext.getBean(SpelMessageHandler.class);
  messageHandler.handleMessage(buildMessage(slowQueue, message));
  assertEquals(message, messageListener.getLastReceivedMessage());
  messageListener.setLastReceivedMessage(null);
  messageHandler.handleMessage(buildMessage(smartQueue, message + message));
  assertEquals(message + message, messageListener.getLastReceivedMessage());
}
 
Example 17
Source File: RqueueMessageHandlerTest.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodWithMessagePayloadParameterIsInvoked() {
  StaticApplicationContext applicationContext = new StaticApplicationContext();
  applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class);
  applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
  applicationContext.refresh();
  MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
  messageHandler.handleMessage(buildMessage(messagePayloadQueue, payloadConvertedMessage));
  IncomingMessageHandler messageListener =
      applicationContext.getBean(IncomingMessageHandler.class);
  assertEquals(messagePayload, messageListener.getLastReceivedMessage());
}