List of usage examples for java.net ServerSocket getLocalPort
public int getLocalPort()
From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcherTest.java
@Before public void before() throws Exception { ServerSocket ss = new ServerSocket(0); int serverPort = ss.getLocalPort(); ss.close();// w ww . j av a 2 s.c om TestServer server = new TestServer(); server.start(serverPort); moduleHostUri = "http://localhost:" + serverPort; }
From source file:org.auraframework.integration.test.archetype.AuraArchetypeSimpleTestMANUAL.java
@Test public void testProjectCreation() throws Throwable { Process jettyProcess = null;/*from ww w .j a v a2s . c o m*/ workspace = new File(IOUtil.newTempDir("archetype")); try { // create a workspace to place the project files in workspace.mkdirs(); // generate a project from the archetype Process genProcess = startProcess(workspace, ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo, "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId, "-DarchetypeArtifactId=" + archetype.artifactId, "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId, "-DartifactId=" + project.artifactId, "-Dversion=" + project.version, "-Dpackage=" + projectPackage, "-DinteractiveMode=false")); goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!"); File projectDir = new File(workspace, project.artifactId); assertDirectory(projectDir); verifyGeneratedResources(projectDir); // build the new project Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install")); goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!"); // get a free port for jetty ServerSocket socket = new ServerSocket(0); int jettyPort = socket.getLocalPort(); socket.close(); // start up jetty jettyProcess = startProcess(projectDir, ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort)); int status = 0; for (int i = 0; i < 30; i++) { try { HttpGet get = obtainGetMethod("/"); HttpResponse response = perform(get); status = getStatusCode(response); get.releaseConnection(); break; } catch (ConnectException ce) { // expected, before server is listening Thread.sleep(1000); } } assertEquals("Failed to connect to server", HttpStatus.SC_OK, status); verifyDefaultDocument(); verifySampleComponents(); } catch (Throwable t) { // if any errors in Jetty requests, let's print out the Jetty // console output for diag before killing the // test if (jettyProcess != null) { InputStream is = jettyProcess.getInputStream(); int len = is.available(); byte[] buf = new byte[len]; is.read(buf); System.err.println(new String(buf)); } throw t; } finally { // kill Jetty if (jettyProcess != null) { try { jettyProcess.exitValue(); } catch (IllegalThreadStateException e) { jettyProcess.destroy(); } } // cleanup generated workspace IOUtil.delete(workspace); } }
From source file:org.auraframework.archetype.AuraArchetypeSimpleTestMANUAL.java
public void testProjectCreation() throws Throwable { Process jettyProcess = null;/*from w ww.ja v a 2s. co m*/ workspace = new File( System.getProperty("java.io.tmpdir") + File.separator + getName() + System.currentTimeMillis()); try { // create a workspace to place the project files in workspace.mkdirs(); // generate a project from the archetype Process genProcess = startProcess(workspace, ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo, "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId, "-DarchetypeArtifactId=" + archetype.artifactId, "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId, "-DartifactId=" + project.artifactId, "-Dversion=" + project.version, "-Dpackage=" + projectPackage, "-DinteractiveMode=false")); goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!"); File projectDir = new File(workspace, project.artifactId); assertDirectory(projectDir); verifyGeneratedResources(projectDir); // build the new project Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install")); goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!"); // get a free port for jetty ServerSocket socket = new ServerSocket(0); int jettyPort = socket.getLocalPort(); socket.close(); // start up jetty jettyProcess = startProcess(projectDir, ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort)); int status = 0; for (int i = 0; i < 30; i++) { try { HttpGet get = obtainGetMethod("/"); HttpResponse response = perform(get); status = getStatusCode(response); get.releaseConnection(); break; } catch (ConnectException ce) { // expected, before server is listening Thread.sleep(1000); } } assertEquals("Failed to connect to server", HttpStatus.SC_OK, status); verifyDefaultDocument(); verifySampleComponents(); } catch (Throwable t) { // if any errors in Jetty requests, let's print out the Jetty // console output for diag before killing the // test if (jettyProcess != null) { InputStream is = jettyProcess.getInputStream(); int len = is.available(); byte[] buf = new byte[len]; is.read(buf); System.err.println(new String(buf)); } throw t; } finally { // kill Jetty if (jettyProcess != null) { try { jettyProcess.exitValue(); } catch (IllegalThreadStateException e) { jettyProcess.destroy(); } } // cleanup generated workspace IOUtil.delete(workspace); } }
From source file:com.amazonaws.auth.EC2MetadataServiceMock.java
private ServerSocket startServerSocket() { try {/*from w w w .j a v a 2 s . co m*/ ServerSocket serverSocket = new ServerSocket(0); System.setProperty(EC2_METADATA_SERVICE_OVERRIDE_SYSTEM_PROPERTY, "http://localhost:" + serverSocket.getLocalPort()); System.out.println("Started mock metadata service at: " + System.getProperty(EC2_METADATA_SERVICE_OVERRIDE_SYSTEM_PROPERTY)); return serverSocket; } catch (IOException ioe) { throw new RuntimeException("Unable to start mock EC2 metadata server", ioe); } }
From source file:org.apache.nifi.atlas.emulator.EmbeddedKafka.java
/** * Will determine the available port used by Kafka/Zookeeper servers. *///from w w w . ja va 2 s .c om private int availablePort() { ServerSocket s = null; try { s = new ServerSocket(0); s.setReuseAddress(true); return s.getLocalPort(); } catch (Exception e) { throw new IllegalStateException("Failed to discover available port.", e); } finally { try { s.close(); } catch (IOException e) { // ignore } } }
From source file:com.reversemind.hypergate.server.HyperGateServer.java
/** * Detect free setPort on System/*w w w .j a v a2 s. co m*/ * * @return */ private int detectFreePort() { try { ServerSocket serverSocket = new ServerSocket(0); if (serverSocket.getLocalPort() == -1) { System.exit(-100); throw new RuntimeException( "\n\nCould not start HyperGateServer there are no any free port in the system available"); } int detectedPortNumber = serverSocket.getLocalPort(); serverSocket.close(); int count = 0; while (!serverSocket.isClosed()) { if (count++ > 10) { throw new RuntimeException("Could not start HyperGateServer"); } try { Thread.sleep(100); LOG.info("Waiting for closing auto discovered socket try number#" + count); } catch (InterruptedException e) { System.exit(-100); throw new RuntimeException("Could not start HyperGateServer"); } } serverSocket = null; return detectedPortNumber; } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException("Could not start HyperGateServer 'cause no any available free port in system"); }
From source file:ezbake.thriftrunner.starters.SimpleStarter.java
boolean serverSocketIsFree(int port) { ServerSocket socket = null; try {// ww w . ja v a2 s . c o m socket = new ServerSocket(); socket.setReuseAddress(true); socket.bind(new InetSocketAddress(port)); this.portNumber = socket.getLocalPort(); return true; } catch (final IOException e) { return false; } finally { try { if (socket != null) { socket.close(); } } catch (final IOException e) { // should never happen } } }
From source file:org.apache.hadoop.ipc.TestServer.java
@Test public void testBind() throws Exception { Configuration conf = new Configuration(); ServerSocket socket = new ServerSocket(); InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0); socket.bind(address);/*from w ww . j a va 2 s . co m*/ try { int min = socket.getLocalPort(); int max = min + 100; conf.set("TestRange", min + "-" + max); ServerSocket socket2 = new ServerSocket(); InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0); Server.bind(socket2, address2, 10, conf, "TestRange"); try { assertTrue(socket2.isBound()); assertTrue(socket2.getLocalPort() > min); assertTrue(socket2.getLocalPort() <= max); } finally { socket2.close(); } } finally { socket.close(); } }
From source file:org.apache.hadoop.ipc.TestServer.java
@Test public void testBindError() throws Exception { Configuration conf = new Configuration(); ServerSocket socket = new ServerSocket(); InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0); socket.bind(address);//from w w w. ja v a 2 s . c om try { int min = socket.getLocalPort(); conf.set("TestRange", min + "-" + min); ServerSocket socket2 = new ServerSocket(); InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0); boolean caught = false; try { Server.bind(socket2, address2, 10, conf, "TestRange"); } catch (BindException e) { caught = true; } finally { socket2.close(); } assertTrue("Failed to catch the expected bind exception", caught); } finally { socket.close(); } }
From source file:org.openflamingo.remote.thrift.thriftfs.ThriftPluginServer.java
/** * Start processing requests.//from w w w.j a va 2 s .c o m * * @throws IllegalStateException if the server has already been started. * @throws java.io.IOException on network errors. */ public void start() throws IOException { String hostname = address.getAddress().getHostAddress(); synchronized (this) { if (server != null) { throw new IllegalStateException("Thrift server already started"); } LOG.info("Starting Thrift server"); ServerSocket sock = new ServerSocket(); sock.setReuseAddress(true); if (port == 0) { sock.bind(null); address = new InetSocketAddress(hostname, sock.getLocalPort()); port = address.getPort(); } else { sock.bind(address); } int socketTimeout = conf.getInt("dfs.thrift.socket.timeout", SOCKET_READ_TIMEOUT); TServerTransport transport = new TServerSocket(sock, socketTimeout); SanerThreadPoolServer.Options options = new SanerThreadPoolServer.Options(); options.minWorkerThreads = conf.getInt("dfs.thrift.threads.min", 5); options.maxWorkerThreads = conf.getInt("dfs.thrift.threads.max", 20); options.stopTimeoutVal = conf.getInt("dfs.thrift.timeout", 60); options.stopTimeoutUnit = TimeUnit.SECONDS; options.queueSize = conf.getInt("dfs.thrift.queue.size", 4 * options.maxWorkerThreads); server = new SanerThreadPoolServer(processorFactory, transport, transportFactory, transportFactory, new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), options); } Thread t = new Thread(this); t.start(); LOG.info("Thrift server listening on " + hostname + ":" + port); }