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.eclipse.scanning.test.scan.nexus.MandelbrotRemoteTest.java

/**
 * Checks if a port is free./*from   w w  w. jav  a 2 s.  c  om*/
 * @param port
 * @return
 */
public static boolean isPortFree(int port) {

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
        // Swallow this, it's not free
        return false;
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

}

From source file:com.ngdata.hbaseindexer.mr.HBaseIndexingOptionsTest.java

private static int getFreePort() {
    ServerSocket socket = null;
    try {/*from  w  w w .ja v  a2  s  .co  m*/
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException("Error finding a free port", e);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Error closing ServerSocket used to detect a free port.", e);
            }
        }
    }
}

From source file:org.apache.hama.util.BSPNetUtils.java

/**
 * Checks to see if a specific port is available.
 * /* ww  w .  ja  va 2 s.com*/
 * @param port the port to check for availability
 */
public static boolean available(int port) {
    if (port < 1000 || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

private static int getFreePort() throws IOException {
    ServerSocket serverSocket = new ServerSocket(0);
    int port = serverSocket.getLocalPort();
    serverSocket.close();
    return port;//from  w  w  w . j  av  a2s.  com
}

From source file:org.apache.flink.runtime.clusterframework.BootstrapTools.java

/**
 * Starts an ActorSystem with the given configuration listening at the address/ports.
 * @param configuration The Flink configuration
 * @param listeningAddress The address to listen at.
 * @param portRangeDefinition The port range to choose a port from.
 * @param logger The logger to output log information.
 * @return The ActorSystem which has been started
 * @throws Exception/*from   ww  w .j  a va 2 s. c o  m*/
 */
public static ActorSystem startActorSystem(Configuration configuration, String listeningAddress,
        String portRangeDefinition, Logger logger) throws Exception {

    // parse port range definition and create port iterator
    Iterator<Integer> portsIterator;
    try {
        portsIterator = NetUtils.getPortRangeFromString(portRangeDefinition);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid port range definition: " + portRangeDefinition);
    }

    while (portsIterator.hasNext()) {
        // first, we check if the port is available by opening a socket
        // if the actor system fails to start on the port, we try further
        ServerSocket availableSocket = NetUtils.createSocketFromPorts(portsIterator,
                new NetUtils.SocketFactory() {
                    @Override
                    public ServerSocket createSocket(int port) throws IOException {
                        return new ServerSocket(port);
                    }
                });

        int port;
        if (availableSocket == null) {
            throw new BindException("Unable to allocate further port in port range: " + portRangeDefinition);
        } else {
            port = availableSocket.getLocalPort();
            try {
                availableSocket.close();
            } catch (IOException ignored) {
            }
        }

        try {
            return startActorSystem(configuration, listeningAddress, port, logger);
        } catch (Exception e) {
            // we can continue to try if this contains a netty channel exception
            Throwable cause = e.getCause();
            if (!(cause instanceof org.jboss.netty.channel.ChannelException
                    || cause instanceof java.net.BindException)) {
                throw e;
            } // else fall through the loop and try the next port
        }
    }

    // if we come here, we have exhausted the port range
    throw new BindException("Could not start actor system on any port in port range " + portRangeDefinition);
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

public static int getFreePort() throws IOException {
    ServerSocket serverSocket = new ServerSocket(0);
    int port = serverSocket.getLocalPort();
    serverSocket.close();
    return port;//  ww  w .ja v  a2 s  . c o  m
}

From source file:org.apache.smscserver.test.TestUtil.java

/**
 * Attempts to find a free port//  ww w.  j  a  va 2s. c  o m
 * 
 * @param initPort
 *            The first port to try, before resolving to brute force searching
 * @throws IOException
 * 
 * @throws IOException
 */
public static int findFreePort(int initPort) throws IOException {
    int port = -1;
    ServerSocket tmpSocket = null;
    // first try the default port
    try {
        tmpSocket = new ServerSocket(initPort);

        port = initPort;

        System.out.println("Using default port: " + port);
    } catch (IOException e) {
        System.out.println("Failed to use specified port");
        // didn't work, try to find one dynamically
        try {
            int attempts = 0;

            while ((port < 1024) && (attempts < 2000)) {
                attempts++;

                tmpSocket = new ServerSocket(0);

                port = tmpSocket.getLocalPort();
            }

        } catch (IOException e1) {
            throw new IOException("Failed to find a port to use for testing: " + e1.getMessage());
        }
    } finally {
        if (tmpSocket != null) {
            try {
                tmpSocket.close();
            } catch (IOException e) {
                // ignore
            }
            tmpSocket = null;
        }
    }

    return port;
}

From source file:org.lnicholls.galleon.util.Tools.java

public static int findAvailablePort(int port) {
    if (log.isDebugEnabled())
        log.debug("findAvailablePort: " + port);
    for (int i = 0; i < 100; i++) {
        try {//from   w  ww .  j  a  v a2 s  .c  o m
            if (log.isDebugEnabled())
                log.debug("Trying port " + port);
            ServerSocket serverSocket = new ServerSocket(port);
            serverSocket.close();
            serverSocket = null;
            break;
        } catch (Exception ex) {
            if (log.isDebugEnabled())
                log.debug("Port " + port + " is already in use.");
            port = port + 1;
        }
    }
    return port;
}

From source file:org.sonar.process.BaseProcessTest.java

@Before
public void setup() throws IOException {
    ServerSocket socket = new ServerSocket(0);
    freePort = socket.getLocalPort();//from w  w  w  .j  ava 2  s. co  m
    socket.close();

    dummyAppJar = FileUtils.toFile(getClass().getResource("/sonar-dummy-app.jar"));
}

From source file:org.apache.ftpserver.test.TestUtil.java

/**
 * Attempts to find a free port//  ww  w .java2 s.c  om
 * @param initPort The first port to try, before resolving to 
 *   brute force searching
 * @throws IOException
 * 
 * @throws IOException
 */
public static int findFreePort(int initPort) throws IOException {
    int port = -1;
    ServerSocket tmpSocket = null;
    // first try the default port
    try {
        tmpSocket = new ServerSocket(initPort);

        port = initPort;

        System.out.println("Using default port: " + port);
    } catch (IOException e) {
        System.out.println("Failed to use specified port");
        // didn't work, try to find one dynamically
        try {
            int attempts = 0;

            while (port < 1024 && attempts < 2000) {
                attempts++;

                tmpSocket = new ServerSocket(0);

                port = tmpSocket.getLocalPort();
            }

        } catch (IOException e1) {
            throw new IOException("Failed to find a port to use for testing: " + e1.getMessage());
        }
    } finally {
        if (tmpSocket != null) {
            try {
                tmpSocket.close();
            } catch (IOException e) {
                // ignore
            }
            tmpSocket = null;
        }
    }

    return port;
}