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

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

Introduction

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

Prototype

TcpListener

Source Link

Usage

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

/**
 * Delegate TCP Client Connection factories that are used to receive
 * data need a Listener to send the messages to.
 * This applies to client factories used for outbound gateways
 * or for a pair of collaborating channel adapters.
 * <p/>/*  ww w .  j  a va 2  s .  c o  m*/
 * During initialization, if a factory detects it has no listener
 * it's listening logic (active thread) is terminated.
 * <p/>
 * The listener registered with a factory is provided to each
 * connection it creates so it can call the onMessage() method.
 * <p/>
 * This code satisfies the first requirement in that this
 * listener signals to the factory that it needs to run
 * its listening logic.
 * <p/>
 * When we wrap actual connections with FailoverTcpConnections,
 * the connection is given the wrapper as a listener, so it
 * can enhance the headers in onMessage(); the wrapper then invokes
 * the real listener supplied here, with the modified message.
 */
@Override
public void registerListener(TcpListener listener) {
    super.registerListener(listener);
    for (AbstractClientConnectionFactory factory : this.factories) {
        factory.registerListener(new TcpListener() {
            public boolean onMessage(Message<?> message) {
                throw new UnsupportedOperationException("This should never be called");
            }
        });
    }
}

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

@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, nullPublisher, 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, nullPublisher, 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);/* w ww .j  ava2  s  .  c o  m*/
    PipedOutputStream out = new PipedOutputStream(pipe);
    out.write(baos.toByteArray());
    out.close();

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

        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                inboundMessage.set(message);
            }
            return false;
        }
    };
    inboundConnection.registerListener(listener);
    inboundConnection.run();
    assertNotNull(inboundMessage.get());
    assertEquals("foo", inboundMessage.get().getPayload());
    assertEquals("baz", inboundMessage.get().getHeaders().get("bar"));
}

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//  w  w w  .  j  a  v a2  s.com
        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"));
}

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

@Test
public void testAssemblerUsesSecondaryExecutor() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    factory.setApplicationEventPublisher(nullPublisher);

    CompositeExecutor compositeExec = compositeExecutor();

    factory.setSoTimeout(1000);//  w ww .  j a  va2  s .co m
    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();
}

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

@Test
public void testAllMessagesDelivered() throws Exception {
    final int numberOfSockets = 100;
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    factory.setApplicationEventPublisher(nullPublisher);

    CompositeExecutor compositeExec = compositeExecutor();

    factory.setTaskExecutor(compositeExec);
    final CountDownLatch latch = new CountDownLatch(numberOfSockets * 4);
    factory.registerListener(new TcpListener() {

        @Override//from   w w  w . jav a2 s  .c om
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                latch.countDown();
            }
            return false;
        }

    });
    factory.start();
    TestingUtilities.waitListening(factory, null);
    int port = factory.getPort();

    Socket[] sockets = new Socket[numberOfSockets];
    for (int i = 0; i < numberOfSockets; i++) {
        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);
        sockets[i] = socket;
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write("foo1 and...".getBytes());
        sockets[i].getOutputStream().flush();
    }
    Thread.sleep(100);
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...foo2\r\nbar1 and...").getBytes());
        sockets[i].getOutputStream().flush();
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...bar2\r\n").getBytes());
        sockets[i].getOutputStream().flush();
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write("foo3 and...".getBytes());
        sockets[i].getOutputStream().flush();
    }
    Thread.sleep(100);
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...foo4\r\nbar3 and...").getBytes());
        sockets[i].getOutputStream().flush();
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...bar4\r\n").getBytes());
        sockets[i].close();
    }

    assertTrue("latch is still " + latch.getCount(), latch.await(60, TimeUnit.SECONDS));

    factory.stop();
}

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

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

        @Override/*from   w ww  .j a va  2s  .  c o m*/
        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();
    te.setCorePoolSize(3); // selector, reader, assembler
    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);

    final CountDownLatch readerLatch = new CountDownLatch(4); // 3 dataAvailable, 1 continuing
    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();
}