Search in sources :

Example 41 with MessageDeliveryException

use of org.springframework.messaging.MessageDeliveryException in project spring-integration by spring-projects.

the class StompMessageHandlerWebSocketIntegrationTests method testStompMessageHandler.

@Test
public void testStompMessageHandler() throws InterruptedException {
    StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
    headers.setDestination("/app/simple");
    Message<String> message = MessageBuilder.withPayload("foo").setHeaders(headers).build();
    this.webSocketOutputChannel.send(message);
    SimpleController controller = this.serverContext.getBean(SimpleController.class);
    assertTrue(controller.latch.await(10, TimeUnit.SECONDS));
    Message<?> receive = this.stompEvents.receive(10000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(StompSessionConnectedEvent.class));
    // Simple Broker Relay doesn't support RECEIPT Frame, so we check here the 'lost' StompReceiptEvent
    receive = this.stompEvents.receive(10000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(StompReceiptEvent.class));
    StompReceiptEvent stompReceiptEvent = (StompReceiptEvent) receive.getPayload();
    assertEquals(StompCommand.SEND, stompReceiptEvent.getStompCommand());
    assertEquals("/app/simple", stompReceiptEvent.getDestination());
    assertTrue(stompReceiptEvent.isLost());
    assertNotNull(stompReceiptEvent.getMessage());
    headers = StompHeaderAccessor.create(StompCommand.SEND);
    headers.setDestination("/foo");
    message = MessageBuilder.withPayload("bar").setHeaders(headers).build();
    this.webSocketOutputChannel.send(message);
    receive = this.stompEvents.receive(10000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(StompExceptionEvent.class));
    StompExceptionEvent stompExceptionEvent = (StompExceptionEvent) receive.getPayload();
    Throwable cause = stompExceptionEvent.getCause();
    assertThat(cause, instanceOf(MessageDeliveryException.class));
    MessageDeliveryException messageDeliveryException = (MessageDeliveryException) cause;
    Message<?> failedMessage = messageDeliveryException.getFailedMessage();
    assertThat((String) failedMessage.getPayload(), containsString("preSend intentional Exception"));
    receive = this.stompEvents.receive(10000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(StompReceiptEvent.class));
    stompReceiptEvent = (StompReceiptEvent) receive.getPayload();
    assertEquals(StompCommand.SEND, stompReceiptEvent.getStompCommand());
    assertEquals("/foo", stompReceiptEvent.getDestination());
    assertTrue(stompReceiptEvent.isLost());
}
Also used : StompReceiptEvent(org.springframework.integration.stomp.event.StompReceiptEvent) StompExceptionEvent(org.springframework.integration.stomp.event.StompExceptionEvent) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) Matchers.containsString(org.hamcrest.Matchers.containsString) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) StompSessionConnectedEvent(org.springframework.integration.stomp.event.StompSessionConnectedEvent) LongRunningIntegrationTest(org.springframework.integration.test.support.LongRunningIntegrationTest) Test(org.junit.Test)

Example 42 with MessageDeliveryException

use of org.springframework.messaging.MessageDeliveryException in project spring-integration by spring-projects.

the class SubscribableJmsChannelTests method dispatcherHasNoSubscribersQueue.

@Test
public void dispatcherHasNoSubscribersQueue() throws Exception {
    JmsChannelFactoryBean factoryBean = new JmsChannelFactoryBean(true);
    factoryBean.setConnectionFactory(this.connectionFactory);
    factoryBean.setDestinationName("noSubscribersQueue");
    factoryBean.setBeanName("noSubscribersChannel");
    factoryBean.setBeanFactory(mock(BeanFactory.class));
    factoryBean.afterPropertiesSet();
    SubscribableJmsChannel channel = (SubscribableJmsChannel) factoryBean.getObject();
    channel.afterPropertiesSet();
    AbstractMessageListenerContainer container = TestUtils.getPropertyValue(channel, "container", AbstractMessageListenerContainer.class);
    MessageListener listener = (MessageListener) container.getMessageListener();
    try {
        listener.onMessage(new StubTextMessage("Hello, world!"));
        fail("Exception expected");
    } catch (MessageDeliveryException e) {
        assertThat(e.getMessage(), containsString("Dispatcher has no subscribers for jms-channel 'noSubscribersChannel'."));
    }
}
Also used : JmsChannelFactoryBean(org.springframework.integration.jms.config.JmsChannelFactoryBean) BeanFactory(org.springframework.beans.factory.BeanFactory) MessageListener(javax.jms.MessageListener) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) AbstractMessageListenerContainer(org.springframework.jms.listener.AbstractMessageListenerContainer) Test(org.junit.Test)

Example 43 with MessageDeliveryException

use of org.springframework.messaging.MessageDeliveryException in project spring-framework by spring-projects.

the class ExecutorSubscribableChannelTests method failurePropagates.

@Test
public void failurePropagates() {
    RuntimeException ex = new RuntimeException();
    willThrow(ex).given(this.handler).handleMessage(this.message);
    MessageHandler secondHandler = mock(MessageHandler.class);
    this.channel.subscribe(this.handler);
    this.channel.subscribe(secondHandler);
    try {
        this.channel.send(message);
    } catch (MessageDeliveryException actualException) {
        assertThat(actualException.getCause()).isEqualTo(ex);
    }
    verifyNoInteractions(secondHandler);
}
Also used : MessageHandler(org.springframework.messaging.MessageHandler) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) Test(org.junit.jupiter.api.Test)

Example 44 with MessageDeliveryException

use of org.springframework.messaging.MessageDeliveryException in project spring-framework by spring-projects.

the class GenericMessagingTemplateTests method createLateReplier.

private MessageHandler createLateReplier(final CountDownLatch latch, final AtomicReference<Throwable> failure) {
    MessageHandler handler = message -> {
        try {
            Thread.sleep(500);
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(new GenericMessage<>("response"));
            failure.set(new IllegalStateException("Expected exception"));
        } catch (InterruptedException e) {
            failure.set(e);
        } catch (MessageDeliveryException ex) {
            String expected = "Reply message received but the receiving thread has exited due to a timeout";
            String actual = ex.getMessage();
            if (!expected.equals(actual)) {
                failure.set(new IllegalStateException("Unexpected error: '" + actual + "'"));
            }
        } finally {
            latch.countDown();
        }
    };
    return handler;
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SubscribableChannel(org.springframework.messaging.SubscribableChannel) ExecutorSubscribableChannel(org.springframework.messaging.support.ExecutorSubscribableChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Message(org.springframework.messaging.Message) MessageHeaderAccessor(org.springframework.messaging.support.MessageHeaderAccessor) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) MessageChannel(org.springframework.messaging.MessageChannel) MessageHeaders(org.springframework.messaging.MessageHeaders) BDDMockito.willAnswer(org.mockito.BDDMockito.willAnswer) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) List(java.util.List) MessageHandler(org.springframework.messaging.MessageHandler) GenericMessage(org.springframework.messaging.support.GenericMessage) MessageBuilder(org.springframework.messaging.support.MessageBuilder) StubMessageChannel(org.springframework.messaging.StubMessageChannel) Mockito.mock(org.mockito.Mockito.mock) GenericMessage(org.springframework.messaging.support.GenericMessage) MessageHandler(org.springframework.messaging.MessageHandler) MessageChannel(org.springframework.messaging.MessageChannel) StubMessageChannel(org.springframework.messaging.StubMessageChannel) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException)

Example 45 with MessageDeliveryException

use of org.springframework.messaging.MessageDeliveryException in project spring-framework by spring-projects.

the class StompBrokerRelayMessageHandler method handleMessageInternal.

@Override
protected void handleMessageInternal(Message<?> message) {
    String sessionId = SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
    if (!isBrokerAvailable()) {
        if (sessionId == null || SYSTEM_SESSION_ID.equals(sessionId)) {
            throw new MessageDeliveryException("Message broker not active. Consider subscribing to " + "receive BrokerAvailabilityEvent's from an ApplicationListener Spring bean.");
        }
        RelayConnectionHandler handler = this.connectionHandlers.get(sessionId);
        if (handler != null) {
            handler.sendStompErrorFrameToClient("Broker not available.");
            handler.clearConnection();
        } else {
            StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
            if (getHeaderInitializer() != null) {
                getHeaderInitializer().initHeaders(accessor);
            }
            accessor.setSessionId(sessionId);
            Principal user = SimpMessageHeaderAccessor.getUser(message.getHeaders());
            if (user != null) {
                accessor.setUser(user);
            }
            accessor.setMessage("Broker not available.");
            MessageHeaders headers = accessor.getMessageHeaders();
            getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers));
        }
        return;
    }
    StompHeaderAccessor stompAccessor;
    StompCommand command;
    MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
    if (accessor == null) {
        throw new IllegalStateException("No header accessor (not using the SimpMessagingTemplate?): " + message);
    } else if (accessor instanceof StompHeaderAccessor) {
        stompAccessor = (StompHeaderAccessor) accessor;
        command = stompAccessor.getCommand();
    } else if (accessor instanceof SimpMessageHeaderAccessor) {
        stompAccessor = StompHeaderAccessor.wrap(message);
        command = stompAccessor.getCommand();
        if (command == null) {
            command = stompAccessor.updateStompCommandAsClientMessage();
        }
    } else {
        throw new IllegalStateException("Unexpected header accessor type " + accessor.getClass() + " in " + message);
    }
    if (sessionId == null) {
        if (!SimpMessageType.MESSAGE.equals(stompAccessor.getMessageType())) {
            if (logger.isErrorEnabled()) {
                logger.error("Only STOMP SEND supported from within the server side. Ignoring " + message);
            }
            return;
        }
        sessionId = SYSTEM_SESSION_ID;
        stompAccessor.setSessionId(sessionId);
    }
    if (StompCommand.CONNECT.equals(command) || StompCommand.STOMP.equals(command)) {
        if (logger.isDebugEnabled()) {
            logger.debug(stompAccessor.getShortLogMessage(EMPTY_PAYLOAD));
        }
        stompAccessor = (stompAccessor.isMutable() ? stompAccessor : StompHeaderAccessor.wrap(message));
        stompAccessor.setLogin(this.clientLogin);
        stompAccessor.setPasscode(this.clientPasscode);
        if (getVirtualHost() != null) {
            stompAccessor.setHost(getVirtualHost());
        }
        RelayConnectionHandler handler = new RelayConnectionHandler(sessionId, stompAccessor);
        this.connectionHandlers.put(sessionId, handler);
        this.stats.incrementConnectCount();
        Assert.state(this.tcpClient != null, "No TCP client available");
        this.tcpClient.connect(handler);
    } else if (StompCommand.DISCONNECT.equals(command)) {
        RelayConnectionHandler handler = this.connectionHandlers.get(sessionId);
        if (handler == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring DISCONNECT in session " + sessionId + ". Connection already cleaned up.");
            }
            return;
        }
        this.stats.incrementDisconnectCount();
        handler.forward(message, stompAccessor);
    } else {
        RelayConnectionHandler handler = this.connectionHandlers.get(sessionId);
        if (handler == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("No TCP connection for session " + sessionId + " in " + message);
            }
            return;
        }
        String destination = stompAccessor.getDestination();
        if (command != null && command.requiresDestination() && !checkDestinationPrefix(destination)) {
            // Not a broker destination but send a heartbeat to keep the connection
            if (handler.shouldSendHeartbeatForIgnoredMessage()) {
                handler.forward(HEARTBEAT_MESSAGE, HEART_BEAT_ACCESSOR);
            }
            return;
        }
        handler.forward(message, stompAccessor);
    }
}
Also used : SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor) MessageHeaderAccessor(org.springframework.messaging.support.MessageHeaderAccessor) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) MessageHeaders(org.springframework.messaging.MessageHeaders) Principal(java.security.Principal) SimpMessageHeaderAccessor(org.springframework.messaging.simp.SimpMessageHeaderAccessor)

Aggregations

MessageDeliveryException (org.springframework.messaging.MessageDeliveryException)47 Test (org.junit.Test)19 GenericMessage (org.springframework.messaging.support.GenericMessage)17 QueueChannel (org.springframework.integration.channel.QueueChannel)13 MessagingException (org.springframework.messaging.MessagingException)10 MessageChannel (org.springframework.messaging.MessageChannel)8 Message (org.springframework.messaging.Message)6 BeanFactory (org.springframework.beans.factory.BeanFactory)5 DirectChannel (org.springframework.integration.channel.DirectChannel)5 MessageHandler (org.springframework.messaging.MessageHandler)5 MessageHeaders (org.springframework.messaging.MessageHeaders)4 PollableChannel (org.springframework.messaging.PollableChannel)4 IOException (java.io.IOException)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 SubscribableChannel (org.springframework.messaging.SubscribableChannel)3 MessageHeaderAccessor (org.springframework.messaging.support.MessageHeaderAccessor)3 FileNotFoundException (java.io.FileNotFoundException)2 Date (java.util.Date)2 List (java.util.List)2 Matchers.containsString (org.hamcrest.Matchers.containsString)2