Search in sources :

Example 46 with ErrorMessage

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

the class StompInboundChannelAdapterWebSocketIntegrationTests method testWebSocketStompClient.

@Test
public void testWebSocketStompClient() throws Exception {
    Message<?> eventMessage = this.stompEvents.receive(10000);
    assertNotNull(eventMessage);
    assertThat(eventMessage.getPayload(), instanceOf(StompSessionConnectedEvent.class));
    Message<?> receive = this.stompEvents.receive(10000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(StompReceiptEvent.class));
    StompReceiptEvent stompReceiptEvent = (StompReceiptEvent) receive.getPayload();
    assertEquals(StompCommand.SUBSCRIBE, stompReceiptEvent.getStompCommand());
    assertEquals("/topic/myTopic", stompReceiptEvent.getDestination());
    waitForSubscribe("/topic/myTopic");
    SimpMessagingTemplate messagingTemplate = this.serverContext.getBean("brokerMessagingTemplate", SimpMessagingTemplate.class);
    StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.create(StompCommand.MESSAGE);
    stompHeaderAccessor.setContentType(MediaType.APPLICATION_JSON);
    stompHeaderAccessor.updateStompCommandAsServerMessage();
    stompHeaderAccessor.setLeaveMutable(true);
    messagingTemplate.send("/topic/myTopic", MessageBuilder.createMessage("{\"foo\": \"bar\"}".getBytes(), stompHeaderAccessor.getMessageHeaders()));
    receive = this.stompInputChannel.receive(10000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(Map.class));
    @SuppressWarnings("unchecked") Map<String, String> payload = (Map<String, String>) receive.getPayload();
    String foo = payload.get("foo");
    assertNotNull(foo);
    assertEquals("bar", foo);
    this.stompInboundChannelAdapter.removeDestination("/topic/myTopic");
    waitForUnsubscribe("/topic/myTopic");
    messagingTemplate.convertAndSend("/topic/myTopic", "foo");
    receive = this.errorChannel.receive(100);
    assertNull(receive);
    this.stompInboundChannelAdapter.addDestination("/topic/myTopic");
    receive = this.stompEvents.receive(10000);
    assertNotNull(receive);
    waitForSubscribe("/topic/myTopic");
    messagingTemplate.convertAndSend("/topic/myTopic", "foo");
    receive = this.errorChannel.receive(10000);
    assertNotNull(receive);
    assertThat(receive, instanceOf(ErrorMessage.class));
    ErrorMessage errorMessage = (ErrorMessage) receive;
    Throwable throwable = errorMessage.getPayload();
    assertThat(throwable, instanceOf(MessageHandlingException.class));
    assertThat(throwable.getCause(), instanceOf(MessageConversionException.class));
    assertThat(throwable.getMessage(), containsString("No suitable converter for payload type [interface java.util.Map]"));
    this.serverContext.close();
    eventMessage = this.stompEvents.receive(10000);
    assertNotNull(eventMessage);
    assertThat(eventMessage.getPayload(), instanceOf(StompConnectionFailedEvent.class));
    this.serverContext.refresh();
    do {
        eventMessage = this.stompEvents.receive(10000);
        assertNotNull(eventMessage);
    } while (!(eventMessage.getPayload() instanceof StompSessionConnectedEvent));
    waitForSubscribe("/topic/myTopic");
    messagingTemplate = this.serverContext.getBean("brokerMessagingTemplate", SimpMessagingTemplate.class);
    messagingTemplate.convertAndSend("/topic/myTopic", "foo");
    receive = this.errorChannel.receive(10000);
    assertNotNull(receive);
    assertEquals(0, ((QueueChannel) this.errorChannel).getQueueSize());
}
Also used : SimpMessagingTemplate(org.springframework.messaging.simp.SimpMessagingTemplate) MessageConversionException(org.springframework.messaging.converter.MessageConversionException) StompHeaderAccessor(org.springframework.messaging.simp.stomp.StompHeaderAccessor) Matchers.containsString(org.hamcrest.Matchers.containsString) MessageHandlingException(org.springframework.messaging.MessageHandlingException) StompReceiptEvent(org.springframework.integration.stomp.event.StompReceiptEvent) StompConnectionFailedEvent(org.springframework.integration.stomp.event.StompConnectionFailedEvent) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) StompSessionConnectedEvent(org.springframework.integration.stomp.event.StompSessionConnectedEvent) Test(org.junit.Test)

Example 47 with ErrorMessage

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

the class WebFluxRequestExecutingMessageHandlerTests method testReactiveErrorOneWay.

@Test
public void testReactiveErrorOneWay() {
    ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return Mono.defer(response::setComplete);
    });
    WebClient webClient = WebClient.builder().clientConnector(httpConnector).build();
    String destinationUri = "http://www.springsource.org/spring-integration";
    WebFluxRequestExecutingMessageHandler reactiveHandler = new WebFluxRequestExecutingMessageHandler(destinationUri, webClient);
    reactiveHandler.setExpectReply(false);
    QueueChannel errorChannel = new QueueChannel();
    reactiveHandler.handleMessage(MessageBuilder.withPayload("hello, world").setErrorChannel(errorChannel).build());
    Message<?> errorMessage = errorChannel.receive(10000);
    assertNotNull(errorMessage);
    assertThat(errorMessage, instanceOf(ErrorMessage.class));
    Throwable throwable = (Throwable) errorMessage.getPayload();
    assertThat(throwable.getMessage(), containsString("401 Unauthorized"));
}
Also used : ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) QueueChannel(org.springframework.integration.channel.QueueChannel) Matchers.containsString(org.hamcrest.Matchers.containsString) ErrorMessage(org.springframework.messaging.support.ErrorMessage) WebClient(org.springframework.web.reactive.function.client.WebClient) HttpHandlerConnector(org.springframework.test.web.reactive.server.HttpHandlerConnector) Test(org.junit.Test)

Example 48 with ErrorMessage

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

the class TcpNetConnectionTests method transferHeaders.

@Test
public void transferHeaders() throws Exception {
    Socket inSocket = mock(Socket.class);
    PipedInputStream pipe = new PipedInputStream();
    when(inSocket.getInputStream()).thenReturn(pipe);
    TcpConnectionSupport inboundConnection = new TcpNetConnection(inSocket, true, false, e -> {
    }, null);
    inboundConnection.setDeserializer(new MapJsonSerializer());
    MapMessageConverter inConverter = new MapMessageConverter();
    MessageConvertingTcpMessageMapper inMapper = new MessageConvertingTcpMessageMapper(inConverter);
    inboundConnection.setMapper(inMapper);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Socket outSocket = mock(Socket.class);
    TcpNetConnection outboundConnection = new TcpNetConnection(outSocket, true, false, e -> {
    }, null);
    when(outSocket.getOutputStream()).thenReturn(baos);
    MapMessageConverter outConverter = new MapMessageConverter();
    outConverter.setHeaderNames("bar");
    MessageConvertingTcpMessageMapper outMapper = new MessageConvertingTcpMessageMapper(outConverter);
    outboundConnection.setMapper(outMapper);
    outboundConnection.setSerializer(new MapJsonSerializer());
    Message<String> message = MessageBuilder.withPayload("foo").setHeader("bar", "baz").build();
    outboundConnection.send(message);
    PipedOutputStream out = new PipedOutputStream(pipe);
    out.write(baos.toByteArray());
    out.close();
    final AtomicReference<Message<?>> inboundMessage = new AtomicReference<Message<?>>();
    TcpListener listener = message1 -> {
        if (!(message1 instanceof ErrorMessage)) {
            inboundMessage.set(message1);
        }
        return false;
    };
    inboundConnection.registerListener(listener);
    inboundConnection.run();
    assertNotNull(inboundMessage.get());
    assertEquals("foo", inboundMessage.get().getPayload());
    assertEquals("baz", inboundMessage.get().getHeaders().get("bar"));
}
Also used : Socket(java.net.Socket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) MessageBuilder(org.springframework.integration.support.MessageBuilder) SocketChannel(java.nio.channels.SocketChannel) PipedInputStream(java.io.PipedInputStream) Mockito.doAnswer(org.mockito.Mockito.doAnswer) MapJsonSerializer(org.springframework.integration.ip.tcp.serializer.MapJsonSerializer) Message(org.springframework.messaging.Message) MapMessageConverter(org.springframework.integration.support.converter.MapMessageConverter) ChannelInputStream(org.springframework.integration.ip.tcp.connection.TcpNioConnection.ChannelInputStream) ByteArrayStxEtxSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayStxEtxSerializer) Assert.assertNotNull(org.junit.Assert.assertNotNull) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) PipedOutputStream(java.io.PipedOutputStream) Mockito(org.mockito.Mockito) Log(org.apache.commons.logging.Log) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) InputStream(java.io.InputStream) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) PipedOutputStream(java.io.PipedOutputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) PipedInputStream(java.io.PipedInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MapMessageConverter(org.springframework.integration.support.converter.MapMessageConverter) MapJsonSerializer(org.springframework.integration.ip.tcp.serializer.MapJsonSerializer) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Socket(java.net.Socket) Test(org.junit.Test)

Example 49 with ErrorMessage

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

the class TcpNioConnectionTests method testAssemblerUsesSecondaryExecutor.

@Test
public void testAssemblerUsesSecondaryExecutor() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    factory.setApplicationEventPublisher(nullPublisher);
    CompositeExecutor compositeExec = compositeExecutor();
    factory.setSoTimeout(1000);
    factory.setTaskExecutor(compositeExec);
    final AtomicReference<String> threadName = new AtomicReference<String>();
    final CountDownLatch latch = new CountDownLatch(1);
    factory.registerListener(new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                threadName.set(Thread.currentThread().getName());
                latch.countDown();
            }
            return false;
        }
    });
    factory.start();
    TestingUtilities.waitListening(factory, null);
    int port = factory.getPort();
    Socket socket = null;
    int n = 0;
    while (n++ < 100) {
        try {
            socket = SocketFactory.getDefault().createSocket("localhost", port);
            break;
        } catch (ConnectException e) {
        }
        Thread.sleep(100);
    }
    assertTrue("Could not open socket to localhost:" + port, n < 100);
    socket.getOutputStream().write("foo\r\n".getBytes());
    socket.close();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertThat(threadName.get(), containsString("assembler"));
    factory.stop();
    cleanupCompositeExecutor(compositeExec);
}
Also used : CompositeExecutor(org.springframework.integration.util.CompositeExecutor) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) ConnectException(java.net.ConnectException) Test(org.junit.Test)

Example 50 with ErrorMessage

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

the class TcpNioConnectionTests method int3453RaceTest.

@Test
public void int3453RaceTest() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    final CountDownLatch connectionLatch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            if (event instanceof TcpConnectionOpenEvent) {
                connectionLatch.countDown();
            }
        }

        @Override
        public void publishEvent(Object event) {
        }
    });
    final CountDownLatch assemblerLatch = new CountDownLatch(1);
    final AtomicReference<Thread> assembler = new AtomicReference<Thread>();
    factory.registerListener(new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                assembler.set(Thread.currentThread());
                assemblerLatch.countDown();
            }
            return false;
        }
    });
    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    // selector, reader, assembler
    te.setCorePoolSize(3);
    te.setMaxPoolSize(3);
    te.setQueueCapacity(0);
    te.initialize();
    factory.setTaskExecutor(te);
    factory.start();
    TestingUtilities.waitListening(factory, 10000L);
    int port = factory.getPort();
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    assertTrue(connectionLatch.await(10, TimeUnit.SECONDS));
    TcpNioConnection connection = (TcpNioConnection) TestUtils.getPropertyValue(factory, "connections", Map.class).values().iterator().next();
    Log logger = spy(TestUtils.getPropertyValue(connection, "logger", Log.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(connection);
    dfa.setPropertyValue("logger", logger);
    ChannelInputStream cis = spy(TestUtils.getPropertyValue(connection, "channelInputStream", ChannelInputStream.class));
    dfa.setPropertyValue("channelInputStream", cis);
    // 3 dataAvailable, 1 continuing
    final CountDownLatch readerLatch = new CountDownLatch(4);
    final CountDownLatch readerFinishedLatch = new CountDownLatch(1);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            // delay the reader thread resetting writingToPipe
            readerLatch.await(10, TimeUnit.SECONDS);
            Thread.sleep(100);
            readerFinishedLatch.countDown();
            return null;
        }
    }).when(cis).write(any(ByteBuffer.class));
    doReturn(true).when(logger).isTraceEnabled();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("checking data avail"));
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("Nio assembler continuing"));
    socket.getOutputStream().write("foo\r\n".getBytes());
    assertTrue(assemblerLatch.await(10, TimeUnit.SECONDS));
    assertTrue(readerFinishedLatch.await(10, TimeUnit.SECONDS));
    StackTraceElement[] stackTrace = assembler.get().getStackTrace();
    assertThat(Arrays.asList(stackTrace).toString(), not(containsString("ChannelInputStream.getNextBuffer")));
    socket.close();
    factory.stop();
    te.shutdown();
}
Also used : ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ChannelInputStream(org.springframework.integration.ip.tcp.connection.TcpNioConnection.ChannelInputStream) Log(org.apache.commons.logging.Log) ApplicationEvent(org.springframework.context.ApplicationEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

ErrorMessage (org.springframework.messaging.support.ErrorMessage)59 Test (org.junit.Test)47 CountDownLatch (java.util.concurrent.CountDownLatch)17 GenericMessage (org.springframework.messaging.support.GenericMessage)17 MessagingException (org.springframework.messaging.MessagingException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 Message (org.springframework.messaging.Message)12 QueueChannel (org.springframework.integration.channel.QueueChannel)11 MessageHandlingException (org.springframework.messaging.MessageHandlingException)11 Socket (java.net.Socket)9 ArrayList (java.util.ArrayList)7 LongRunningIntegrationTest (org.springframework.integration.test.support.LongRunningIntegrationTest)7 Semaphore (java.util.concurrent.Semaphore)6 Log (org.apache.commons.logging.Log)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)6 BeanFactory (org.springframework.beans.factory.BeanFactory)5 MessageDeliveryException (org.springframework.messaging.MessageDeliveryException)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 ServerSocket (java.net.ServerSocket)3