List of usage examples for org.springframework.integration.ip.tcp.connection TcpNetClientConnectionFactory TcpNetClientConnectionFactory
public TcpNetClientConnectionFactory(String host, int port)
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test public void testCloseOnTimeoutNet() throws Exception { TestingUtilities.waitListening(serverCf, null); testCloseOnTimeoutGuts(new TcpNetClientConnectionFactory("localhost", serverCf.getPort())); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test public void testCachedFailoverRealClose() throws Exception { TcpNetServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server1"); final CountDownLatch latch1 = new CountDownLatch(3); server1.registerListener(message -> { latch1.countDown();/*from w ww.j a v a2 s. c o m*/ return false; }); server1.start(); TestingUtilities.waitListening(server1, 10000L); int port1 = server1.getPort(); TcpNetServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server2"); final CountDownLatch latch2 = new CountDownLatch(2); server2.registerListener(message -> { latch2.countDown(); return false; }); server2.start(); TestingUtilities.waitListening(server2, 10000L); int port2 = server2.getPort(); // Failover AbstractClientConnectionFactory factory1 = new TcpNetClientConnectionFactory("localhost", port1); factory1.setBeanName("client1"); factory1.registerListener(message -> false); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2); factory2.setBeanName("client2"); factory2.registerListener(message -> false); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); GenericMessage<String> message = new GenericMessage<String>("foo"); conn1.send(message); conn1.close(); TcpConnection conn2 = cachingFactory.getConnection(); assertSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn2.send(message); conn1 = cachingFactory.getConnection(); assertNotSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn1.send(message); conn1.close(); conn2.close(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); server1.stop(); TestingUtilities.waitStopListening(server1, 10000L); TestingUtilities.waitUntilFactoryHasThisNumberOfConnections(factory1, 0); conn1 = cachingFactory.getConnection(); conn2 = cachingFactory.getConnection(); conn1.send(message); conn2.send(message); conn1.close(); conn2.close(); assertTrue(latch2.await(10, TimeUnit.SECONDS)); SimplePool<?> pool = TestUtils.getPropertyValue(cachingFactory, "pool", SimplePool.class); assertEquals(2, pool.getIdleCount()); server2.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test public void testCachedFailoverRealBadHost() throws Exception { TcpNetServerConnectionFactory server1 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server1"); final CountDownLatch latch1 = new CountDownLatch(3); server1.registerListener(message -> { latch1.countDown();// w ww. j a va 2 s . c o m return false; }); server1.start(); TestingUtilities.waitListening(server1, 10000L); int port1 = server1.getPort(); TcpNetServerConnectionFactory server2 = new TcpNetServerConnectionFactory(0); server1.setBeanName("server2"); final CountDownLatch latch2 = new CountDownLatch(2); server2.registerListener(message -> { latch2.countDown(); return false; }); server2.start(); TestingUtilities.waitListening(server2, 10000L); int port2 = server2.getPort(); // Failover AbstractClientConnectionFactory factory1 = new TcpNetClientConnectionFactory("junkjunk", port1); factory1.setBeanName("client1"); factory1.registerListener(message -> false); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2); factory2.setBeanName("client2"); factory2.registerListener(message -> false); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); GenericMessage<String> message = new GenericMessage<String>("foo"); conn1.send(message); conn1.close(); TcpConnection conn2 = cachingFactory.getConnection(); assertSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn2.send(message); conn1 = cachingFactory.getConnection(); assertNotSame(((TcpConnectionInterceptorSupport) conn1).getTheConnection(), ((TcpConnectionInterceptorSupport) conn2).getTheConnection()); conn1.send(message); conn1.close(); conn2.close(); assertTrue(latch2.await(10, TimeUnit.SECONDS)); assertEquals(3, latch1.getCount()); server1.stop(); server2.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@Test //INT-3650 public void testRealConnection() throws Exception { TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0); final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(102); final List<String> connectionIds = new ArrayList<String>(); in.registerListener(message -> {//from w ww .ja va2s. c om connectionIds.add((String) message.getHeaders().get(IpHeaders.CONNECTION_ID)); latch1.countDown(); latch2.countDown(); return false; }); in.start(); TestingUtilities.waitListening(in, null); int port = in.getPort(); TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port); CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 1); cache.setSingleUse(false); cache.setConnectionWaitTimeout(100); cache.start(); TcpConnectionSupport connection1 = cache.getConnection(); connection1.send(new GenericMessage<String>("foo")); connection1.close(); TcpConnectionSupport connection2 = cache.getConnection(); connection2.send(new GenericMessage<String>("foo")); connection2.close(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertSame(connectionIds.get(0), connectionIds.get(1)); for (int i = 0; i < 100; i++) { TcpConnectionSupport connection = cache.getConnection(); connection.send(new GenericMessage<String>("foo")); connection.close(); } assertTrue(latch2.await(10, TimeUnit.SECONDS)); assertSame(connectionIds.get(0), connectionIds.get(101)); in.stop(); cache.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
@SuppressWarnings("unchecked") @Test //INT-3722/*from w w w . ja v a 2s . 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.CachingClientConnectionFactoryTests.java
@Test // INT-3728 public void testEarlyReceive() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AbstractClientConnectionFactory factory = new TcpNetClientConnectionFactory("", 0) { @Override//from w w w.j a v a 2s. co m protected Socket createSocket(String host, int port) throws IOException { Socket mock = mock(Socket.class); when(mock.getInputStream()).thenReturn(new ByteArrayInputStream("foo\r\n".getBytes())); return mock; } @Override public boolean isActive() { return true; } }; factory.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); final CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(factory, 1); final AtomicReference<Message<?>> received = new AtomicReference<Message<?>>(); cachingFactory.registerListener(message -> { if (!(message instanceof ErrorMessage)) { received.set(message); latch.countDown(); } return false; }); cachingFactory.start(); cachingFactory.getConnection(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNotNull(received.get()); assertNotNull(received.get().getHeaders().get(IpHeaders.ACTUAL_CONNECTION_ID)); cachingFactory.stop(); }
From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java
@Test public void testFailConnect() { TcpNetClientConnectionFactory ccf = new TcpNetClientConnectionFactory("junkjunk", 1234); final AtomicReference<ApplicationEvent> failEvent = new AtomicReference<ApplicationEvent>(); ccf.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override//from ww w.jav a 2 s. co m public void publishEvent(Object event) { } @Override public void publishEvent(ApplicationEvent event) { failEvent.set(event); } }); ccf.start(); try { ccf.getConnection(); fail("expected exception"); } catch (Exception e) { assertThat(e, instanceOf(UnknownHostException.class)); TcpConnectionFailedEvent event = (TcpConnectionFailedEvent) failEvent.get(); assertSame(e, event.getCause()); } }
From source file:org.springframework.integration.ip.tcp.connection.ConnectionFactoryTests.java
public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactory) throws Exception { final List<IpIntegrationEvent> events = Collections.synchronizedList(new ArrayList<IpIntegrationEvent>()); int expectedEvents = serverFactory instanceof TcpNetServerConnectionFactory ? 7 // Listening, + OPEN, CLOSE, EXCEPTION for each side : 5; // Listening, + OPEN, CLOSE (but we *might* get exceptions, depending on timing). final CountDownLatch serverListeningLatch = new CountDownLatch(1); final CountDownLatch eventLatch = new CountDownLatch(expectedEvents); ApplicationEventPublisher publisher = new ApplicationEventPublisher() { @Override// ww w .j a v a2 s . c o m public void publishEvent(ApplicationEvent event) { LogFactory.getLog(this.getClass()).trace("Received: " + event); events.add((IpIntegrationEvent) event); if (event instanceof TcpConnectionServerListeningEvent) { serverListeningLatch.countDown(); } eventLatch.countDown(); } @Override public void publishEvent(Object event) { } }; serverFactory.setBeanName("serverFactory"); serverFactory.setApplicationEventPublisher(publisher); serverFactory = spy(serverFactory); final CountDownLatch serverConnectionInitLatch = new CountDownLatch(1); doAnswer(invocation -> { Object result = invocation.callRealMethod(); serverConnectionInitLatch.countDown(); return result; }).when(serverFactory).wrapConnection(any(TcpConnectionSupport.class)); ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(10); scheduler.afterPropertiesSet(); BeanFactory bf = mock(BeanFactory.class); when(bf.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true); when(bf.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)) .thenReturn(scheduler); serverFactory.setBeanFactory(bf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setOutputChannel(new NullChannel()); adapter.setConnectionFactory(serverFactory); adapter.start(); assertTrue("Listening event not received", serverListeningLatch.await(10, TimeUnit.SECONDS)); assertThat(events.get(0), instanceOf(TcpConnectionServerListeningEvent.class)); assertThat(((TcpConnectionServerListeningEvent) events.get(0)).getPort(), equalTo(serverFactory.getPort())); int port = serverFactory.getPort(); TcpNetClientConnectionFactory clientFactory = new TcpNetClientConnectionFactory("localhost", port); clientFactory.registerListener(message -> false); clientFactory.setBeanName("clientFactory"); clientFactory.setApplicationEventPublisher(publisher); clientFactory.start(); TcpConnectionSupport client = clientFactory.getConnection(); List<String> clients = clientFactory.getOpenConnectionIds(); assertEquals(1, clients.size()); assertTrue(clients.contains(client.getConnectionId())); assertTrue("Server connection failed to register", serverConnectionInitLatch.await(1, TimeUnit.SECONDS)); List<String> servers = serverFactory.getOpenConnectionIds(); assertEquals(1, servers.size()); assertTrue(serverFactory.closeConnection(servers.get(0))); servers = serverFactory.getOpenConnectionIds(); assertEquals(0, servers.size()); int n = 0; clients = clientFactory.getOpenConnectionIds(); while (n++ < 100 && clients.size() > 0) { Thread.sleep(100); clients = clientFactory.getOpenConnectionIds(); } assertEquals(0, clients.size()); assertTrue(eventLatch.await(10, TimeUnit.SECONDS)); assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events, events.size(), greaterThanOrEqualTo(expectedEvents)); FooEvent event = new FooEvent(client, "foo"); client.publishEvent(event); assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events, events.size(), greaterThanOrEqualTo(expectedEvents + 1)); try { event = new FooEvent(mock(TcpConnectionSupport.class), "foo"); client.publishEvent(event); fail("Expected exception"); } catch (IllegalArgumentException e) { assertTrue("Can only publish events with this as the source".equals(e.getMessage())); } SocketAddress address = serverFactory.getServerSocketAddress(); if (address instanceof InetSocketAddress) { InetSocketAddress inetAddress = (InetSocketAddress) address; assertEquals(port, inetAddress.getPort()); } serverFactory.stop(); scheduler.shutdown(); }
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 ww . java 2s . 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 ww. j av a 2 s . c om*/ 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(); }