List of usage examples for javax.net ServerSocketFactory getDefault
public static ServerSocketFactory getDefault()
From source file:org.codehaus.stomp.jms.StompConnect.java
public ServerSocketFactory getServerSocketFactory() { if (serverSocketFactory == null) { serverSocketFactory = ServerSocketFactory.getDefault(); }/* www. j a v a 2 s.c o m*/ return serverSocketFactory; }
From source file:org.springframework.cloud.stream.app.tcp.client.source.TcpClientTests.java
@BeforeClass public static void startup() throws Exception { serverSocket = ServerSocketFactory.getDefault().createServerSocket(0); System.setProperty("tcp.client.test.port", Integer.toString(serverSocket.getLocalPort())); }
From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java
private void testServerExceptionGuts(int port, AbstractServerConnectionFactory factory) throws Exception { ServerSocket ss = null;//from w w w. ja v a 2 s.c o m try { ss = ServerSocketFactory.getDefault().createServerSocket(port); } catch (Exception e) { return; // skip this test, someone grabbed the port } final AtomicReference<TcpConnectionServerExceptionEvent> theEvent = new AtomicReference<TcpConnectionServerExceptionEvent>(); final CountDownLatch latch = new CountDownLatch(1); factory.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override public void publishEvent(ApplicationEvent event) { theEvent.set((TcpConnectionServerExceptionEvent) event); latch.countDown(); } @Override public void publishEvent(Object event) { } }); factory.setBeanName("sf"); factory.registerListener(message -> false); Log logger = spy(TestUtils.getPropertyValue(factory, "logger", Log.class)); doAnswer(new DoesNothing()).when(logger).error(anyString(), any(Throwable.class)); new DirectFieldAccessor(factory).setPropertyValue("logger", logger); factory.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); String actual = theEvent.toString(); assertThat(actual, containsString("cause=java.net.BindException")); assertThat(actual, containsString("source=" + "sf, port=" + port)); ArgumentCaptor<String> reasonCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class); verify(logger).error(reasonCaptor.capture(), throwableCaptor.capture()); assertThat(reasonCaptor.getValue(), startsWith("Error on Server")); assertThat(reasonCaptor.getValue(), endsWith("; port = " + port)); assertThat(throwableCaptor.getValue(), instanceOf(BindException.class)); ss.close(); }
From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java
@Test public void testWriteTimeout() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>(); Executors.newSingleThreadExecutor().execute(() -> { try {//from w w w . j a v a 2 s . c o m ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0); logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort()); serverSocket.set(server); latch.countDown(); Socket s = server.accept(); // block so we fill the buffer done.await(10, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", serverSocket.get().getLocalPort()); factory.setApplicationEventPublisher(nullPublisher); factory.setSoTimeout(1000); factory.start(); try { TcpConnection connection = factory.getConnection(); connection.send(MessageBuilder.withPayload(new byte[1000000]).build()); } catch (Exception e) { assertTrue( "Expected SocketTimeoutException, got " + e.getClass().getSimpleName() + ":" + e.getMessage(), e instanceof SocketTimeoutException); } done.countDown(); serverSocket.get().close(); }
From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java
@Test public void testReadTimeout() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>(); Executors.newSingleThreadExecutor().execute(() -> { try {/*from www. jav a 2 s .c o m*/ ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0); logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort()); serverSocket.set(server); latch.countDown(); Socket socket = server.accept(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); // block to cause timeout on read. done.await(10, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", serverSocket.get().getLocalPort()); factory.setApplicationEventPublisher(nullPublisher); factory.setSoTimeout(1000); factory.start(); try { TcpConnection connection = factory.getConnection(); connection.send(MessageBuilder.withPayload("Test").build()); int n = 0; while (connection.isOpen()) { Thread.sleep(100); if (n++ > 200) { break; } } assertTrue(!connection.isOpen()); } catch (Exception e) { fail("Unexpected exception " + e); } done.countDown(); serverSocket.get().close(); }
From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java
@Test public void testMemoryLeak() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>(); Executors.newSingleThreadExecutor().execute(() -> { try {//from ww w. ja v a 2 s . c o m ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0); logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort()); serverSocket.set(server); latch.countDown(); Socket socket = server.accept(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); } catch (Exception e) { e.printStackTrace(); } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost", serverSocket.get().getLocalPort()); factory.setApplicationEventPublisher(nullPublisher); factory.setNioHarvestInterval(100); factory.start(); try { TcpConnection connection = factory.getConnection(); Map<SocketChannel, TcpNioConnection> connections = factory.getConnections(); assertEquals(1, connections.size()); connection.close(); assertTrue(!connection.isOpen()); TestUtils.getPropertyValue(factory, "selector", Selector.class).wakeup(); int n = 0; while (connections.size() > 0) { Thread.sleep(100); if (n++ > 100) { break; } } assertEquals(0, connections.size()); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception " + e); } factory.stop(); serverSocket.get().close(); }
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 . j a v a2 s .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 a v a2 s .c o 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 a 2s .com*/ 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//from ww w . j av a 2 s. c o 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(); }