List of usage examples for org.springframework.integration.ip.tcp TcpOutboundGateway start
@Override public void start()
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@SuppressWarnings("unchecked") @Test //INT-3722/*from w ww.jav a2 s. c o 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.ConnectionEventTests.java
@Test public void testOutboundGatewayNoConnectionEvents() { TcpOutboundGateway gw = new TcpOutboundGateway(); AbstractClientConnectionFactory ccf = new AbstractClientConnectionFactory("localhost", 0) { };/*from www .jav a 2 s . c om*/ final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>(); ccf.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override public void publishEvent(Object event) { } @Override public void publishEvent(ApplicationEvent event) { theEvent.set(event); } }); gw.setConnectionFactory(ccf); DirectChannel requestChannel = new DirectChannel(); requestChannel .subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message)); gw.start(); Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar") .build(); gw.onMessage(message); assertNotNull(theEvent.get()); TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get(); assertEquals("bar", event.getConnectionId()); MessagingException messagingException = (MessagingException) event.getCause(); assertSame(message, messagingException.getFailedMessage()); assertEquals("Cannot correlate response - no pending reply for bar", messagingException.getMessage()); message = new GenericMessage<String>("foo"); gw.onMessage(message); assertNotNull(theEvent.get()); event = (TcpConnectionFailedCorrelationEvent) theEvent.get(); assertNull(event.getConnectionId()); messagingException = (MessagingException) event.getCause(); assertSame(message, messagingException.getFailedMessage()); assertEquals("Cannot correlate response - no connection id", messagingException.getMessage()); }
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();/*from www . jav a 2 s . c o 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();/*w w w . j a va2 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 a v a2 s . 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(); }