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

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

Introduction

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

Prototype

public TcpNioConnection(SocketChannel socketChannel, boolean server, boolean lookupHost,
        ApplicationEventPublisher applicationEventPublisher, @Nullable String connectionFactoryName) 

Source Link

Document

Constructs a TcpNetConnection for the SocketChannel.

Usage

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

private TcpConnectionSupport mockedTcpNioConnection() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    new DirectFieldAccessor(socketChannel).setPropertyValue("open", false);
    doThrow(new IOException("Foo")).when(socketChannel).write(Mockito.any(ByteBuffer.class));
    when(socketChannel.socket()).thenReturn(mock(Socket.class));
    TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, new ApplicationEventPublisher() {

        @Override//  w ww  .  ja  v a 2  s .c  om
        public void publishEvent(ApplicationEvent event) {
        }

        @Override
        public void publishEvent(Object event) {

        }

    }, "foo");
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(new ByteArrayCrLfSerializer());
    return conn;
}

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

@Test
public void testBinary() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, true, false, nullPublisher, null);
    ChannelInputStream inputStream = TestUtils.getPropertyValue(connection, "channelInputStream",
            ChannelInputStream.class);
    inputStream.write(new byte[] { (byte) 0x80 }, 1);
    assertEquals(0x80, inputStream.read());
}

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

@Test
public void testInsufficientThreads() throws Exception {
    final ExecutorService exec = Executors.newFixedThreadPool(2);
    Future<Object> future = exec.submit(() -> {
        SocketChannel channel = mock(SocketChannel.class);
        Socket socket = mock(Socket.class);
        Mockito.when(channel.socket()).thenReturn(socket);
        doAnswer(invocation -> {/*  w w  w .  j ava2s  . co  m*/
            ByteBuffer buffer = invocation.getArgument(0);
            buffer.position(1);
            return 1;
        }).when(channel).read(Mockito.any(ByteBuffer.class));
        when(socket.getReceiveBufferSize()).thenReturn(1024);
        final TcpNioConnection connection = new TcpNioConnection(channel, false, false, nullPublisher, null);
        connection.setTaskExecutor(exec);
        connection.setPipeTimeout(200);
        Method method = TcpNioConnection.class.getDeclaredMethod("doRead");
        method.setAccessible(true);
        // Nobody reading, should timeout on 6th write.
        try {
            for (int i = 0; i < 6; i++) {
                method.invoke(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw (Exception) e.getCause();
        }
        return null;
    });
    try {
        Object o = future.get(10, TimeUnit.SECONDS);
        fail("Expected exception, got " + o);
    } catch (ExecutionException e) {
        assertEquals("Timed out waiting for buffer space", e.getCause().getMessage());
    }
}

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

@Test
public void testSufficientThreads() throws Exception {
    final ExecutorService exec = Executors.newFixedThreadPool(3);
    final CountDownLatch messageLatch = new CountDownLatch(1);
    Future<Object> future = exec.submit(() -> {
        SocketChannel channel = mock(SocketChannel.class);
        Socket socket = mock(Socket.class);
        Mockito.when(channel.socket()).thenReturn(socket);
        doAnswer(invocation -> {//from   ww  w.j  a  v a 2  s.  c o  m
            ByteBuffer buffer = invocation.getArgument(0);
            buffer.position(1025);
            buffer.put((byte) '\r');
            buffer.put((byte) '\n');
            return 1027;
        }).when(channel).read(Mockito.any(ByteBuffer.class));
        final TcpNioConnection connection = new TcpNioConnection(channel, false, false, null, null);
        connection.setTaskExecutor(exec);
        connection.registerListener(message -> {
            messageLatch.countDown();
            return false;
        });
        connection.setMapper(new TcpMessageMapper());
        connection.setDeserializer(new ByteArrayCrLfSerializer());
        Method method = TcpNioConnection.class.getDeclaredMethod("doRead");
        method.setAccessible(true);
        try {
            for (int i = 0; i < 20; i++) {
                method.invoke(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw (Exception) e.getCause();
        }
        return null;
    });
    future.get(60, TimeUnit.SECONDS);
    assertTrue(messageLatch.await(10, TimeUnit.SECONDS));
}

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

@Test
public void testByteArrayRead() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    byte[] out = new byte[2];
    int n = stream.read(out);
    assertEquals(2, n);//from  www .ja  v a 2 s  .  co  m
    assertEquals("fo", new String(out));
    out = new byte[2];
    n = stream.read(out);
    assertEquals(1, n);
    assertEquals("o\u0000", new String(out));
}

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

@Test
public void testByteArrayReadMulti() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    stream.write(ByteBuffer.wrap("bar".getBytes()));
    byte[] out = new byte[6];
    int n = stream.read(out);
    assertEquals(6, n);//from   www . j av a2  s.c  om
    assertEquals("foobar", new String(out));
}

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

@Test
public void testByteArrayReadWithOffset() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    byte[] out = new byte[5];
    int n = stream.read(out, 1, 4);
    assertEquals(3, n);//from w w  w . j ava2 s  . c om
    assertEquals("\u0000foo\u0000", new String(out));
}

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

@Test
public void testByteArrayReadWithBadArgs() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    byte[] out = new byte[5];
    try {//from   w  w w . j av  a  2s .c  om
        stream.read(out, 1, 5);
        fail("Expected IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        stream.read(null, 1, 5);
        fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    assertEquals(0, stream.read(out, 0, 0));
    assertEquals(3, stream.read(out));
}

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

@Test
public void testByteArrayBlocksForZeroRead() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    final TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    final CountDownLatch latch = new CountDownLatch(1);
    final byte[] out = new byte[4];
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(new Runnable() {

        @Override/*from  www  . jav  a 2s  .  com*/
        public void run() {
            try {
                stream.read(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    });
    Thread.sleep(1000);
    assertEquals(0x00, out[0]);
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertEquals("foo\u0000", new String(out));
}

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

@Test
public void transferHeaders() throws Exception {
    Socket inSocket = mock(Socket.class);
    SocketChannel inChannel = mock(SocketChannel.class);
    when(inChannel.socket()).thenReturn(inSocket);

    TcpNioConnection inboundConnection = new TcpNioConnection(inChannel, true, false, nullPublisher, null);
    inboundConnection.setDeserializer(new MapJsonSerializer());
    MapMessageConverter inConverter = new MapMessageConverter();
    MessageConvertingTcpMessageMapper inMapper = new MessageConvertingTcpMessageMapper(inConverter);
    inboundConnection.setMapper(inMapper);
    final ByteArrayOutputStream written = new ByteArrayOutputStream();
    doAnswer(new Answer<Integer>() {

        @Override//from  w w  w.  j  a v a  2s .  c  om
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            ByteBuffer buff = invocation.getArgument(0);
            byte[] bytes = written.toByteArray();
            buff.put(bytes);
            return bytes.length;
        }
    }).when(inChannel).read(any(ByteBuffer.class));

    Socket outSocket = mock(Socket.class);
    SocketChannel outChannel = mock(SocketChannel.class);
    when(outChannel.socket()).thenReturn(outSocket);
    TcpNioConnection outboundConnection = new TcpNioConnection(outChannel, true, false, nullPublisher, null);
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            ByteBuffer buff = invocation.getArgument(0);
            byte[] bytes = new byte[buff.limit()];
            buff.get(bytes);
            written.write(bytes);
            return null;
        }
    }).when(outChannel).write(any(ByteBuffer.class));

    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);

    final AtomicReference<Message<?>> inboundMessage = new AtomicReference<Message<?>>();
    final CountDownLatch latch = new CountDownLatch(1);
    TcpListener listener = new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            inboundMessage.set(message);
            latch.countDown();
            return false;
        }
    };
    inboundConnection.registerListener(listener);
    inboundConnection.readPacket();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertNotNull(inboundMessage.get());
    assertEquals("foo", inboundMessage.get().getPayload());
    assertEquals("baz", inboundMessage.get().getHeaders().get("bar"));
}