List of usage examples for java.net ServerSocket getLocalPort
public int getLocalPort()
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 www .ja v a 2 s. c om*/ 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 w w w. ja va2 s. c om*/ 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 w w w . java 2 s .c om*/ 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.cloudata.core.commitlog.CommitLogServer.java
private int startFileTransferChannel(String dirName, FileChannel[] fileChannelList) { int port = -1; try {/*w w w . j a v a 2s .c om*/ ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket serverSocket = ssc.socket(); serverSocket.bind(null); port = serverSocket.getLocalPort(); new FileTransferThread(dirName, ssc, fileChannelList).start(); //LOG.info("File transfer thread is started and read method is done"); } catch (IOException e) { LOG.warn("starting file transfer is fail", e); } return port; }
From source file:hudson.gridmaven.gridlayer.PluginImpl.java
/** * Compute the host name that Hadoop nodes can be used to talk to Name node. * * <p>//from w ww. j av a 2 s .co m * We prefer to use {@link Hudson#getRootUrl()}, except we have to watch out for a possibility * that it points to a front end (like apache, router with port-forwarding, etc.), and if that is the case, * use some heuristics to find out a usable host name. * * TODO: move this to {@code Hudson.toComputer().getHostName()}. */ String getMasterHostName() throws IOException, InterruptedException { // check if rootURL is reliable Hudson h = Hudson.getInstance(); String rootUrl = h.getRootUrl(); if (rootUrl == null) { // the only option is to auto-detect. String real = h.toComputer().getHostName(); LOGGER.fine("Hudson root URL isn't configured. Using " + real + " instead"); return real; } // according to Hudson's setting, this is the host name that we can use to connect to master, // at least for HTTP. See if we can connect to the arbitrary port in this way. final String hostName = new URL(rootUrl).getHost(); final ServerSocket ss = new ServerSocket(0); Thread t = new Thread() { @Override public void run() { try { ss.accept(); } catch (IOException e) { // shouldn't happen LOGGER.log(Level.INFO, "Failed to accept", e); } finally { try { ss.close(); } catch (IOException e) { // ignore } } } }; t.start(); try { Socket s = new Socket(); s.connect(new InetSocketAddress(hostName, ss.getLocalPort()), 1000); s.close(); // yep, it worked return hostName; } catch (IOException e) { // no it didn't String real = h.toComputer().getHostName(); LOGGER.fine("Hudson root URL " + rootUrl + " looks like a front end. Using " + real + " instead"); return real; } }
From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java
@Test(timeout = 1000L) public void testRequestTimeout() throws Exception { session.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, 100); ServerSocket server = new ServerSocket(0); newTransporter("http://localhost:" + server.getLocalPort()); try {//from w w w. jav a2s . co m try { transporter.get(new GetTask(URI.create("repo/file.txt"))); fail("Expected error"); } catch (SocketTimeoutException e) { assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } finally { server.close(); } }
From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java
private void startSecondary() { final String serviceHost = config.getString("fileserver.sync-host", DEFAULT_HOST); final int servicePort = config.getInt("fileserver.sync-port", DEFAULT_SYNC_PORT); Util.ensureDirectoryExists(); ServerSocket socket = null; try {/*from w ww . j a v a 2 s . co m*/ LOG.debug("setting up syncing socket on " + serviceHost + ":" + servicePort); final InetAddress address = InetAddress.getByName(serviceHost); socket = new ServerSocket(servicePort, 0, address); LOG.info( "listenting on " + socket.getInetAddress().getHostAddress() + " port " + socket.getLocalPort()); LOG.debug("listenting on " + socket); do { syncConnection(socket.accept(), 0); } while (awaitConnections); } catch (final UnknownHostException e) { LOG.error("Unknown host " + serviceHost, e); System.exit(0); } catch (final IOException e) { LOG.error("start failure - networking not set up for " + serviceHost, e); System.exit(0); } catch (final RuntimeException e) { LOG.error("start failure", e); System.exit(0); } }
From source file:ext.services.network.TestNetworkUtils.java
/** * Test get connection url proxy with proxy. * // w ww. ja va 2 s.com * * @throws Exception the exception */ public void testGetConnectionURLProxyWithProxy() throws Exception { final ServerSocket socket = new ServerSocket(PROXY_PORT); Thread thread = new Thread("ProxySocketAcceptThread") { @Override public void run() { try { while (!bStop) { Socket sock = socket.accept(); Log.debug("Accepted connection, sending back garbage and close socket..."); sock.getOutputStream().write(1); sock.close(); } } catch (IOException e) { Log.error(e); } } }; thread.setDaemon(true); // to finish tests even if this is still running thread.start(); Log.debug("Using local port: " + socket.getLocalPort()); try { // useful content when inet access is allowed Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false"); HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL), new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password")); assertNotNull(connection); connection.disconnect(); } finally { bStop = true; socket.close(); thread.join(); } }
From source file:com.apporiented.hermesftp.client.FtpTestClient.java
public String openExtendedActiveMode() throws IOException { StringBuffer params = new StringBuffer(); params.append("|1|"); InetAddress addr = NetUtils.getMachineAddress(true); ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 1, addr); params.append(addr.getHostAddress()); params.append("|"); params.append(serverSocket.getLocalPort()); params.append("|"); sendCommand("EPRT " + params.toString()); String response = getResponse(); if (passiveModeSocket != null) { passiveModeSocket.close();//from w w w . ja va2 s . c om } activeModeServerSocket = serverSocket; return response; }
From source file:org.apache.htrace.impl.HTracedProcess.java
private HTracedProcess(Builder builder) throws Exception { this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile(); if (!this.htracedPath.exists()) { throw new RuntimeException("No htraced binary exists at " + this.htracedPath); }//from w w w. ja va 2 s.c o m this.dataDir = new DataDir(); // Create a notifier socket bound to a random port. ServerSocket listener = new ServerSocket(0); boolean success = false; Process process = null; HttpClient http = null; try { // Use a random port for the web address. No 'scheme' yet. String random = builder.host + ":0"; String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath(); // Pass cmdline args to htraced to it uses our test dir for data. ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random, "-Ddata.store.clear=true", "-Dstartup.notification.address=localhost:" + listener.getLocalPort(), "-Ddata.store.directories=" + dataDir.get().getAbsolutePath()); // Set HTRACED_CONF_DIR to the temporary directory we just created, to // ensure that it doesn't pull in any other configuration file that might // be on this test machine. Map<String, String> env = pb.environment(); env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath()); // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that // we use the default value (which finds the local web files by relative // path). env.remove("HTRACED_WEB_DIR"); pb.redirectErrorStream(true); // Inherit STDERR/STDOUT i/o; dumps on console for now. Can add logs later. pb.inheritIO(); pb.directory(dataDir.get()); //assert pb.redirectInput() == Redirect.PIPE; //assert pb.redirectOutput().file() == dataDir; process = pb.start(); assert process.getInputStream().read() == -1; StartupNotificationData data = readStartupNotification(listener); httpAddr = data.httpAddr; hrpcAddr = data.hrpcAddr; LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr + ", logging to " + logPath); http = RestBufferManager.createHttpClient(60000L, 60000L); http.start(); success = true; } finally { if (!success) { // Clean up after failure if (process != null) { process.destroy(); process = null; } if (http != null) { http.stop(); } } delegate = process; listener.close(); httpClient = http; } }