Example usage for java.net ServerSocket getLocalPort

List of usage examples for java.net ServerSocket getLocalPort

Introduction

In this page you can find the example usage for java.net ServerSocket getLocalPort.

Prototype

public int getLocalPort() 

Source Link

Document

Returns the port number on which this socket is listening.

Usage

From source file:net.sf.ehcache.distribution.RMICacheManagerPeerListener.java

/**
 * Gets a free server socket port.//  ww  w . j  a  v  a  2s  .c o  m
 *
 * @return a number in the range 1025 - 65536 that was free at the time this method was executed
 * @throws IllegalArgumentException
 */
protected int getFreePort() throws IllegalArgumentException {
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(0);
        return serverSocket.getLocalPort();
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not acquire a free port number.");
    } finally {
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                serverSocket.close();
            } catch (Exception e) {
                LOG.debug("Error closing ServerSocket: " + e.getMessage());
            }
        }
    }
}

From source file:org.apache.tajo.rpc.TestAsyncRpc.java

@Test(timeout = 60000)
@SetupRpcConnection(setupRpcServer = false, setupRpcClient = false)
public void testClientRetryFailureOnStartup() throws Exception {
    retries = 2;/*  w  w  w  .j  a  v  a  2s  .  c o  m*/
    ServerSocket serverSocket = new ServerSocket(0);
    final InetSocketAddress address = new InetSocketAddress("127.0.0.1", serverSocket.getLocalPort());
    serverSocket.close();
    service = new DummyProtocolAsyncImpl();

    EchoMessage echoMessage = EchoMessage.newBuilder().setMessage(MESSAGE).build();
    CallFuture<EchoMessage> future = new CallFuture<>();

    RpcConnectionKey rpcConnectionKey = new RpcConnectionKey(address, DummyProtocol.class, true);

    Properties connParams = new Properties();
    connParams.setProperty(RpcConstants.CLIENT_RETRY_NUM, String.valueOf(retries));

    AsyncRpcClient client = new AsyncRpcClient(NettyUtils.getDefaultEventLoopGroup(), rpcConnectionKey,
            connParams);
    try {
        client.connect();
        fail();
    } catch (ConnectTimeoutException e) {
        assertFalse(e.getMessage(), client.isConnected());
    }

    stub = client.getStub();
    stub.echo(future.getController(), echoMessage, future);

    EchoMessage result = null;
    try {
        result = future.get();
    } catch (ExecutionException e) {
    }

    assertEquals(null, result);
    assertTrue(future.isDone());
    assertTrue(future.getController().failed());
    assertNotNull(future.getController().errorText(), future.getController().errorText());
}

From source file:org.apache.tajo.rpc.TestAsyncRpc.java

@Test
@SetupRpcConnection(setupRpcServer = false, setupRpcClient = false)
public void testClientRetryOnStartup() throws Exception {
    retries = 10;/*from w w w. j  ava 2s  .  c  om*/
    ServerSocket serverSocket = new ServerSocket(0);
    final InetSocketAddress address = new InetSocketAddress("127.0.0.1", serverSocket.getLocalPort());
    serverSocket.close();
    service = new DummyProtocolAsyncImpl();

    EchoMessage echoMessage = EchoMessage.newBuilder().setMessage(MESSAGE).build();
    CallFuture<EchoMessage> future = new CallFuture<>();

    //lazy startup
    Thread serverThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                server = new AsyncRpcServer(DummyProtocol.class, service, address, 2);
            } catch (Exception e) {
                fail(e.getMessage());
            }
            server.start();
        }
    });
    serverThread.start();

    RpcConnectionKey rpcConnectionKey = new RpcConnectionKey(address, DummyProtocol.class, true);

    Properties connParams = new Properties();
    connParams.setProperty(RpcConstants.CLIENT_RETRY_NUM, String.valueOf(retries));

    AsyncRpcClient client = manager.newClient(rpcConnectionKey, connParams);
    assertTrue(client.isConnected());

    Interface stub = client.getStub();
    stub.echo(future.getController(), echoMessage, future);

    assertFalse(future.isDone());
    assertEquals(echoMessage, future.get());
    assertTrue(future.isDone());
    client.close();
    server.shutdown(true);
}

From source file:com.cloudant.tests.CloudantClientTests.java

/**
 * Check that the connection timeout throws a SocketTimeoutException when it can't connect
 * within the timeout./*from  w w  w .j a  va2 s.  c o  m*/
 */
@Test(expected = SocketTimeoutException.class)
public void connectionTimeout() throws Throwable {

    ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 1);

    //block the single connection to our server
    Socket socket = new Socket();
    socket.connect(serverSocket.getLocalSocketAddress());

    //now try to connect, but should timeout because there is no connection available
    try {
        CloudantClient c = ClientBuilder.url(new URL("http://127.0.0.1:" + serverSocket.getLocalPort()))
                .connectTimeout(100, TimeUnit.MILLISECONDS).build();

        // Make a request
        c.getAllDbs();
    } catch (CouchDbException e) {
        //unwrap the CouchDbException
        if (e.getCause() != null) {
            //whilst it would be really nice to actually assert that this was a connect
            //exception and not some other SocketTimeoutException there are JVM differences in
            //this respect (i.e. OpenJDK does not appear to distinguish between read/connect)
            //in its exception messages
            throw e.getCause();
        } else {
            throw e;
        }
    } finally {
        //make sure we close the sockets
        IOUtils.closeQuietly(serverSocket);
        IOUtils.closeQuietly(socket);
    }
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void connectTimeout() throws Exception {
    // Pick a free port with no server running
    ServerSocket ss = new ServerSocket(0);
    int serverPort = ss.getLocalPort();
    ss.close();//  w  w w.  ja va  2s . c o m

    set(client + ".niws.client.ConnectTimeout", "100");
    int code = 200;
    statusCode.set(code);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get("niws://test/http://localhost:" + serverPort + "/empty").subscribe(Actions.empty(),
            new Action1<Throwable>() {
                @Override
                public void call(Throwable t) {
                    throwable.set(t);
                    latch.countDown();
                }
            }, new Action0() {
                @Override
                public void call() {
                    latch.countDown();
                }
            });

    latch.await();
    Assert.assertTrue(throwable.get() instanceof ConnectException);
}

From source file:hudson.plugins.selenium.PluginImpl.java

public Object readResolve() {
    // Update from plugin 2.0 to 2.1 where browsers were introduced
    if (rcFirefoxProfileTemplate != null || rcBrowserSessionReuse != null || rcTrustAllSSLCerts != null
            || rcBrowserSideLog != null) {
        String rcFirefoxProfileTemplate = getDefaultForNull(this.rcFirefoxProfileTemplate, "");
        Boolean rcBrowserSessionReuse = getDefaultForNull(this.rcBrowserSessionReuse, Boolean.FALSE);
        Boolean rcTrustAllSSLCerts = getDefaultForNull(this.rcTrustAllSSLCerts, Boolean.FALSE);
        Boolean rcBrowserSideLog = getDefaultForNull(this.rcBrowserSideLog, Boolean.FALSE);

        List<SeleniumBrowser> browsers = new ArrayList<SeleniumBrowser>();
        browsers.add(new IEBrowser(5, "", ""));
        browsers.add(new FirefoxBrowser(5, "", ""));
        browsers.add(new ChromeBrowser(5, "", ""));

        int port = 4445;
        try {//  ww  w.  j  a v  a 2  s .  com
            ServerSocket ss = new ServerSocket(0);
            port = ss.getLocalPort();
            ss.close();
        } catch (IOException e) {
        }

        SeleniumNodeConfiguration c = new CustomRCConfiguration(port, rcBrowserSideLog, rcDebug,
                rcTrustAllSSLCerts, rcBrowserSessionReuse, -1, rcFirefoxProfileTemplate, browsers, null);

        synchronized (configurations) {
            configurations.add(
                    new SeleniumGlobalConfiguration("Selenium v2.0 configuration", new MatchAllMatcher(), c));
        }

    }

    // update to 2.3 where hostname options were introduced
    if (hostnameResolver == null) {
        hostnameResolver = new JenkinsRootHostnameResolver();
    }

    return this;
}

From source file:org.apache.htrace.util.HTracedProcess.java

public HTracedProcess(final File binPath, final File dataDir, final String host) throws IOException {
    // Create a notifier socket bound to a random port.
    ServerSocket listener = new ServerSocket(0);
    boolean success = false;
    Process process = null;/*w w  w  .j  av  a 2  s  .c  o m*/
    try {
        // Use a random port for the web address.  No 'scheme' yet.
        String webAddress = host + ":0";
        String logPath = new File(dataDir, "log.txt").getAbsolutePath();
        // Pass cmdline args to htraced to it uses our test dir for data.
        ProcessBuilder pb = new ProcessBuilder(binPath.toString(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath,
                "-Dweb.address=" + webAddress, "-Ddata.store.clear=true",
                "-Dstartup.notification.address=localhost:" + listener.getLocalPort(),
                "-Ddata.store.directories=" + dataDir.toString());
        pb.redirectErrorStream(true);
        // Inherit STDERR/STDOUT i/o; dumps on console for now.  Can add logs later.
        pb.inheritIO();
        pb.directory(dataDir);
        //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;
        LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr
                + ", logging to " + logPath);
        success = true;
    } finally {
        if (!success) {
            // Clean up after failure
            if (process != null) {
                process.destroy();
                process = null;
            }
        }
        delegate = process;
        listener.close();
    }
}

From source file:TalkServerThread.java

public void start() {
    ServerSocket serverRSocket = null;
    int numConnected = 0;

    try {// ww  w  . j  ava  2 s  . c  o  m
        serverRSocket = new ServerSocket(0);
        System.out.println("TalkServer listening on rendezvous port: "
                           + serverRSocket.getLocalPort());
    } catch (IOException e) {
        System.err.println("Server could not create server socket for rendezvous.");
        return;
    }

    while (true) {

        //Connect to two clients.
        while (numConnected < 2) {
            TalkServerThread tst;
            tst = connectToClient(serverRSocket);
            if (tst != null) {
                numConnected++;
                if (tstList[0] == null) {
                    tstList[0] = tst;
                } else {
                    tstList[1] = tst;
                }
            }
        } //end while (numConnected < 2) loop

        if (DEBUG) {
            try {
                System.out.println("tst #0 = " + tstList[0]);
            } catch (Exception e) {}
            try {
                System.out.println("tst #1 = " + tstList[1]);
            } catch (Exception e) {}
        }

        //If they're really OK, tell them to start writing.
        if (everythingIsOK(0) & everythingIsOK(1)) {
            for (int i = 0; i < 2; i++) {
                writeToStream("START WRITING!\n----------------------"
                              + "-------------", tstList[i].os);
            }
        } else {
            System.err.println("2 server threads created, but "
                               + "not everything is OK");
        }

        while (numConnected == 2) {
            if (!everythingIsOK(0)) {
                if (DEBUG) {
                    System.out.println("Applet #0 is hosed; disconnecting.");
                }
                numConnected--;
                cleanup(tstList[0]);
                tstList[0] = null;
            }
            if (!everythingIsOK(1)) {
                if (DEBUG) {
                    System.out.println("Applet #1 is hosed; disconnecting.");
                }
                numConnected--;
                cleanup(tstList[1]);
                tstList[1] = null;
            }
                   try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            } 
        } //end while(numConnected==2) loop

        if (DEBUG) {
            try {
                System.out.println("Number of connections = " + numConnected);
                System.out.println("tst #0 = " + tstList[0]);
                System.out.println("tst #1 = " + tstList[1]);
            } catch (Exception e) {}
        }

    } //end while (true) loop
}

From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java

/**
 * Finds a free port on the machine.//from   w w  w. ja  va2  s. co m
 *
 * @return
 * @throws IOException
 */
public static int findFreePort() throws IOException {
    ServerSocket socket = new ServerSocket(0);
    int port = socket.getLocalPort();
    socket.close();
    return port;
}

From source file:org.eredlab.g4.ccl.net.bsd.RCommandClient.java

InputStream _createErrorStream() throws IOException {
    int localPort;
    ServerSocket server;
    Socket socket;//from   w  ww .ja v  a  2 s . co m

    localPort = MAX_CLIENT_PORT;
    server = null; // Keep compiler from barfing

    for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort) {
        try {
            server = _socketFactory_.createServerSocket(localPort, 1, getLocalAddress());
        } catch (SocketException e) {
            continue;
        }
        break;
    }

    if (localPort < MIN_CLIENT_PORT)
        throw new BindException("All ports in use.");

    _output_.write(Integer.toString(server.getLocalPort()).getBytes());
    _output_.write('\0');
    _output_.flush();

    socket = server.accept();
    server.close();

    if (isRemoteVerificationEnabled() && !verifyRemote(socket)) {
        socket.close();
        throw new IOException("Security violation: unexpected connection attempt by "
                + socket.getInetAddress().getHostAddress());
    }

    return (new SocketInputStream(socket, socket.getInputStream()));
}