Java Code Examples for java.net.ServerSocket#getLocalPort()
The following examples show how to use
java.net.ServerSocket#getLocalPort() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SocksConnectTimeout.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { try { serverSocket = new ServerSocket(0); (new Thread() { @Override public void run() { serve(); } }).start(); Proxy socksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(InetAddress.getLocalHost(), serverSocket.getLocalPort())); test(socksProxy); } catch (IOException e) { unexpected(e); } finally { close(serverSocket); if (failed > 0) throw new RuntimeException("Test Failed: passed:" + passed + ", failed:" + failed); } }
Example 2
Source File: SocksConnectTimeout.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { try { serverSocket = new ServerSocket(0); (new Thread() { @Override public void run() { serve(); } }).start(); Proxy socksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(InetAddress.getLocalHost(), serverSocket.getLocalPort())); test(socksProxy); } catch (IOException e) { unexpected(e); } finally { close(serverSocket); if (failed > 0) throw new RuntimeException("Test Failed: passed:" + passed + ", failed:" + failed); } }
Example 3
Source File: NettyRestServerTest.java From tajo with Apache License 2.0 | 6 votes |
@Test public void testNettyRestServerCreation() throws Exception { ResourceConfig resourceConfig = ResourceConfig.forApplicationClass(TestApplication1.class); ServerSocket serverSocket = new ServerSocket(0); int availPort = serverSocket.getLocalPort(); serverSocket.close(); URI baseUri = new URI("http://localhost:"+availPort+"/rest"); NettyRestServer restServer = NettyRestServerFactory.createNettyRestServer(baseUri, resourceConfig, 3); assertNotNull(restServer); assertNotNull(restServer.getHandler()); assertNotNull(restServer.getChannel()); assertNotNull(restServer.getListenAddress()); InetSocketAddress listeningAddress = restServer.getListenAddress(); assertEquals(availPort, listeningAddress.getPort()); }
Example 4
Source File: Application.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) throws Exception { // bind to a random port if (args.length < 1) { System.err.println("First argument should be path to output file."); } String outFileName = args[0]; ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); int pid = ProcessTools.getProcessId(); System.out.println("shutdownPort=" + port); System.out.println("pid=" + pid); System.out.flush(); try (PrintWriter writer = new PrintWriter(outFileName)) { writer.println("shutdownPort=" + port); writer.println("pid=" + pid); writer.println("done"); writer.flush(); } // wait for test harness to connect Socket s = ss.accept(); s.close(); ss.close(); }
Example 5
Source File: NearestNeighborTest.java From deeplearning4j with Apache License 2.0 | 5 votes |
public static int getAvailablePort() { try { ServerSocket socket = new ServerSocket(0); try { return socket.getLocalPort(); } finally { socket.close(); } } catch (IOException e) { throw new IllegalStateException("Cannot find available port: " + e.getMessage(), e); } }
Example 6
Source File: TestApplication.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws IOException { // Some tests require the application to exit immediately if (args.length > 0 && args[0].equals("-exit")) { return; } // bind to a random port ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); int pid = -1; try { pid = ProcessTools.getProcessId(); } catch (Exception e) { e.printStackTrace(); } // signal test that we are started - do not remove these lines!! System.out.println("port:" + port); System.out.println("pid:" + pid); System.out.println("waiting for the manager ..."); System.out.flush(); // wait for manager to connect Socket s = ss.accept(); s.close(); ss.close(); }
Example 7
Source File: NioEndpoint.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
/** * Port in use. */ @Override public int getLocalPort() { ServerSocketChannel ssc = serverSock; if (ssc == null) { return -1; } else { ServerSocket s = ssc.socket(); if (s == null) { return -1; } else { return s.getLocalPort(); } } }
Example 8
Source File: Application.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) throws Exception { // bind to a random port if (args.length < 1) { System.err.println("First argument should be path to output file."); } String outFileName = args[0]; ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); int pid = ProcessTools.getProcessId(); System.out.println("shutdownPort=" + port); System.out.println("pid=" + pid); System.out.flush(); try (PrintWriter writer = new PrintWriter(outFileName)) { writer.println("shutdownPort=" + port); writer.println("pid=" + pid); writer.println("done"); writer.flush(); } // wait for test harness to connect Socket s = ss.accept(); s.close(); ss.close(); }
Example 9
Source File: ConsumerManagerTest.java From openid4java with Apache License 2.0 | 5 votes |
public static MockOpenIDServer createAndStart() throws Exception { ServerSocket socket = new ServerSocket(0); int port = socket.getLocalPort(); socket.close(); MockOpenIDServer result = new MockOpenIDServer(port); result.start(); return result; }
Example 10
Source File: IntelliJCoderServer.java From intellijcoder with MIT License | 5 votes |
public int start() throws IntelliJCoderException { final ServerSocket serverSocket; try { serverSocket = network.bindServerSocket(0); } catch (IOException e) { throw new IntelliJCoderException(FAILED_TO_START_SERVER_MESSAGE, e); } new Thread(new ServerCycle(serverSocket)).start(); return serverSocket.getLocalPort(); }
Example 11
Source File: PickUnusedPort.java From brave with Apache License 2.0 | 5 votes |
static int get() { try { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { throw new AssertionError(e); } }
Example 12
Source File: InvalidLdapFilters.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
void doServerSide() throws Exception { ServerSocket serverSock = new ServerSocket(serverPort); // signal client, it's ready to accecpt connection serverPort = serverSock.getLocalPort(); serverReady = true; // accept a connection Socket socket = serverSock.accept(); System.out.println("Server: Connection accepted"); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); // read the bindRequest while (is.read() != -1) { // ignore is.skip(is.available()); break; } byte[] bindResponse = {0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00}; // write bindResponse os.write(bindResponse); os.flush(); // ignore any more request. while (is.read() != -1) { // ignore is.skip(is.available()); } is.close(); os.close(); socket.close(); serverSock.close(); }
Example 13
Source File: Main.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public void run() { try { // Find vacant port number ServerSocket ss = new ServerSocket(0); port = ss.getLocalPort(); ss.close(); // Publish WebService System.out.println("Publishing WebService on " + port + " port"); Endpoint ep = Endpoint.publish("http://localhost:" + port + "/ws/hello", new HelloWorldImpl()); // Notify main thread that WS endpoint is published initSignal.countDown(); // Wait for main thread to complete testing System.out.println("Waiting for done signal from test client."); doneSignal.await(); // Terminate WS endpoint System.out.println("Got done signal from the client. Stopping WS endpoint."); ep.stop(); } catch (IOException ioe) { System.out.println("Failed to get vacant port number:" + ioe); } catch (InterruptedException ie) { System.out.println("Failed to wait for test completion:" + ie); } }
Example 14
Source File: AxisClientPluginIT.java From glowroot with Apache License 2.0 | 4 votes |
private int getAvailablePort() throws Exception { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; }
Example 15
Source File: AddrInUse.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { System.err.println("\nRegression test for bug 4111507\n"); /* * Bind a server socket to a port. */ ServerSocket server = new ServerSocket(0); port = server.getLocalPort(); System.err.println("Created a ServerSocket on port " + port + "..."); /* * Start a thread that creates a registry on the same port, * and analyze the result. */ System.err.println("create a registry on the same port..."); System.err.println("(should cause an ExportException)"); AddrInUse obj = new AddrInUse(); synchronized (obj) { (new Thread(obj, "AddrInUse")).start(); /* * Don't wait forever (original bug is that the export * hangs). */ obj.wait(TIMEOUT); if (obj.exportSucceeded) { throw new RuntimeException( "TEST FAILED: export on already-bound port succeeded"); } else if (obj.exportException != null) { obj.exportException.printStackTrace(); if (obj.exportException instanceof ExportException) { System.err.println("TEST PASSED"); } else { throw new RuntimeException( "TEST FAILED: unexpected exception occurred", obj.exportException); } } else { throw new RuntimeException("TEST FAILED: export timed out"); } } }
Example 16
Source File: RunToExit.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
public static void main(String args[]) throws Exception { // find a free port ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); ss.close(); String address = String.valueOf(port); // launch the server debuggee Process process = launch(address, "Exit0"); // wait for the debugge to be ready while (!ready) { try { Thread.sleep(1000); } catch(Exception ee) { throw ee; } } // attach to server debuggee and resume it so it can exit AttachingConnector conn = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach"); Map conn_args = conn.defaultArguments(); Connector.IntegerArgument port_arg = (Connector.IntegerArgument)conn_args.get("port"); port_arg.setValue(port); VirtualMachine vm = conn.attach(conn_args); // The first event is always a VMStartEvent, and it is always in // an EventSet by itself. Wait for it. EventSet evtSet = vm.eventQueue().remove(); for (Event event: evtSet) { if (event instanceof VMStartEvent) { break; } throw new RuntimeException("Test failed - debuggee did not start properly"); } vm.eventRequestManager().deleteAllBreakpoints(); vm.resume(); int exitCode = process.waitFor(); // if the server debuggee ran cleanly, we assume we were clean if (exitCode == 0 && error_seen == 0) { System.out.println("Test passed - server debuggee cleanly terminated"); } else { throw new RuntimeException("Test failed - server debuggee generated an error when it terminated"); } }
Example 17
Source File: Vertx1xIT.java From glowroot with Apache License 2.0 | 4 votes |
private static int getAvailablePort() throws Exception { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; }
Example 18
Source File: RMTHelper.java From scheduling with GNU Affero General Public License v3.0 | 4 votes |
static int findFreePort() throws IOException { ServerSocket server = new ServerSocket(0); int port = server.getLocalPort(); server.close(); return port; }
Example 19
Source File: HIVERangerAuthorizerTest.java From ranger with Apache License 2.0 | 4 votes |
@org.junit.BeforeClass public static void setup() throws Exception { // Get a random port ServerSocket serverSocket = new ServerSocket(0); port = serverSocket.getLocalPort(); serverSocket.close(); HiveConf conf = new HiveConf(); // Warehouse File warehouseDir = new File("./target/hdfs/warehouse").getAbsoluteFile(); conf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, warehouseDir.getPath()); // Scratchdir File scratchDir = new File("./target/hdfs/scratchdir").getAbsoluteFile(); conf.set("hive.exec.scratchdir", scratchDir.getPath()); // REPL DUMP target folder File replRootDir = new File("./target/user/hive").getAbsoluteFile(); conf.set("hive.repl.rootdir", replRootDir.getPath()); // Create a temporary directory for the Hive metastore File metastoreDir = new File("./metastore_db/").getAbsoluteFile(); conf.set(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname, String.format("jdbc:derby:;databaseName=%s;create=true", metastoreDir.getPath())); conf.set(HiveConf.ConfVars.METASTORE_AUTO_CREATE_ALL.varname, "true"); conf.set(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT.varname, "" + port); conf.set(HiveConf.ConfVars.METASTORE_SCHEMA_VERIFICATION.toString(), "false"); conf.set(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_PORT.varname, "0"); conf.set(HiveConf.ConfVars.HIVE_EXECUTION_ENGINE.varname,"mr"); hiveServer = new HiveServer2(); hiveServer.init(conf); hiveServer.start(); Class.forName("org.apache.hive.jdbc.HiveDriver"); // Create database String initialUrl = "jdbc:hive2://localhost:" + port; Connection connection = DriverManager.getConnection(initialUrl, "admin", "admin"); Statement statement = connection.createStatement(); statement.execute("CREATE DATABASE IF NOT EXISTS rangerauthz with dbproperties ('repl.source.for'='1,2,3')"); statement.execute("CREATE DATABASE IF NOT EXISTS demo"); statement.close(); connection.close(); // Load data into HIVE String url = "jdbc:hive2://localhost:" + port + "/rangerauthz"; connection = DriverManager.getConnection(url, "admin", "admin"); statement = connection.createStatement(); // statement.execute("CREATE TABLE WORDS (word STRING, count INT)"); statement.execute("create table if not exists words (word STRING, count INT) row format delimited fields terminated by '\t' stored as textfile"); // Copy "wordcount.txt" to "target" to avoid overwriting it during load File inputFile = new File(HIVERangerAuthorizerTest.class.getResource("../../../../../wordcount.txt").toURI()); Path outputPath = Paths.get(inputFile.toPath().getParent().getParent().toString() + File.separator + "wordcountout.txt"); Files.copy(inputFile.toPath(), outputPath); statement.execute("LOAD DATA INPATH '" + outputPath + "' OVERWRITE INTO TABLE words"); // Just test to make sure it's working ResultSet resultSet = statement.executeQuery("SELECT * FROM words where count == '100'"); if (resultSet.next()) { Assert.assertEquals("Mr.", resultSet.getString(1)); } else { Assert.fail("No ResultSet found"); } statement.close(); connection.close(); // Enable ranger authorization after the initial db setup and table creating is done. conf.set(HiveConf.ConfVars.HIVE_AUTHORIZATION_ENABLED.varname, "true"); conf.set(HiveConf.ConfVars.HIVE_SERVER2_ENABLE_DOAS.varname, "true"); conf.set(HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER.varname, "org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizerFactory"); }
Example 20
Source File: RunToExit.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void main(String args[]) throws Exception { // find a free port ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); ss.close(); String address = String.valueOf(port); // launch the server debuggee Process process = launch(address, "Exit0"); // attach to server debuggee and resume it so it can exit AttachingConnector conn = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach"); Map conn_args = conn.defaultArguments(); Connector.IntegerArgument port_arg = (Connector.IntegerArgument)conn_args.get("port"); port_arg.setValue(port); System.out.println("Connection arguments: " + conn_args); VirtualMachine vm = null; while (vm == null) { try { vm = conn.attach(conn_args); } catch (ConnectException e) { e.printStackTrace(System.out); System.out.println("--- Debugee not ready. Retrying in 500ms. ---"); Thread.sleep(500); } } // The first event is always a VMStartEvent, and it is always in // an EventSet by itself. Wait for it. EventSet evtSet = vm.eventQueue().remove(); for (Event event: evtSet) { if (event instanceof VMStartEvent) { break; } throw new RuntimeException("Test failed - debuggee did not start properly"); } vm.eventRequestManager().deleteAllBreakpoints(); vm.resume(); int exitCode = process.waitFor(); // if the server debuggee ran cleanly, we assume we were clean if (exitCode == 0 && error_seen == 0) { System.out.println("Test passed - server debuggee cleanly terminated"); } else { throw new RuntimeException("Test failed - server debuggee generated an error when it terminated, " + "exit code was " + exitCode + ", " + error_seen + " error(s) seen in debugee output."); } }