Example usage for org.springframework.integration.ip.tcp.connection TcpNioClientConnectionFactory TcpNioClientConnectionFactory

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

Introduction

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

Prototype

public TcpNioClientConnectionFactory(String host, int port) 

Source Link

Document

Creates a TcpNioClientConnectionFactory for connections to the host and port.

Usage

From source file:com.acmemotors.Main.java

@Bean
public TcpNioClientConnectionFactory connectionFactory(@Value("${dongleHost:192.168.0.10}") String dongleHost,
        @Value("${donglePort:35000}") int donglePort) {
    TcpNioClientConnectionFactory factory;

    factory = new TcpNioClientConnectionFactory(dongleHost, donglePort);

    OBD2Serializer odb2Serializer = new OBD2Serializer();
    factory.setSerializer(odb2Serializer);
    factory.setDeserializer(odb2Serializer);
    factory.setSingleUse(false);/*from  w  w  w . ja  v  a 2  s  .  c o m*/
    factory.afterPropertiesSet();

    return factory;
}

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

@Test
public void testCloseOnTimeoutNio() throws Exception {
    TestingUtilities.waitListening(serverCf, null);
    testCloseOnTimeoutGuts(new TcpNioClientConnectionFactory("localhost", serverCf.getPort()));
}

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 {/*ww  w . j  a v  a2 s .  c  o 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 {//  w ww.  j  a v a  2 s.c o  m
            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.connection.TcpNioConnectionTests.java

@Test
public void testMemoryLeak() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {//ww  w.  j ava2 s  .c o m
            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);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost",
            serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setNioHarvestInterval(100);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        Map<SocketChannel, TcpNioConnection> connections = factory.getConnections();
        assertEquals(1, connections.size());
        connection.close();
        assertTrue(!connection.isOpen());
        TestUtils.getPropertyValue(factory, "selector", Selector.class).wakeup();
        int n = 0;
        while (connections.size() > 0) {
            Thread.sleep(100);
            if (n++ > 100) {
                break;
            }
        }
        assertEquals(0, connections.size());
    } catch (Exception e) {
        e.printStackTrace();
        fail("Unexpected exception " + e);
    }
    factory.stop();
    serverSocket.get().close();
}

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

@Test
public void testCleanup() throws Exception {
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", 0);
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setNioHarvestInterval(100);//from   ww w  .  j a  v  a  2  s  .  co  m
    Map<SocketChannel, TcpNioConnection> connections = new HashMap<SocketChannel, TcpNioConnection>();
    SocketChannel chan1 = mock(SocketChannel.class);
    SocketChannel chan2 = mock(SocketChannel.class);
    SocketChannel chan3 = mock(SocketChannel.class);
    TcpNioConnection conn1 = mock(TcpNioConnection.class);
    TcpNioConnection conn2 = mock(TcpNioConnection.class);
    TcpNioConnection conn3 = mock(TcpNioConnection.class);
    connections.put(chan1, conn1);
    connections.put(chan2, conn2);
    connections.put(chan3, conn3);
    final List<Field> fields = new ArrayList<Field>();
    ReflectionUtils.doWithFields(SocketChannel.class, field -> {
        field.setAccessible(true);
        fields.add(field);
    }, field -> field.getName().equals("open"));
    Field field = fields.get(0);
    // Can't use Mockito because isOpen() is final
    ReflectionUtils.setField(field, chan1, true);
    ReflectionUtils.setField(field, chan2, true);
    ReflectionUtils.setField(field, chan3, true);
    Selector selector = mock(Selector.class);
    HashSet<SelectionKey> keys = new HashSet<SelectionKey>();
    when(selector.selectedKeys()).thenReturn(keys);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(3, connections.size()); // all open

    ReflectionUtils.setField(field, chan1, false);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(3, connections.size()); // interval didn't pass
    Thread.sleep(110);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(2, connections.size()); // first is closed

    ReflectionUtils.setField(field, chan2, false);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(2, connections.size()); // interval didn't pass
    Thread.sleep(110);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(1, connections.size()); // second is closed

    ReflectionUtils.setField(field, chan3, false);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(1, connections.size()); // interval didn't pass
    Thread.sleep(110);
    factory.processNioSelections(1, selector, null, connections);
    assertEquals(0, connections.size()); // third is closed

    assertEquals(0, TestUtils.getPropertyValue(factory, "connections", Map.class).size());
}

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

@Test
public void testNioGWPropagatesSocketClose() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    AbstractClientConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);/*from w  w  w.j av  a  2s  . co m*/
    ccf.setSingleUse(false);
    ccf.start();
    testGWPropagatesSocketCloseGuts(port, ccf);
}

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

@Test
public void testNioCrLf() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*w w w .j a va  2 s  .  c  o  m*/
                Socket socket = server.accept();
                int i = 0;
                while (true) {
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + (++i) + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    Set<String> results = new HashSet<String>();
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    results.add(new String((byte[]) mOut.getPayload()));
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    results.add(new String((byte[]) mOut.getPayload()));
    assertTrue(results.remove("Reply1"));
    assertTrue(results.remove("Reply2"));
    done.set(true);
    ccf.stop();
}

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

@Test
public void testNioStxEtx() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//from w w w  .  java2 s.  c o  m
                Socket socket = server.accept();
                int i = 0;
                while (true) {
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    b = ("\u0002Reply" + (++i) + "\u0003").getBytes();
                    socket.getOutputStream().write(b);
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayStxEtxSerializer serializer = new ByteArrayStxEtxSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    Set<String> results = new HashSet<String>();
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    results.add(new String((byte[]) mOut.getPayload()));
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    results.add(new String((byte[]) mOut.getPayload()));
    assertTrue(results.remove("Reply1"));
    assertTrue(results.remove("Reply2"));
    done.set(true);
    ccf.stop();
}

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

@Test
public void testNioLength() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*www  .j  a  v a  2  s . co  m*/
                Socket socket = server.accept();
                int i = 0;
                while (true) {
                    byte[] b = new byte[8];
                    readFully(socket.getInputStream(), b);
                    if (!"\u0000\u0000\u0000\u0004Test".equals(new String(b))) {
                        throw new RuntimeException("Bad Data");
                    }
                    b = ("\u0000\u0000\u0000\u0006Reply" + (++i)).getBytes();
                    socket.getOutputStream().write(b);
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayLengthHeaderSerializer serializer = new ByteArrayLengthHeaderSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    Set<String> results = new HashSet<String>();
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    results.add(new String((byte[]) mOut.getPayload()));
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    results.add(new String((byte[]) mOut.getPayload()));
    assertTrue(results.remove("Reply1"));
    assertTrue(results.remove("Reply2"));
    done.set(true);
    ccf.stop();
}