Example usage for org.springframework.integration.ip.tcp TcpSendingMessageHandler setConnectionFactory

List of usage examples for org.springframework.integration.ip.tcp TcpSendingMessageHandler setConnectionFactory

Introduction

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

Prototype

public void setConnectionFactory(AbstractConnectionFactory connectionFactory) 

Source Link

Document

Sets the client or server connection factory; for this (an outbound adapter), if the factory is a server connection factory, the sockets are owned by a receiving channel adapter and this adapter is used to send replies.

Usage

From source file:ru.jts_dev.authserver.config.AuthIntegrationConfig.java

/**
 * Endpoint for output messages./*from w  ww  . j  a v  a  2 s  . com*/
 * Receives message from tcpOutputChannel, and send it to client with corresponding {@link IpHeaders#CONNECTION_ID}
 *
 * @param connectionFactory - server factory bean
 * @return - tcp message handler bean
 */
@Bean
@ServiceActivator(inputChannel = "tcpOutChannel")
public TcpSendingMessageHandler tcpOut(AbstractServerConnectionFactory connectionFactory) {
    TcpSendingMessageHandler gateway = new TcpSendingMessageHandler();
    gateway.setConnectionFactory(connectionFactory);

    return gateway;
}

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

@SuppressWarnings("unchecked")
@Test //INT-3722//from w  w w.ja  va2  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.connection.ConnectionEventTests.java

@Test
public void testOutboundChannelAdapterNoConnectionEvents() {
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override/*from  ww w  . ja v a 2 s .  c  o m*/
        public void run() {
        }
    };
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    scf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }

    });
    handler.setConnectionFactory(scf);
    handler.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    try {
        handler.handleMessage(message);
        fail("expected exception");
    } catch (MessageHandlingException e) {
        assertThat(e.getMessage(), Matchers.containsString("Unable to find outbound socket"));
    }
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
}

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();/*w ww .j a  v  a  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 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();
}

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

@Test
public void testNetCrLfClientMode() 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  v a 2  s  .  c om
                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(Integer.MAX_VALUE);
    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.setClientMode(true);
    handler.setRetryInterval(10000);
    handler.afterPropertiesSet();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setPoolSize(1);
    taskScheduler.initialize();
    handler.setTaskScheduler(taskScheduler);
    handler.start();
    adapter.start();
    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);
    handler.stop();
    handler.start();
    handler.stop();
}

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();//from www. ja v a  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 testNetStxEtx() 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  ava 2  s  . co  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 TcpNetClientConnectionFactory("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());
    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();
}

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   ww w.j  a v  a  2  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 testNetLength() 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  ww . j av a 2s  . com*/
                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 TcpNetClientConnectionFactory("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());
    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();
}

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 2s  . c o 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();
}