Example usage for org.springframework.integration.ip.tcp.connection TcpConnection send

List of usage examples for org.springframework.integration.ip.tcp.connection TcpConnection send

Introduction

In this page you can find the example usage for org.springframework.integration.ip.tcp.connection TcpConnection send.

Prototype

void send(Message<?> message);

Source Link

Document

Converts and sends the message.

Usage

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

private void doTestCloseOnSendError(TcpConnection conn1, TcpConnection conn2,
        CachingClientConnectionFactory cccf) throws Exception {
    TcpConnection cached1 = cccf.getConnection();
    try {/*from   ww  w.j  av  a 2  s .  co  m*/
        cached1.send(new GenericMessage<String>("foo"));
        fail("Expected IOException");
    } catch (IOException e) {
        assertEquals("Foo", e.getMessage());
    }
    // Before INT-3163 this failed with a timeout - connection not returned to pool after failure on send()
    TcpConnection cached2 = cccf.getConnection();
    assertTrue(cached1.getConnectionId().contains(conn1.getConnectionId()));
    assertTrue(cached2.getConnectionId().contains(conn2.getConnectionId()));
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

@Test
public void testCachedFailover() throws Exception {
    // Failover//w ww  .  ja v a  2 s.co  m
    AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class);
    AbstractClientConnectionFactory factory2 = mock(AbstractClientConnectionFactory.class);
    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(factory1);
    factories.add(factory2);
    TcpConnectionSupport mockConn1 = makeMockConnection();
    TcpConnectionSupport mockConn2 = makeMockConnection();
    when(factory1.getConnection()).thenReturn(mockConn1);
    when(factory2.getConnection()).thenReturn(mockConn2);
    when(factory1.isActive()).thenReturn(true);
    when(factory2.isActive()).thenReturn(true);
    doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class));
    doAnswer(invocation -> null).when(mockConn2).send(Mockito.any(Message.class));
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);
    failoverFactory.start();

    // Cache
    CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2);
    cachingFactory.start();
    TcpConnection conn1 = cachingFactory.getConnection();
    GenericMessage<String> message = new GenericMessage<String>("foo");
    conn1 = cachingFactory.getConnection();
    conn1.send(message);
    Mockito.verify(mockConn2).send(message);
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

@Test
public void testCachedFailoverRealClose() throws Exception {
    TcpNetServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0);
    server1.setBeanName("server1");
    final CountDownLatch latch1 = new CountDownLatch(3);
    server1.registerListener(message -> {
        latch1.countDown();//  w w w  . j a v a 2 s. c  o  m
        return false;
    });
    server1.start();
    TestingUtilities.waitListening(server1, 10000L);
    int port1 = server1.getPort();
    TcpNetServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0);
    server1.setBeanName("server2");
    final CountDownLatch latch2 = new CountDownLatch(2);
    server2.registerListener(message -> {
        latch2.countDown();
        return false;
    });
    server2.start();
    TestingUtilities.waitListening(server2, 10000L);
    int port2 = server2.getPort();
    // Failover
    AbstractClientConnectionFactory factory1 = new TcpNetClientConnectionFactory("localhost", port1);
    factory1.setBeanName("client1");
    factory1.registerListener(message -> false);
    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2);
    factory2.setBeanName("client2");
    factory2.registerListener(message -> false);
    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(factory1);
    factories.add(factory2);
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);

    // Cache
    CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2);
    cachingFactory.start();
    TcpConnection conn1 = cachingFactory.getConnection();
    GenericMessage<String> message = new GenericMessage<String>("foo");
    conn1.send(message);
    conn1.close();
    TcpConnection conn2 = cachingFactory.getConnection();
    assertSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(),
            ((TcpConnectionInterceptorSupport) conn2).getTheConnection());
    conn2.send(message);
    conn1 = cachingFactory.getConnection();
    assertNotSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(),
            ((TcpConnectionInterceptorSupport) conn2).getTheConnection());
    conn1.send(message);
    conn1.close();
    conn2.close();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    server1.stop();
    TestingUtilities.waitStopListening(server1, 10000L);
    TestingUtilities.waitUntilFactoryHasThisNumberOfConnections(factory1, 0);
    conn1 = cachingFactory.getConnection();
    conn2 = cachingFactory.getConnection();
    conn1.send(message);
    conn2.send(message);
    conn1.close();
    conn2.close();
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    SimplePool<?> pool = TestUtils.getPropertyValue(cachingFactory, "pool", SimplePool.class);
    assertEquals(2, pool.getIdleCount());
    server2.stop();
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

@Test
public void testCachedFailoverRealBadHost() throws Exception {
    TcpNetServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0);
    server1.setBeanName("server1");
    final CountDownLatch latch1 = new CountDownLatch(3);
    server1.registerListener(message -> {
        latch1.countDown();//from  w w w  . ja  v  a 2 s  . c o m
        return false;
    });
    server1.start();
    TestingUtilities.waitListening(server1, 10000L);
    int port1 = server1.getPort();
    TcpNetServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0);
    server1.setBeanName("server2");
    final CountDownLatch latch2 = new CountDownLatch(2);
    server2.registerListener(message -> {
        latch2.countDown();
        return false;
    });
    server2.start();
    TestingUtilities.waitListening(server2, 10000L);
    int port2 = server2.getPort();
    // Failover
    AbstractClientConnectionFactory factory1 = new TcpNetClientConnectionFactory("junkjunk", port1);
    factory1.setBeanName("client1");
    factory1.registerListener(message -> false);
    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2);
    factory2.setBeanName("client2");
    factory2.registerListener(message -> false);
    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(factory1);
    factories.add(factory2);
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);

    // Cache
    CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2);
    cachingFactory.start();
    TcpConnection conn1 = cachingFactory.getConnection();
    GenericMessage<String> message = new GenericMessage<String>("foo");
    conn1.send(message);
    conn1.close();
    TcpConnection conn2 = cachingFactory.getConnection();
    assertSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(),
            ((TcpConnectionInterceptorSupport) conn2).getTheConnection());
    conn2.send(message);
    conn1 = cachingFactory.getConnection();
    assertNotSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(),
            ((TcpConnectionInterceptorSupport) conn2).getTheConnection());
    conn1.send(message);
    conn1.close();
    conn2.close();
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertEquals(3, latch1.getCount());
    server1.stop();
    server2.stop();
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testWriteTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {/*from w ww . java 2  s. co m*/
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
            serverSocket.set(server);
            latch.countDown();
            Socket s = server.accept();
            // block so we fill the buffer
            done.await(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost",
            serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setSoTimeout(1000);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        connection.send(MessageBuilder.withPayload(new byte[1000000]).build());
    } catch (Exception e) {
        assertTrue(
                "Expected SocketTimeoutException, got " + e.getClass().getSimpleName() + ":" + e.getMessage(),
                e instanceof SocketTimeoutException);
    }
    done.countDown();
    serverSocket.get().close();
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testReadTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {/*from www.j  a  v  a 2 s.c om*/
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
            serverSocket.set(server);
            latch.countDown();
            Socket socket = server.accept();
            byte[] b = new byte[6];
            readFully(socket.getInputStream(), b);
            // block to cause timeout on read.
            done.await(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost",
            serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setSoTimeout(1000);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        connection.send(MessageBuilder.withPayload("Test").build());
        int n = 0;
        while (connection.isOpen()) {
            Thread.sleep(100);
            if (n++ > 200) {
                break;
            }
        }
        assertTrue(!connection.isOpen());
    } catch (Exception e) {
        fail("Unexpected exception " + e);
    }
    done.countDown();
    serverSocket.get().close();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandler.java

/**
 * Writes the message payload to the underlying socket, using the specified
 * message format. /*from w w w. jav  a  2  s.  com*/
 * @see org.springframework.integration.core.MessageHandler#handleMessage(org.springframework.integration.Message)
 */
public void handleMessageInternal(final Message<?> message)
        throws MessageRejectedException, MessageHandlingException, MessageDeliveryException {
    if (this.serverConnectionFactory != null) {
        // We don't own the connection
        Object connectionId = message.getHeaders().get(IpHeaders.CONNECTION_ID);
        TcpConnection connection = connections.get(connectionId);
        if (connection != null) {
            try {
                connection.send(message);
            } catch (Exception e) {
                logger.error("Error sending message", e);
                connection.close();
            }
        } else {
            logger.error("Unable to find incoming socket for " + message);
        }
        return;
    }

    try {
        doWrite(message);
    } catch (MessageMappingException e) {
        // retry - socket may have closed
        if (e.getCause() instanceof IOException) {
            logger.debug("Fail on first write attempt", e);
            doWrite(message);
        } else {
            throw e;
        }
    }
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandler.java

/**
 * Method that actually does the write./*from   w  w  w  . ja  v  a2 s  . co m*/
 * @param message The message to write.
 */
protected void doWrite(Message<?> message) {
    try {
        TcpConnection connection = getConnection();
        if (connection == null) {
            throw new MessageMappingException(message, "Failed to create connection");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Got Connection " + connection.getConnectionId());
        }
        connection.send(message);
    } catch (Exception e) {
        String connectionId = null;
        if (this.connection != null) {
            connectionId = this.connection.getConnectionId();
        }
        this.connection = null;
        if (e instanceof MessageMappingException) {
            throw (MessageMappingException) e;
        }
        throw new MessageMappingException(message, "Failed to map message using " + connectionId, e);
    }
}