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:org.springframework.integration.ip.util.SocketUtils.java

public static int findAvailableServerSocket(int seed) {
    for (int i = seed; i < seed + 200; i++) {
        try {//from   w  ww . j  ava2  s  . com
            ServerSocket sock = ServerSocketFactory.getDefault().createServerSocket(i);
            sock.close();
            return i;
        } catch (Exception e) {
        }
    }
    throw new RuntimeException("Cannot find a free server socket");
}

From source file:ubicrypt.core.TestUtils.java

/**
 * Returns a free port number on localhost.
 *
 * <p>Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT
 * just because of this). Slightly improved with stop() missing in JDT. And throws exception
 * instead of returning -1.//w w w .  j a  va  2s . c o m
 *
 * @return a free port number on localhost
 * @throws IllegalStateException if unable to find a free port
 */
public static int findFreePort() {
    ServerSocket socket = null;
    do {
        try {
            final int port = ThreadLocalRandom.current().nextInt(49152, 65535 + 1);
            socket = new ServerSocket(port);
            socket.setReuseAddress(false);
            try {
                socket.close();
            } catch (final IOException e) {
                // Ignore IOException on stop()
            }
            return port;
        } catch (final IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (final IOException e) {
                }
            }
        }
    } while (true);
}

From source file:org.apache.servicemix.http.HttpWsdlTest.java

/**
 * determines a free port number//w  w w  .j  av  a2s  .  c  om
 * @return a free port number
 */
private static int getFreePortNumber() {

    int portNumber = usedPortNumber + 1;
    boolean inUse = true;

    while (inUse) {
        try {
            ServerSocket serverSocket = new ServerSocket();
            SocketAddress endpoint = new InetSocketAddress(portNumber);
            serverSocket.bind(endpoint);
            serverSocket.close();
            inUse = false;
            usedPortNumber = portNumber;
        } catch (IOException e) {
            inUse = true;
        }
    }

    return portNumber;

}

From source file:org.apache.pulsar.functions.utils.Utils.java

public static int findAvailablePort() {
    // The logic here is a little flaky. There is no guarantee that this
    // port returned will be available later on when the instance starts
    // TODO(sanjeev):- Fix this
    try {//www  .  j  a va 2s  .c o m
        ServerSocket socket = new ServerSocket(0);
        int port = socket.getLocalPort();
        socket.close();
        return port;
    } catch (IOException ex) {
        throw new RuntimeException("No free port found", ex);
    }
}

From source file:com.graphaware.test.util.TestUtils.java

/**
 * Get some available port./*w w  w.  j ava 2s .c  om*/
 *
 * @return port number.
 */
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);
    }
}

From source file:org.alfresco.util.PortUtil.java

/**
 * Check if specified port is free.//from   w w w . j  a  v  a  2  s  .  c om
 * @param port Port number to check.
 * @param host A local address to bind to; if null, "" or "0.0.0.0" then all local addresses will be considered.
 */
public static void checkPort(int port, String host) throws IOException {
    ServerSocket serverSocket = null;

    try {
        if (host != null && !host.equals("") && !"0.0.0.0".equals(host.trim())) {
            serverSocket = new ServerSocket(port, 0, InetAddress.getByName(host.trim()));
        } else {
            serverSocket = new ServerSocket(port);
        }
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException ioe) {
                if (logger.isDebugEnabled()) {
                    logger.debug(ioe.toString());
                }
            }
        }
    }
}

From source file:com.github.avarabyeu.restendpoint.http.GuiceTestModule.java

private static int findFreePort() {
    ServerSocket socket = null;
    try {//from  w  w  w. j a  v a2s  . com
        socket = new ServerSocket(0);
        System.out.println("Used Port: " + socket.getLocalPort());
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException("Unable to find free port", e);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }
}

From source file:org.apache.sentry.service.thrift.SentryService.java

private static int findFreePort() {
    int attempts = 0;
    while (attempts++ <= 1000) {
        try {/*  w ww .j ava 2  s  .  c o  m*/
            ServerSocket s = new ServerSocket(0);
            int port = s.getLocalPort();
            s.close();
            return port;
        } catch (IOException e) {
            // ignore and retry
        }
    }
    throw new IllegalStateException("Unable to find a port after 1000 attempts");
}

From source file:org.apache.beam.sdk.io.jdbc.JdbcIOTest.java

@BeforeClass
public static void startDatabase() throws Exception {
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();/*w w w. j  a v  a  2s  .com*/
    socket.close();

    LOG.info("Starting Derby database on {}", port);

    // by default, derby uses a lock timeout of 60 seconds. In order to speed up the test
    // and detect the lock faster, we decrease this timeout
    System.setProperty("derby.locks.waitTimeout", "2");
    System.setProperty("derby.stream.error.file", "target/derby.log");

    derbyServer = new NetworkServerControl(InetAddress.getByName("localhost"), port);
    StringWriter out = new StringWriter();
    derbyServer.start(new PrintWriter(out));
    boolean started = false;
    int count = 0;
    // Use two different methods to detect when server is started:
    // 1) Check the server stdout for the "started" string
    // 2) wait up to 15 seconds for the derby server to start based on a ping
    // on faster machines and networks, this may return very quick, but on slower
    // networks where the DNS lookups are slow, this may take a little time
    while (!started && count < 30) {
        if (out.toString().contains("started")) {
            started = true;
        } else {
            count++;
            Thread.sleep(500);
            try {
                derbyServer.ping();
                started = true;
            } catch (Throwable t) {
                // ignore, still trying to start
            }
        }
    }

    dataSource = new ClientDataSource();
    dataSource.setCreateDatabase("create");
    dataSource.setDatabaseName("target/beam");
    dataSource.setServerName("localhost");
    dataSource.setPortNumber(port);

    readTableName = DatabaseTestHelper.getTestTableName("UT_READ");

    DatabaseTestHelper.createTable(dataSource, readTableName);
    addInitialData(dataSource, readTableName);
}

From source file:org.apache.marmotta.platform.core.test.base.JettyMarmotta.java

public static boolean isPortAvailable(final int port) {
    ServerSocket ss = null;
    try {/*from  w w  w . j av a2  s.  co m*/
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        return true;
    } catch (final IOException e) {

    } finally {
        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {

            }
        }
    }
    return false;
}