Example usage for java.net ServerSocket getLocalPort

List of usage examples for java.net ServerSocket getLocalPort

Introduction

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

Prototype

public int getLocalPort() 

Source Link

Document

Returns the port number on which this socket is listening.

Usage

From source file:VASSAL.launch.ModuleManager.java

public static void main(String[] args) {
    // FIXME: We need to catch more exceptions in main() and then exit in
    // order to avoid situations where the main thread ends due to an uncaught
    // exception, but there are other threads still running, and so VASSAL
    // does not quit. For example, this can happen if an IllegalArgumentException
    // is thrown here...

    // parse command-line arguments
    LaunchRequest lr = null;//from  w  w  w.  ja va  2s .  c o m
    try {
        lr = LaunchRequest.parseArgs(args);
    } catch (LaunchRequestException e) {
        // FIXME: should be a dialog...
        System.err.println("VASSAL: " + e.getMessage());
        System.exit(1);
    }

    // do this before the graphics subsystem fires up or it won't stick
    System.setProperty("swing.boldMetal", "false");

    if (lr.mode == LaunchRequest.Mode.TRANSLATE) {
        // show the translation window in translation mode
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // FIXME: does this window exit on close?
                new TranslateVassalWindow(null).setVisible(true);
            }
        });
        return;
    }

    //
    // How we start exactly one request server:
    //
    // To ensure that exactly one process acts as the request server, we
    // acquire a lock on the ~/VASSAL/key file, and then attempt to acquire
    // a lock on the ~/VASSAL/lock file. If we cannot lock ~/VASSAL/lock,
    // then there is already a server running; in that case, we read the
    // port number and security key from ~/VASSAL/key. If we can lock
    // ~/VASSAL/lock, then we start the server, write the port number and
    // key to ~/VASSAL/key, and continue to hold the lock on ~/VASSAL/lock.
    // Finally, we unlock ~/VASSAL/key and proceed to act as a client,
    // sending requests over localhost:port using the security key.
    //
    // The advantages of this method are:
    //
    // (1) No race conditions between processes started at the same time.
    // (2) No port collisions, because we don't use a predetermined port.
    //

    final File keyfile = new File(Info.getConfDir(), "key");
    final File lockfile = new File(Info.getConfDir(), "lock");

    int port = 0;
    long key = 0;

    RandomAccessFile kraf = null;
    FileLock klock = null;
    try {
        // acquire an exclusive lock on the key file
        kraf = new RandomAccessFile(keyfile, "rw");

        try {
            klock = kraf.getChannel().lock();
        } catch (OverlappingFileLockException e) {
            throw (IOException) new IOException().initCause(e);
        }

        // determine whether we are the server or a client

        // Note: We purposely keep lout open in the case where we are the
        // server, because closing lout will release the lock.
        FileLock lock = null;
        final FileOutputStream lout = new FileOutputStream(lockfile);
        try {
            lock = lout.getChannel().tryLock();
        } catch (OverlappingFileLockException e) {
            throw (IOException) new IOException().initCause(e);
        }

        if (lock != null) {
            // we have the lock, so we will be the request server

            // bind to an available port on the loopback device
            final ServerSocket serverSocket = new ServerSocket(0, 0, InetAddress.getByName(null));

            // write the port number where we listen to the key file
            port = serverSocket.getLocalPort();
            kraf.writeInt(port);

            // create new security key and write it to the key file
            key = (long) (Math.random() * Long.MAX_VALUE);
            kraf.writeLong(key);

            // create a new Module Manager
            new ModuleManager(serverSocket, key, lout, lock);
        } else {
            // we do not have the lock, so we will be a request client
            lout.close();

            // read the port number we will connect to from the key file
            port = kraf.readInt();

            // read the security key from the key file
            key = kraf.readLong();
        }

        kraf.close();
    } catch (IOException e) {
        // FIXME: should be a dialog...
        System.err.println("VASSAL: IO error");
        e.printStackTrace();
        System.exit(1);
    } finally {
        // this will also release the lock on the key file
        IOUtils.closeQuietly(kraf);
    }

    lr.key = key;

    // pass launch parameters on to the ModuleManager via the socket
    Socket clientSocket = null;
    ObjectOutputStream out = null;
    InputStream in = null;
    try {
        clientSocket = new Socket((String) null, port);

        out = new ObjectOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
        out.writeObject(lr);
        out.flush();

        in = clientSocket.getInputStream();
        IOUtils.copy(in, System.err);
    } catch (IOException e) {
        // FIXME: should be a dialog...
        System.err.println("VASSAL: Problem with socket on port " + port);
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly((Closeable) out);
        IOUtils.closeQuietly(clientSocket);
    }
}

From source file:org.superbiz.moviefun.MoviesHtmlUnitTest.java

@BeforeClass
public static void start() throws IOException {

    // get a random unused port to use for http requests
    ServerSocket server = new ServerSocket(0);
    port = server.getLocalPort();
    server.close();/*from  www .ja va2 s .  com*/

    webApp = createWebApp();
    Properties p = new Properties();
    p.setProperty(EJBContainer.APP_NAME, "moviefun");
    p.setProperty(EJBContainer.PROVIDER, "tomee-embedded"); // need web feature
    p.setProperty(EJBContainer.MODULES, webApp.getAbsolutePath());
    p.setProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT, String.valueOf(port));
    container = EJBContainer.createEJBContainer(p);
}

From source file:org.sonar.plugins.email.EmailSendingTest.java

private static int getNextAvailablePort() {
    try {/*from   w  ww  .j a v  a 2 s. co m*/
        ServerSocket socket = new ServerSocket(0);
        int unusedPort = socket.getLocalPort();
        socket.close();
        return unusedPort;
    } catch (IOException e) {
        throw new RuntimeException("Error getting an available port from system", e);
    }
}

From source file:com.alibaba.jstorm.utils.NetWorkUtils.java

/**
 * Check whether the port is available to binding
 * /*  w ww .  jav  a  2s .co m*/
 * @param port
 * @return -1 means not available, others means available
 * @throws IOException
 */
public static int tryPort(int port) throws IOException {
    ServerSocket socket = new ServerSocket(port);
    int rtn = socket.getLocalPort();
    socket.close();
    return rtn;
}

From source file:com.netflix.explorers.helloworld.ExplorerAppTest.java

private static int getLocalPort() throws IOException {
    ServerSocket ss = new ServerSocket(0);
    ss.setReuseAddress(true);//  w ww  . j a v  a  2  s. c o m
    return ss.getLocalPort();
}

From source file:org.apache.cloudstack.network.contrail.management.TestDbSetup.java

public static int findFreePort() throws Exception {

    int port;/*  ww  w  .  j  ava2  s .co  m*/
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();

    return port;
}

From source file:org.glowroot.agent.plugin.netty.NettyIT.java

private static int getAvailablePort() throws Exception {
    ServerSocket serverSocket = new ServerSocket(0);
    int port = serverSocket.getLocalPort();
    serverSocket.close();/*from  www .  j  a va2  s .co m*/
    return port;
}

From source file:com.barchart.netty.rest.client.TestRestClientBase.java

@BeforeClass
public static void init() throws Exception {

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();
    s.close();//from  w w  w .  j av  a2s  .  co  m

    handler = new TestRequestHandler();

    server = new HttpServer().requestHandler("/test", handler);

    server.listen(port).sync();

    client = new RestClientBase("http://localhost:" + port) {
    };

}

From source file:io.vertx.ext.consul.dc.ConsulAgent.java

private static int getFreePort() {
    int port = -1;
    try {/*from w w  w .j av a2  s  .  com*/
        ServerSocket socket = new ServerSocket(0);
        port = socket.getLocalPort();
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return port;
}

From source file:org.apache.hadoop.net.ServerSocketUtil.java

/**
 * Find the specified number of unique ports available.
 * The ports are all closed afterwards,//from   w  w w  .j a v  a 2s .c  o  m
 * so other network services started may grab those same ports.
 *
 * @param numPorts number of required port nubmers
 * @return array of available port numbers
 * @throws IOException
 */
public static int[] getPorts(int numPorts) throws IOException {
    ServerSocket[] sockets = new ServerSocket[numPorts];
    int[] ports = new int[numPorts];
    for (int i = 0; i < numPorts; i++) {
        ServerSocket sock = new ServerSocket(0);
        sockets[i] = sock;
        ports[i] = sock.getLocalPort();
    }
    for (ServerSocket sock : sockets) {
        sock.close();
    }
    return ports;
}