Example usage for org.springframework.integration.ip.util TestingUtilities waitListening

List of usage examples for org.springframework.integration.ip.util TestingUtilities waitListening

Introduction

In this page you can find the example usage for org.springframework.integration.ip.util TestingUtilities waitListening.

Prototype

public static void waitListening(AbstractInternetProtocolReceivingChannelAdapter adapter,
        @Nullable Long delayArg) throws IllegalStateException 

Source Link

Document

Wait for a server connection factory to actually start listening before starting a test.

Usage

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

@SuppressWarnings("unchecked")
@Test //INT-3722//  w  ww . j  a  v  a 2  s  .  co  m
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.connection.TcpNioConnectionTests.java

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

    CompositeExecutor compositeExec = compositeExecutor();

    factory.setSoTimeout(1000);/* w w  w . j a  v  a 2  s. c o 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 www . j av  a  2  s . c o m
        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  www . j ava2 s. co 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();
}

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

@Test
public void testOutboundChannelAdapterWithinChain() throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "TcpOutboundChannelAdapterWithinChainTests-context.xml", this.getClass());
    AbstractServerConnectionFactory scf = ctx.getBean(AbstractServerConnectionFactory.class);
    TestingUtilities.waitListening(scf, null);
    MessageChannel channelAdapterWithinChain = ctx.getBean("tcpOutboundChannelAdapterWithinChain",
            MessageChannel.class);
    PollableChannel inbound = ctx.getBean("inbound", PollableChannel.class);
    String testPayload = "Hello, world!";
    channelAdapterWithinChain.send(new GenericMessage<String>(testPayload));
    Message<?> m = inbound.receive(1000);
    assertNotNull(m);/*from w  w  w  . j a v  a  2s  . co m*/
    assertEquals(testPayload, new String((byte[]) m.getPayload()));
}

From source file:org.springframework.integration.samples.tcpclientserver.TcpServerCustomSerializerTest.java

@Before
public void setup() {
    TestingUtilities.waitListening(this.serverConnectionFactory, 10000L);
}