Search in sources :

Example 51 with ErrorMessage

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

the class CachingClientConnectionFactoryTests method testEarlyReceive.

// INT-3728
@Test
public void testEarlyReceive() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AbstractClientConnectionFactory factory = new TcpNetClientConnectionFactory("", 0) {

        @Override
        protected Socket createSocket(String host, int port) throws IOException {
            Socket mock = mock(Socket.class);
            when(mock.getInputStream()).thenReturn(new ByteArrayInputStream("foo\r\n".getBytes()));
            return mock;
        }

        @Override
        public boolean isActive() {
            return true;
        }
    };
    factory.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    final CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(factory, 1);
    final AtomicReference<Message<?>> received = new AtomicReference<Message<?>>();
    cachingFactory.registerListener(message -> {
        if (!(message instanceof ErrorMessage)) {
            received.set(message);
            latch.countDown();
        }
        return false;
    });
    cachingFactory.start();
    cachingFactory.getConnection();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertNotNull(received.get());
    assertNotNull(received.get().getHeaders().get(IpHeaders.ACTUAL_CONNECTION_ID));
    cachingFactory.stop();
}
Also used : ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Socket(java.net.Socket) Test(org.junit.Test)

Example 52 with ErrorMessage

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

the class CachingClientConnectionFactoryTests method testGatewayRelease.

@SuppressWarnings("unchecked")
// INT-3722
@Test
public void testGatewayRelease() throws Exception {
    TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0);
    in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    final TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(in);
    final AtomicInteger count = new AtomicInteger(2);
    in.registerListener(message -> {
        if (!(message instanceof ErrorMessage)) {
            if (count.decrementAndGet() < 1) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            handler.handleMessage(message);
        }
        return false;
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    TestingUtilities.waitListening(in, null);
    int port = in.getPort();
    TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port);
    out.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 2);
    final TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(cache);
    QueueChannel outputChannel = new QueueChannel();
    gate.setOutputChannel(outputChannel);
    gate.setBeanFactory(mock(BeanFactory.class));
    gate.afterPropertiesSet();
    Log logger = spy(TestUtils.getPropertyValue(gate, "logger", Log.class));
    new DirectFieldAccessor(gate).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(new Answer<Void>() {

        private final CountDownLatch latch = new CountDownLatch(2);

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            String log = invocation.getArgument(0);
            if (log.startsWith("Response")) {
                new SimpleAsyncTaskExecutor().execute(() -> gate.handleMessage(new GenericMessage<>("bar")));
                // hold up the first thread until the second has added its pending reply
                latch.await(10, TimeUnit.SECONDS);
            } else if (log.startsWith("Added")) {
                latch.countDown();
            }
            return null;
        }
    }).when(logger).debug(anyString());
    gate.start();
    gate.handleMessage(new GenericMessage<String>("foo"));
    Message<byte[]> result = (Message<byte[]>) outputChannel.receive(10000);
    assertNotNull(result);
    assertEquals("foo", new String(result.getPayload()));
    result = (Message<byte[]>) outputChannel.receive(10000);
    assertNotNull(result);
    assertEquals("bar", new String(result.getPayload()));
    handler.stop();
    gate.stop();
    verify(logger, never()).error(anyString());
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) BeanFactory(org.springframework.beans.factory.BeanFactory) TcpSendingMessageHandler(org.springframework.integration.ip.tcp.TcpSendingMessageHandler) Log(org.apache.commons.logging.Log) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) CountDownLatch(java.util.concurrent.CountDownLatch) TcpOutboundGateway(org.springframework.integration.ip.tcp.TcpOutboundGateway) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Test(org.junit.Test)

Example 53 with ErrorMessage

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

the class CachingClientConnectionFactoryTests method testReuse.

@Test
public void testReuse() throws Exception {
    AbstractClientConnectionFactory factory = mock(AbstractClientConnectionFactory.class);
    when(factory.isRunning()).thenReturn(true);
    TcpConnectionSupport mockConn1 = makeMockConnection("conn1");
    TcpConnectionSupport mockConn2 = makeMockConnection("conn2");
    when(factory.getConnection()).thenReturn(mockConn1).thenReturn(mockConn2);
    CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(factory, 2);
    cachingFactory.start();
    TcpConnection conn1 = cachingFactory.getConnection();
    // INT-3652
    TcpConnectionInterceptorSupport cachedConn1 = (TcpConnectionInterceptorSupport) conn1;
    Log logger = spy(TestUtils.getPropertyValue(cachedConn1, "logger", Log.class));
    when(logger.isDebugEnabled()).thenReturn(true);
    new DirectFieldAccessor(cachedConn1).setPropertyValue("logger", logger);
    cachedConn1.onMessage(new ErrorMessage(new RuntimeException()));
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger).debug(captor.capture());
    assertThat(captor.getValue(), startsWith("Message discarded; no listener:"));
    // end INT-3652
    assertEquals("Cached:" + mockConn1.toString(), conn1.toString());
    conn1.close();
    conn1 = cachingFactory.getConnection();
    assertEquals("Cached:" + mockConn1.toString(), conn1.toString());
    TcpConnection conn2 = cachingFactory.getConnection();
    assertEquals("Cached:" + mockConn2.toString(), conn2.toString());
    conn1.close();
    conn2.close();
}
Also used : Log(org.apache.commons.logging.Log) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Test(org.junit.Test)

Example 54 with ErrorMessage

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

the class TcpNioConnectionReadTests method testReadStxEtxOverflow.

@Test
public void testReadStxEtxOverflow() throws Exception {
    ByteArrayStxEtxSerializer serializer = new ByteArrayStxEtxSerializer();
    serializer.setMaxMessageSize(1024);
    final Semaphore semaphore = new Semaphore(0);
    final List<TcpConnection> added = new ArrayList<TcpConnection>();
    final List<TcpConnection> removed = new ArrayList<TcpConnection>();
    final CountDownLatch errorMessageLetch = new CountDownLatch(1);
    final AtomicReference<Throwable> errorMessageRef = new AtomicReference<Throwable>();
    AbstractServerConnectionFactory scf = getConnectionFactory(serializer, message -> {
        if (message instanceof ErrorMessage) {
            errorMessageRef.set(((ErrorMessage) message).getPayload());
            errorMessageLetch.countDown();
        }
        return false;
    }, new TcpSender() {

        @Override
        public void addNewConnection(TcpConnection connection) {
            added.add(connection);
            semaphore.release();
        }

        @Override
        public void removeDeadConnection(TcpConnection connection) {
            removed.add(connection);
            semaphore.release();
        }
    });
    // Fire up the sender.
    CountDownLatch done = SocketTestUtils.testSendStxEtxOverflow(scf.getPort());
    whileOpen(semaphore, added);
    assertEquals(1, added.size());
    assertTrue(errorMessageLetch.await(10, TimeUnit.SECONDS));
    assertThat(errorMessageRef.get().getMessage(), anyOf(containsString("Connection is closed"), containsString("ETX not found before max message length: 1024")));
    assertTrue(semaphore.tryAcquire(10000, TimeUnit.MILLISECONDS));
    assertTrue(removed.size() > 0);
    scf.stop();
    done.countDown();
}
Also used : ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) Semaphore(java.util.concurrent.Semaphore) CountDownLatch(java.util.concurrent.CountDownLatch) ByteArrayStxEtxSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayStxEtxSerializer) ErrorMessage(org.springframework.messaging.support.ErrorMessage) LongRunningIntegrationTest(org.springframework.integration.test.support.LongRunningIntegrationTest) Test(org.junit.Test)

Example 55 with ErrorMessage

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

the class TcpNioConnectionReadTests method testReadLengthOverflow.

@Test
public void testReadLengthOverflow() throws Exception {
    ByteArrayLengthHeaderSerializer serializer = new ByteArrayLengthHeaderSerializer();
    final Semaphore semaphore = new Semaphore(0);
    final List<TcpConnection> added = new ArrayList<TcpConnection>();
    final List<TcpConnection> removed = new ArrayList<TcpConnection>();
    final CountDownLatch errorMessageLetch = new CountDownLatch(1);
    final AtomicReference<Throwable> errorMessageRef = new AtomicReference<Throwable>();
    AbstractServerConnectionFactory scf = getConnectionFactory(serializer, message -> {
        if (message instanceof ErrorMessage) {
            errorMessageRef.set(((ErrorMessage) message).getPayload());
            errorMessageLetch.countDown();
        }
        return false;
    }, new TcpSender() {

        @Override
        public void addNewConnection(TcpConnection connection) {
            added.add(connection);
            semaphore.release();
        }

        @Override
        public void removeDeadConnection(TcpConnection connection) {
            removed.add(connection);
            semaphore.release();
        }
    });
    // Fire up the sender.
    CountDownLatch done = SocketTestUtils.testSendLengthOverflow(scf.getPort());
    whileOpen(semaphore, added);
    assertEquals(1, added.size());
    assertTrue(errorMessageLetch.await(10, TimeUnit.SECONDS));
    assertThat(errorMessageRef.get().getMessage(), anyOf(containsString("Message length 2147483647 exceeds max message length: 2048"), containsString("Connection is closed")));
    assertTrue(semaphore.tryAcquire(10000, TimeUnit.MILLISECONDS));
    assertTrue(removed.size() > 0);
    scf.stop();
    done.countDown();
}
Also used : ByteArrayLengthHeaderSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) Semaphore(java.util.concurrent.Semaphore) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorMessage(org.springframework.messaging.support.ErrorMessage) LongRunningIntegrationTest(org.springframework.integration.test.support.LongRunningIntegrationTest) 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