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.adito.install.forms.WebServerForm.java

private static boolean isHostAndPortValid(String address, int port) {
    ServerSocket socket = null;
    try {// w ww .  j a va  2s. c om
        if (log.isInfoEnabled())
            log.info("Testing listener on " + address + ":" + port);
        socket = new ServerSocket(port, 0, InetAddress.getByName(address));
        return true;
    } catch (IOException e) {
        log.error("Failed to setup server socket.", e);
        return false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:helma.main.Server.java

/**
 *  Check whether a server port is available by trying to open a server socket
 *//*from  w  w w  . j a  va2 s . c om*/
private static void checkPort(InetSocketAddress endpoint) throws IOException {
    try {
        ServerSocket sock = new ServerSocket();
        sock.bind(endpoint);
        sock.close();
    } catch (IOException x) {
        throw new IOException("Error binding to " + endpoint + ": " + x.getMessage());
    }
}

From source file:org.codemucker.testserver.TestServer.java

public static int findFreePort(String hostNameOrIP) throws UnknownHostException {
    if (hostNameOrIP != null && hostNameOrIP.trim().length() == 0) {
        hostNameOrIP = null;/*from  www . ja  va 2 s.c o m*/
    }
    ServerSocket sock = null;
    try {
        // only need a single connection to find a free port
        sock = new ServerSocket(0, 1, hostNameOrIP == null ? null : InetAddress.getByName(hostNameOrIP));
        // free this port up pronto when we close it
        sock.setReuseAddress(true);
        return sock.getLocalPort();
    } catch (final IOException e) {
        throw new RuntimeException(
                "Can't free port for host " + hostNameOrIP + "(null means to find any local host)", e);
    } finally {
        if (sock != null) {
            try {
                sock.close();
            } catch (final IOException e) {
                // ignore, we don't really care
            }
        }
    }
}

From source file:org.kawanfw.sql.tomcat.TomcatStarterUtil.java

/**
 * Checks to see if a specific port is available.
 * /* w w w  .j  a  v  a2s.co m*/
 * @param port
 *            the port to check for availability
 */
public static boolean available(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) {
        // e.printStackTrace();
    } 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.helix.TestHelper.java

public static int getRandomPort() throws IOException {
    ServerSocket sock = new ServerSocket();
    sock.bind(null);//from www.j a  va 2 s  .  c o  m
    int port = sock.getLocalPort();
    sock.close();
    return port;
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Return a free port number. There is no guarantee it will remain free, so it should be used immediately.
 *
 * @returns A free port for binding a local socket
 *///  w w  w.  j  a va2s .  c o m
public static int getFreeSocketPort() {
    int port = 0;
    try {
        ServerSocket s = new ServerSocket(0);
        port = s.getLocalPort();
        s.close();
        return port;
    } catch (IOException e) {
        // Could not get a free port. Return default port 0.
    }
    return port;
}

From source file:org.paxml.selenium.rc.XSelenium.java

private static int getAvailablePort() {
    ServerSocket s = null;

    try {/*from w  w w. j  a v a  2s  .  c om*/
        s = new ServerSocket(0);
        return s.getLocalPort();
    } catch (IOException e) {
        throw new PaxmlRuntimeException(e);
    } finally {
        try {
            if (s != null) {
                s.close();
            }
        } catch (Exception e) {
            log.warn("Cannot close server socket of port: " + s.getLocalPort(), e);
        }
    }

}

From source file:net.grinder.util.NetworkUtils.java

/**
 * Check if the given port is available.
 *
 * @param inetAddress address to be bound
 * @param port        port to be checked
 * @return true if available/*from ww w.j  a v a 2s.c  o  m*/
 */
private static boolean checkExactPortAvailability(InetAddress inetAddress, int port) {
    ServerSocket socket = null;
    try {
        if (inetAddress == null) {
            socket = new ServerSocket(port);
        } else {
            socket = new ServerSocket(port, 1, inetAddress);
        }
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // FALL THROUGH
                noOp();
            }
        }
    }
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;/*from w ww  .ja  v a  2 s.c om*/

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:net.mybox.mybox.Common.java

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 *//* w w w . ja va2  s.com*/
public static boolean portAvailable(int port) {
    if (port < 0 || port > 65535) {
        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;
}