Example usage for java.net ServerSocket close

List of usage examples for java.net ServerSocket close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:hudson.gridmaven.gridlayer.PluginImpl.java

/**
 * Compute the host name that Hadoop nodes can be used to talk to Name node.
 *
 * <p>/*  ww w .j  av a2  s.  c  o 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.vaadin.testbenchsauce.BaseTestBenchTestCase.java

private static int findFreePort() {
    ServerSocket socket = null;
    try {/*from  www . j  a  va 2 s  . co  m*/
        socket = new ServerSocket(0);
        socket.setReuseAddress(true);
        int port = socket.getLocalPort();
        try {
            socket.close();
        } catch (IOException e) {
            // Ignore IOException on close()
        }
        return port;
    } catch (IOException ignored) {
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException ignored) {
            }
        }
    }
    throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on");
}

From source file:org.apache.flink.runtime.taskmanager.TaskManager.java

/**
 * Searches for an available free port and returns the port number.
 * /*from   ww  w  .jav  a  2 s .c o  m*/
 * @return An available port.
 * @throws RuntimeException Thrown, if no free port was found.
 */
private static int getAvailablePort() {
    for (int i = 0; i < 50; i++) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            if (port != 0) {
                return port;
            }
        } catch (IOException e) {

            LOG.debug("Unable to allocate port with exception {}", e);
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (Throwable t) {
                }
            }
        }
    }

    throw new RuntimeException("Could not find a free permitted port on the machine.");
}

From source file:io.tilt.minka.domain.NetworkShardIDImpl.java

private void testPort() {
    ServerSocket socket = null;
    try {//from w ww .  j a  v  a  2 s  .c  om
        socket = new ServerSocket(port);
        logger.info("{}: Testing host {} port {} OK", getClass().getSimpleName(), sourceHost, port);
    } catch (IOException e) {
        throw new IllegalArgumentException("Testing port cannot be opened: " + port, e);
    } finally {
        if (socket != null && !socket.isBound()) {
            throw new IllegalArgumentException("Testing port cannot be opened: " + port);
        } else if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new IllegalArgumentException("Testing port cannot be tested: " + port);
            }
        }
    }
}

From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java

public int findFreePort() {
    ServerSocket socket = null;
    try {//from ww w .  j a v  a2  s  .  c om
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException localIOException2) {
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException localIOException4) {
            }
        }
    }
    return -1;
}

From source file:brooklyn.util.ssh.BashCommandsIntegrationTest.java

License:asdf

@Test(groups = "Integration", dependsOnMethods = "testSudo")
public void testWaitForPortFreeWhenNotAbortingOnTimeout() throws Exception {
    ServerSocket serverSocket = openServerSocket();
    try {//from  w  w  w .ja  v  a 2  s .  co m
        int port = serverSocket.getLocalPort();
        String cmd = BashCommands.waitForPortFree(port, Duration.ONE_SECOND, false);

        String output = execRequiringZeroAndReturningStdout(loc, cmd).get();
        assertTrue(output.contains(port + " still in use"), "output=" + output);

        serverSocket.close();
        assertTrue(Networking.isPortAvailable(port));
        String output2 = execRequiringZeroAndReturningStdout(loc, cmd).get();
        assertFalse(output2.contains("still in use"), "output=" + output2);
    } finally {
        serverSocket.close();
    }
}

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

@Test(timeout = 60000)
@SetupRpcConnection(setupRpcServer = false, setupRpcClient = false)
public void testClientRetryFailureOnStartup() throws Exception {
    retries = 2;//from ww w.j av a 2 s .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;//ww  w.  ja  v  a2 s  .  com
    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.endpoint.lg.browser.service.BrowserInstance.java

/**
 * Finds an available debug port/*from   w w w  .j a  v a 2s . c om*/
 *
 * This could fail, if we find a port and something steals it before we get
 * a browser listening on it. This seems unlikely. Note that chromium
 * doesn't fail if its assigned debug port is unavailable (at least so far
 * as I can tell)
 */
private int findDebugPort() {
    int debugPort = 0;
    ServerSocket s = null;

    for (int i = MIN_DEBUG_PORT; i < MAX_DEBUG_PORT; i++) {
        try {
            s = new ServerSocket(i);
            s.setReuseAddress(true);
            debugPort = i;
        } catch (IOException e) {
            // Port isn't available
            getLog().debug("Port " + i + " isn't available");
        } finally {
            try {
                if (s != null) {
                    s.close();
                }
            } catch (IOException e) {
                // s wasn't opened. Don't throw this
            }
        }
        if (debugPort != 0)
            break;
    }
    if (debugPort == 0) {
        getLog().error("Couldn't find unused debug port for new browser activity");
        return 0;
    }
    getLog().debug("Found debug port " + debugPort + " for new browser instance");
    return debugPort;
}

From source file:org.apache.axis2.clustering.tribes.WkaBasedMembershipScheme.java

private int getLocalPort(ServerSocket socket, String hostname, int port) throws IOException {
    InetSocketAddress addr;/*www  . jav  a2s  .  co m*/
    addr = new InetSocketAddress(hostname, port);
    socket.bind(addr);
    log.info("Receiver Server Socket bound to:" + addr);
    socket.setSoTimeout(5);
    socket.close();
    try {
        Thread.sleep(100);
    } catch (InterruptedException ignored) {
        ignored.printStackTrace();
    }
    return port;
}