Example usage for org.springframework.integration.channel QueueChannel QueueChannel

List of usage examples for org.springframework.integration.channel QueueChannel QueueChannel

Introduction

In this page you can find the example usage for org.springframework.integration.channel QueueChannel QueueChannel.

Prototype

public QueueChannel() 

Source Link

Document

Create a channel with "unbounded" queue capacity.

Usage

From source file:org.springframework.integration.http.inbound.HttpRequestHandlingControllerTests.java

@Test
public void testSendWithError() throws Exception {
    QueueChannel requestChannel = new QueueChannel() {
        @Override//from w  ww.j  a  va  2s . c  om
        protected boolean doSend(Message<?> message, long timeout) {
            throw new RuntimeException("Planned");
        }
    };
    HttpRequestHandlingController controller = new HttpRequestHandlingController(false);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.afterPropertiesSet();
    controller.start();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("hello".getBytes());
    request.setContentType("text/plain");
    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);
    assertEquals(1, modelAndView.getModel().size());
    Errors errors = (Errors) modelAndView.getModel().get("errors");
    assertEquals(1, errors.getErrorCount());
    ObjectError error = errors.getAllErrors().get(0);
    assertEquals(3, error.getArguments().length);
    assertTrue("Wrong message: " + error,
            ((String) error.getArguments()[1]).startsWith("failed to send Message"));
}

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

@SuppressWarnings("unchecked")
@Test //INT-3722/* w  ww  . j a  va 2  s  .c  om*/
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(1000);
                } 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")) {
                Executors.newSingleThreadScheduledExecutor()
                        .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());
}

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

@Test
public void testGoodNetSingle() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    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, 100);
                latch.countDown();/*w  w  w  .j  a  v a2s . c o m*/
                List<Socket> sockets = new ArrayList<Socket>();
                int i = 0;
                while (true) {
                    Socket socket = server.accept();
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    ois.readObject();
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject("Reply" + (i++));
                    sockets.add(socket);
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(true);
    ccf.start();
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    // check the default remote timeout
    assertEquals(Long.valueOf(10000), TestUtils.getPropertyValue(gateway, "remoteTimeout", Long.class));
    gateway.setSendTimeout(123);
    // ensure this also changed the remote timeout
    assertEquals(Long.valueOf(123), TestUtils.getPropertyValue(gateway, "remoteTimeout", Long.class));
    gateway.setRemoteTimeout(60000);
    gateway.setSendTimeout(61000);
    // ensure this did NOT change the remote timeout
    assertEquals(Long.valueOf(60000), TestUtils.getPropertyValue(gateway, "remoteTimeout", Long.class));
    gateway.setRequestTimeout(60000);
    for (int i = 100; i < 200; i++) {
        gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build());
    }
    Set<String> replies = new HashSet<String>();
    for (int i = 100; i < 200; i++) {
        Message<?> m = replyChannel.receive(10000);
        assertNotNull(m);
        replies.add((String) m.getPayload());
    }
    for (int i = 0; i < 100; i++) {
        assertTrue(replies.remove("Reply" + i));
    }
}

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

@Test
public void testGoodNetMultiplex() 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, 10);
                latch.countDown();//from w w w.j  a v  a  2 s. co m
                int i = 0;
                Socket socket = server.accept();
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    ois.readObject();
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject("Reply" + (i++));
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(false);
    ccf.start();
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    for (int i = 100; i < 110; i++) {
        gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build());
    }
    Set<String> replies = new HashSet<String>();
    for (int i = 100; i < 110; i++) {
        Message<?> m = replyChannel.receive(10000);
        assertNotNull(m);
        replies.add((String) m.getPayload());
    }
    for (int i = 0; i < 10; i++) {
        assertTrue(replies.remove("Reply" + i));
    }
    done.set(true);
    gateway.stop();
}

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

@Test
public void testGoodNetTimeout() 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  v a2 s  .co m
                int i = 0;
                Socket socket = server.accept();
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    ois.readObject();
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    Thread.sleep(1000);
                    oos.writeObject("Reply" + (i++));
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(false);
    ccf.start();
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(1);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    @SuppressWarnings("unchecked")
    Future<Integer>[] results = new Future[2];
    for (int i = 0; i < 2; i++) {
        final int j = i;
        results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
                return 0;
            }
        }));
    }
    Set<String> replies = new HashSet<String>();
    int timeouts = 0;
    for (int i = 0; i < 2; i++) {
        try {
            results[i].get();
        } catch (ExecutionException e) {
            if (timeouts > 0) {
                fail("Unexpected " + e.getMessage());
            } else {
                assertNotNull(e.getCause());
                assertTrue(e.getCause() instanceof MessageTimeoutException);
            }
            timeouts++;
            continue;
        }
        Message<?> m = replyChannel.receive(10000);
        assertNotNull(m);
        replies.add((String) m.getPayload());
    }
    if (timeouts < 1) {
        fail("Expected ExecutionException");
    }
    for (int i = 0; i < 1; i++) {
        assertTrue(replies.remove("Reply" + i));
    }
    done.set(true);
    gateway.stop();
}

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

/**
 * Sends 2 concurrent messages on a shared connection. The GW single threads
 * these requests. The first will timeout; the second should receive its
 * own response, not that for the first.
 * @throws Exception/* w  ww.  j  a  v a  2 s.co m*/
 */
private void testGoodNetGWTimeoutGuts(final int port, AbstractConnectionFactory ccf)
        throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    /*
     * The payload of the last message received by the remote side;
     * used to verify the correct response is received.
     */
    final AtomicReference<String> lastReceived = new AtomicReference<String>();
    final CountDownLatch serverLatch = new CountDownLatch(2);

    Executors.newSingleThreadExecutor().execute(new Runnable() {

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();
                int i = 0;
                while (!done.get()) {
                    Socket socket = server.accept();
                    i++;
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request);
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            if (i < 2) {
                                Thread.sleep(1000);
                            }
                            oos.writeObject(request.replace("Test", "Reply"));
                            logger.debug("Replied to " + request);
                            lastReceived.set(request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            logger.debug("error on write " + e.getClass().getSimpleName());
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(Integer.MAX_VALUE);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    gateway.setRemoteTimeout(500);
    @SuppressWarnings("unchecked")
    Future<Integer>[] results = new Future[2];
    for (int i = 0; i < 2; i++) {
        final int j = i;
        results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                // increase the timeout after the first send
                if (j > 0) {
                    gateway.setRemoteTimeout(5000);
                }
                gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
                return j;
            }
        }));
        Thread.sleep(50);
    }
    // wait until the server side has processed both requests
    assertTrue(serverLatch.await(10, TimeUnit.SECONDS));
    List<String> replies = new ArrayList<String>();
    int timeouts = 0;
    for (int i = 0; i < 2; i++) {
        try {
            int result = results[i].get();
            String reply = (String) replyChannel.receive(1000).getPayload();
            logger.debug(i + " got " + result + " " + reply);
            replies.add(reply);
        } catch (ExecutionException e) {
            if (timeouts >= 2) {
                fail("Unexpected " + e.getMessage());
            } else {
                assertNotNull(e.getCause());
                assertTrue(e.getCause() instanceof MessageTimeoutException);
            }
            timeouts++;
            continue;
        }
    }
    assertEquals("Expected exactly one ExecutionException", 1, timeouts);
    assertEquals(1, replies.size());
    assertEquals(lastReceived.get().replace("Test", "Reply"), replies.get(0));
    done.set(true);
    assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size());
    gateway.stop();
}

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

@Test
public void testCachingFailover() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor().execute(new Runnable() {

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*  w  ww  .ja v  a  2 s. co m*/
                while (!done.get()) {
                    Socket socket = server.accept();
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request);
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject("bar");
                            logger.debug("Replied to " + request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            logger.debug("error on write " + e.getClass().getSimpleName());
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));

    // Failover
    AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class);
    TcpConnectionSupport mockConn1 = makeMockConnection();
    when(factory1.getConnection()).thenReturn(mockConn1);
    doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class));

    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port);
    factory2.setSerializer(new DefaultSerializer());
    factory2.setDeserializer(new DefaultDeserializer());
    factory2.setSoTimeout(10000);
    factory2.setSingleUse(false);

    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(factory1);
    factories.add(factory2);
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);
    failoverFactory.start();

    // Cache
    CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2);
    cachingFactory.start();
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(cachingFactory);
    PollableChannel outputChannel = new QueueChannel();
    gateway.setOutputChannel(outputChannel);
    gateway.afterPropertiesSet();
    gateway.start();

    GenericMessage<String> message = new GenericMessage<String>("foo");
    gateway.handleMessage(message);
    Message<?> reply = outputChannel.receive(0);
    assertNotNull(reply);
    assertEquals("bar", reply.getPayload());
    done.set(true);
    gateway.stop();
    verify(mockConn1).send(Mockito.any(Message.class));
}

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

@Test
public void testFailoverCached() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor().execute(new Runnable() {

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*from  w  ww. ja  v a 2  s .  c om*/
                while (!done.get()) {
                    Socket socket = server.accept();
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request);
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject("bar");
                            logger.debug("Replied to " + request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            logger.debug("error on write " + e.getClass().getSimpleName());
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));

    // Cache
    AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class);
    TcpConnectionSupport mockConn1 = makeMockConnection();
    when(factory1.getConnection()).thenReturn(mockConn1);
    doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class));
    CachingClientConnectionFactory cachingFactory1 = new CachingClientConnectionFactory(factory1, 1);

    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port);
    factory2.setSerializer(new DefaultSerializer());
    factory2.setDeserializer(new DefaultDeserializer());
    factory2.setSoTimeout(10000);
    factory2.setSingleUse(false);
    CachingClientConnectionFactory cachingFactory2 = new CachingClientConnectionFactory(factory2, 1);

    // Failover
    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(cachingFactory1);
    factories.add(cachingFactory2);
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);
    failoverFactory.start();

    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(failoverFactory);
    PollableChannel outputChannel = new QueueChannel();
    gateway.setOutputChannel(outputChannel);
    gateway.afterPropertiesSet();
    gateway.start();

    GenericMessage<String> message = new GenericMessage<String>("foo");
    gateway.handleMessage(message);
    Message<?> reply = outputChannel.receive(0);
    assertNotNull(reply);
    assertEquals("bar", reply.getPayload());
    done.set(true);
    gateway.stop();
    verify(mockConn1).send(Mockito.any(Message.class));
}

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

private void testGWPropagatesSocketCloseGuts(final int port, AbstractClientConnectionFactory ccf)
        throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final AtomicReference<String> lastReceived = new AtomicReference<String>();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor().execute(new Runnable() {

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//from ww w.j ava2s.  c om
                int i = 0;
                while (!done.get()) {
                    Socket socket = server.accept();
                    i++;
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request + " closing socket");
                            socket.close();
                            lastReceived.set(request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(Integer.MAX_VALUE);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    gateway.setRemoteTimeout(5000);
    gateway.afterPropertiesSet();
    gateway.start();
    try {
        gateway.handleMessage(MessageBuilder.withPayload("Test").build());
        fail("expected failure");
    } catch (Exception e) {
        assertTrue(e.getCause() instanceof EOFException);
    }
    assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size());
    Message<?> reply = replyChannel.receive(0);
    assertNull(reply);
    done.set(true);
    ccf.getConnection();
}

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

@Test
public void testNetCrLf() 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();/*ww  w .j  a va  2s  .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 TcpNetClientConnectionFactory("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());
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply1", new String((byte[]) mOut.getPayload()));
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply2", new String((byte[]) mOut.getPayload()));
    done.set(true);
    ccf.stop();
}