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:com.evolveum.midpoint.repo.sql.SqlRepositoryFactory.java

private void checkPort(int port) throws RepositoryServiceFactoryException {
    if (port >= 65635 || port < 0) {
        throw new RepositoryServiceFactoryException("Port must be in range 0-65634, not '" + port + "'.");
    }/*from   w  ww. ja  va  2  s. c o m*/

    ServerSocket ss = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
    } catch (BindException e) {
        throw new RepositoryServiceFactoryException("Configured port (" + port + ") for H2 already in use.", e);
    } catch (IOException e) {
        LOGGER.error("Reported IO error, while binding ServerSocket to port " + port
                + " used to test availability " + "of port for H2 Server", e);
    } finally {
        try {
            if (ss != null) {
                ss.close();
            }
        } catch (IOException ex) {
            LOGGER.error("Reported IO error, while closing ServerSocket used to test availability "
                    + "of port for H2 Server", ex);
        }
    }
}

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

/**
 * Gets a free server socket port.// w w w.  j av  a2s  . c  om
 *
 * @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.hadoop.hive.metastore.MetaStoreUtils.java

/**
 * Finds a free port on the machine.//from w w  w  .ja va  2 s  . c o  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:com.adeptj.runtime.server.Server.java

private boolean isPortAvailable(int port) {
    boolean portAvailable = false;
    ServerSocket socket = null;
    try (ServerSocketChannel socketChannel = ServerSocketChannel.open()) {
        socket = socketChannel.socket();
        socket.setReuseAddress(true);// ww  w . j a v a2  s .c  o  m
        socket.bind(new InetSocketAddress(port));
        portAvailable = true;
    } catch (BindException ex) {
        LOGGER.error("BindException while acquiring port: [{}], cause:", port, ex);
    } catch (IOException ex) {
        LOGGER.error("IOException while acquiring port: [{}], cause:", port, ex);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException ex) {
                LOGGER.error("IOException while closing socket!!", ex);
            }
        }
    }
    return portAvailable;
}

From source file:org.apache.hadoop.hbase.fs.TestBlockReorder.java

/**
 * Test that we're can add a hook, and that this hook works when we try to read the file in HDFS.
 *//*from   w w w .j  a  v  a  2s  .c  o  m*/
@Test
public void testBlockLocationReorder() throws Exception {
    Path p = new Path("hello");

    Assert.assertTrue((short) cluster.getDataNodes().size() > 1);
    final int repCount = 2;

    // Let's write the file
    FSDataOutputStream fop = dfs.create(p, (short) repCount);
    final double toWrite = 875.5613;
    fop.writeDouble(toWrite);
    fop.close();

    // Let's check we can read it when everybody's there
    long start = System.currentTimeMillis();
    FSDataInputStream fin = dfs.open(p);
    Assert.assertTrue(toWrite == fin.readDouble());
    long end = System.currentTimeMillis();
    LOG.info("readtime= " + (end - start));
    fin.close();
    Assert.assertTrue((end - start) < 30 * 1000);

    // Let's kill the first location. But actually the fist location returned will change
    // The first thing to do is to get the location, then the port
    FileStatus f = dfs.getFileStatus(p);
    BlockLocation[] lbs;
    do {
        lbs = dfs.getFileBlockLocations(f, 0, 1);
    } while (lbs.length != 1 && lbs[0].getLength() != repCount);
    final String name = lbs[0].getNames()[0];
    Assert.assertTrue(name.indexOf(':') > 0);
    String portS = name.substring(name.indexOf(':') + 1);
    final int port = Integer.parseInt(portS);
    LOG.info("port= " + port);
    int ipcPort = -1;

    // Let's find the DN to kill. cluster.getDataNodes(int) is not on the same port, so we need
    // to iterate ourselves.
    boolean ok = false;
    final String lookup = lbs[0].getHosts()[0];
    StringBuilder sb = new StringBuilder();
    for (DataNode dn : cluster.getDataNodes()) {
        final String dnName = getHostName(dn);
        sb.append(dnName).append(' ');
        if (lookup.equals(dnName)) {
            ok = true;
            LOG.info("killing datanode " + name + " / " + lookup);
            ipcPort = dn.ipcServer.getListenerAddress().getPort();
            dn.shutdown();
            LOG.info("killed datanode " + name + " / " + lookup);
            break;
        }
    }
    Assert.assertTrue("didn't find the server to kill, was looking for " + lookup + " found " + sb, ok);
    LOG.info("ipc port= " + ipcPort);

    // Add the hook, with an implementation checking that we don't use the port we've just killed.
    Assert.assertTrue(HFileSystem.addLocationsOrderInterceptor(conf, new HFileSystem.ReorderBlocks() {
        @Override
        public void reorderBlocks(Configuration c, LocatedBlocks lbs, String src) {
            for (LocatedBlock lb : lbs.getLocatedBlocks()) {
                if (lb.getLocations().length > 1) {
                    if (lb.getLocations()[0].getHostName().equals(lookup)) {
                        LOG.info("HFileSystem bad host, inverting");
                        DatanodeInfo tmp = lb.getLocations()[0];
                        lb.getLocations()[0] = lb.getLocations()[1];
                        lb.getLocations()[1] = tmp;
                    }
                }
            }
        }
    }));

    final int retries = 10;
    ServerSocket ss = null;
    ServerSocket ssI;
    try {
        ss = new ServerSocket(port);// We're taking the port to have a timeout issue later.
        ssI = new ServerSocket(ipcPort);
    } catch (BindException be) {
        LOG.warn("Got bind exception trying to set up socket on " + port + " or " + ipcPort
                + ", this means that the datanode has not closed the socket or"
                + " someone else took it. It may happen, skipping this test for this time.", be);
        if (ss != null) {
            ss.close();
        }
        return;
    }

    // Now it will fail with a timeout, unfortunately it does not always connect to the same box,
    // so we try retries times;  with the reorder it will never last more than a few milli seconds
    for (int i = 0; i < retries; i++) {
        start = System.currentTimeMillis();

        fin = dfs.open(p);
        Assert.assertTrue(toWrite == fin.readDouble());
        fin.close();
        end = System.currentTimeMillis();
        LOG.info("HFileSystem readtime= " + (end - start));
        Assert.assertFalse("We took too much time to read", (end - start) > 60000);
    }

    ss.close();
    ssI.close();
}

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

InputStream _createErrorStream() throws IOException {
    int localPort;
    ServerSocket server;
    Socket socket;//from  w ww .j av a 2 s . com

    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()));
}

From source file:org.spark.examples.events.EventGenerator.java

/**
 * Launch the generator./*from  w  w w .  ja va 2 s  .c o m*/
 * @param authPort Port for authentication related information.
 * @param webPort Port for web related information.
 */
public void startGenerator(int authPort, int webPort) {
    ServerSocket authSocket = null;
    ServerSocket webSocket = null;
    Socket authClient = null;
    Socket webClient = null;
    try {
        System.out.println("Waiting for clients ...");
        authSocket = new ServerSocket(authPort);
        webSocket = new ServerSocket(webPort);
        authClient = authSocket.accept();
        System.out.println("Auth client connected");
        webClient = webSocket.accept();
        System.out.println("Web client connected");
    } catch (IOException e) {
        e.printStackTrace();
    }

    sendEvents(authClient, webClient);

    try {
        if (authClient != null) {
            authClient.close();
        }
        if (webClient != null) {
            webClient.close();
        }
        if (authSocket != null) {
            authSocket.close();
        }
        if (webSocket != null) {
            webSocket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:uk.ac.sanger.cgp.dbcon.support.NanoHttpd.java

/**
 * Starts a HTTP server to given port./*from w ww .  j  a va 2  s.c o  m*/
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHttpd(int port, boolean ignoreIfAlreadyBound) throws IOException {
    myTcpPort = port;

    try {
        final ServerSocket ss = new ServerSocket(myTcpPort);
        Thread t = new Thread(new Runnable() {
            public void run() {
                try {
                    while (true) {
                        if (closeServer) {
                            break;
                        }
                        new HTTPSession(ss.accept());
                    }
                    ss.close();
                } catch (IOException e) {
                    getLog().error("Problem with IO", e);
                }
            }
        });
        t.setDaemon(true);
        t.start();
    } catch (BindException e) {
        if (!ignoreIfAlreadyBound) {
            throw e;
        }
    }
}

From source file:com.google.dart.tools.core.DartCore.java

/**
 * Find and return an unused server socket port.
 *//*w  w w. j a  va  2 s.co  m*/
public static int findUnusedPort() {
    try {
        ServerSocket ss = new ServerSocket(0);
        int port = ss.getLocalPort();
        ss.close();
        return port;
    } catch (IOException ioe) {
        //$FALL-THROUGH$
    }
    return -1;
}

From source file:org.apache.hadoop.hdfs.server.namenode.AvatarNode.java

/**
 * Tries to bind to the address specified in ZooKeeper, this will always fail
 * if the primary is alive either on the same machine or on a remote machine.
 *//*from   ww  w.j  a va2 s .c  o  m*/
private static void isPrimaryAlive(String zkRegistry) throws IOException {
    String parts[] = zkRegistry.split(":");
    if (parts.length != 2) {
        throw new IllegalArgumentException("Invalid Address : " + zkRegistry);
    }
    String host = parts[0];
    int port = Integer.parseInt(parts[1]);
    InetSocketAddress clientSocket = new InetSocketAddress(host, port);
    ServerSocket socket = new ServerSocket();
    socket.bind(clientSocket);
    socket.close();
}