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:org.apache.hadoop.hive.metastore.MetaStoreUtils.java

/**
 * Finds a free port on the machine, but allow the
 * ability to specify a port number to not use, no matter what.
 *///from   www .j  a  v  a 2  s.c o m
public static int findFreePortExcepting(int portToExclude) throws IOException {
    ServerSocket socket1 = null;
    ServerSocket socket2 = null;
    try {
        socket1 = new ServerSocket(0);
        socket2 = new ServerSocket(0);
        if (socket1.getLocalPort() != portToExclude) {
            return socket1.getLocalPort();
        }
        // If we're here, then socket1.getLocalPort was the port to exclude
        // Since both sockets were open together at a point in time, we're
        // guaranteed that socket2.getLocalPort() is not the same.
        return socket2.getLocalPort();
    } finally {
        if (socket1 != null) {
            socket1.close();
        }
        if (socket2 != null) {
            socket2.close();
        }
    }
}

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

/**
 * Find and return an unused server socket port.
 *//*from w  ww.ja v  a 2 s .  c o 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.isis.objectstore.nosql.db.file.server.FileServer.java

private void startControl() {
    final String controlHost = config.getString("fileserver.control-host", DEFAULT_HOST);
    final int controlPort = config.getInt("fileserver.control-port", DEFAULT_CONTROL_PORT);
    final int connectionTimeout = config.getInt("fileserver.connection.timeout", 5000);

    ServerSocket socket = null;
    try {/*from  w ww  . j a va2s  . c  o m*/
        LOG.debug("setting up control socket on " + controlHost + ":" + controlPort);
        final InetAddress address = InetAddress.getByName(controlHost);
        socket = new ServerSocket(controlPort, 0, address);
        socket.setSoTimeout(connectionTimeout);
        LOG.info("file control listenting on " + socket.getInetAddress().getHostAddress() + " port "
                + socket.getLocalPort());
        LOG.debug("file control listenting on " + socket);
    } catch (final UnknownHostException e) {
        LOG.error("Unknown host " + controlHost, e);
        System.exit(0);
    } catch (final IOException e) {
        LOG.error("start failure - networking not set up for " + controlHost, e);
        System.exit(0);
    } catch (final RuntimeException e) {
        LOG.error("start failure", e);
        System.exit(0);
    }
    do {
        try {
            final Socket connection = socket.accept();
            LOG.info("control connection from " + connection);
            controlConnection(connection);
        } catch (final SocketTimeoutException expected) {
        } catch (final IOException e) {
            LOG.error("networking problem", e);
        }
    } while (awaitConnections);
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void startService() {
    final String serviceHost = config.getString("fileserver.host", DEFAULT_HOST);
    final int servicePort = config.getInt("fileserver.port", DEFAULT_SERVICE_PORT);
    final int connectionTimeout = config.getInt("fileserver.connection.timeout", 5000);
    final int readTimeout = config.getInt("fileserver.read.timeout", 5000);

    ServerSocket socket = null;
    try {/*from   w ww . j  av a2 s  .  c om*/
        LOG.debug("setting up service socket on " + serviceHost + ":" + servicePort);
        final InetAddress address = InetAddress.getByName(serviceHost);
        socket = new ServerSocket(servicePort, BACKLOG, address);
        socket.setSoTimeout(connectionTimeout);
        LOG.info("file service listenting on " + socket.getInetAddress().getHostAddress() + " port "
                + socket.getLocalPort());
        LOG.debug("file service listenting on " + socket);
        final LogRange logFileRange = Util.logFileRange();
        if (!logFileRange.noLogFile()) {
            final long lastRecoveryFile = logFileRange.getLast();
            final File file = Util.logFile(lastRecoveryFile);
            LOG.info("replaying last recovery file: " + file.getAbsolutePath());
            recover(file);
        }
        server.startup();
    } catch (final UnknownHostException e) {
        LOG.error("Unknown host " + serviceHost, e);
        System.exit(0);
    } catch (final IOException e) {
        LOG.error("start failure - networking not set up for " + serviceHost, e);
        System.exit(0);
    } catch (final RuntimeException e) {
        LOG.error("start failure", e);
        System.exit(0);
    }
    do {
        try {
            while (isQuiescent) {
                try {
                    Thread.sleep(300);
                } catch (final InterruptedException ignore) {
                }
            }
            final Socket connection = socket.accept();
            LOG.debug("connection from " + connection);
            connection.setSoTimeout(readTimeout);
            serviceConnection(connection, readTimeout);
        } catch (final SocketTimeoutException expected) {
        } catch (final IOException e) {
            LOG.error("networking problem", e);
        }
    } while (awaitConnections);
}

From source file:ca.uhn.hl7v2.testpanel.controller.Controller.java

/**
 * Provide a random, currently unused port
 *///from  w w  w .  ja va2  s . c o m
private int provideRandomPort() {
    ServerSocket server;
    try {
        server = new ServerSocket(0);
        int port = server.getLocalPort();
        server.close();
        return port;
    } catch (IOException e) {
        throw new Error(e);
    }
}

From source file:eu.stratosphere.nephele.taskmanager.TaskManager.java

private int getAvailablePort() {
    ServerSocket serverSocket = null;
    int port = 0;
    for (int i = 0; i < 50; i++) {
        try {//from  w  ww.  ja  v  a 2s  .c om
            serverSocket = new ServerSocket(0);
            port = serverSocket.getLocalPort();
            if (port != 0) {
                serverSocket.close();
                break;
            }
        } catch (IOException e) {
            LOG.debug("Unable to allocate port " + e.getMessage(), e);
        }
    }
    if (!serverSocket.isClosed()) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            LOG.debug("error closing port", e);
        }
    }
    return port;
}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

private void _init(TaskRunConfig runConfig) throws Exception {
    config = runConfig;//w  w  w . ja va2 s. co  m
    mapstats = new TreeMapperStats(log);

    resolve();

    if (nodeCache != null)
        TreeCommonParameters.setDefaultCleanQueueSize(nodeCache);
    if (trashInterval != null)
        TreeCommonParameters.setDefaultTrashInterval(trashInterval);
    if (trashTimeLimit != null)
        TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit);
    if (storage != null) {
        if (storage.maxCacheSize != null)
            TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize);
        if (storage.maxCacheMem != null)
            TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem);
        if (storage.maxPageSize != null)
            TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize);
        if (storage.maxPageMem != null)
            TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem);
        if (storage.memSample != null)
            TreeCommonParameters.setDefaultMemSample(storage.memSample);
    }

    if (Strings.isEmpty(localhost)) {
        localhost = InetAddress.getLocalHost().getHostAddress();
    }
    log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http="
            + enableHttp + " jmx=" + enableJmx + " live=" + live);
    log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId);

    Path treePath = Paths.get(runConfig.dir, "data");
    tree = new ConcurrentTree(Files.initDirectory(treePath.toFile()));
    bench = new Bench(EnumSet.allOf(BENCH.class), 1000);

    if (enableHttp) {
        jetty = new Server(port > 0 ? port++ : 0);
        jetty.start();
        int httpPort = jetty.getConnectors()[0].getLocalPort();
        log.info("[init.http] http://" + localhost + ":" + httpPort + "/");
        Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false);
    }

    if (enableJmx) {
        int queryPort = 0;
        jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort);
        ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname);
        ServerSocket ss = new ServerSocket();
        ss.setReuseAddress(true);
        ss.bind(port > 0 ? new InetSocketAddress(port++) : null);
        int jmxport = ss.getLocalPort();
        ss.close();
        if (jmxport == -1) {
            log.warn("[init.jmx] failed to get a port");
        } else {
            try {
                jmxremote = new MBeanRemotingSupport(jmxport);
                jmxremote.start();
                log.info("[init.jmx] port=" + jmxport);
            } catch (Exception e) {
                log.warn("[init.jmx] err=" + e);
            }
        }
    }

    if (config.jobId != null && live && livePort > -1) {
        QueryEngine liveQueryEngine = new QueryEngine(tree);
        connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine);
    }

    startTime = System.currentTimeMillis();

    if (pre != null) {
        log.warn("pre-chain: " + pre);
        processBundle(new KVBundle(), pre);
    }
}

From source file:org.globus.gsi.gssapi.test.GlobusGSSContextTest.java

public void testStreamInitAcceptContext() throws Exception {

    assertTrue("client ctx already established.", !clientContext.isEstablished());
    assertTrue("server ctx already established.", !serverContext.isEstablished());

    clientContext.requestCredDeleg(true);
    assertTrue(clientContext.getCredDelegState());
    clientContext.requestConf(false);//  w  ww .j  a  va  2  s .com
    serverContext.requestConf(true);

    ServerSocket serverSocket = new ServerSocket(0);

    Server serverThread = new Server(serverSocket, serverContext);
    serverThread.start();

    Socket client = new Socket(InetAddress.getLocalHost(), serverSocket.getLocalPort());

    OutputStream out = client.getOutputStream();
    InputStream in = client.getInputStream();

    while (!clientContext.isEstablished()) {
        clientContext.initSecContext(in, out);
        out.flush();
    }

    // make sure the thread is complete
    serverThread.join();

    client.close();
    serverSocket.close();

    if (serverThread.getException() != null) {
        throw serverThread.getException();
    }

    assertTrue("client ctx not established.", clientContext.isEstablished());
    assertTrue("server ctx not established.", serverContext.isEstablished());

    // just run some wrap/unwrap tests
    runWrapTests(true, false, 0);
}

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

public String openActiveMode() throws IOException {
    InetAddress addr = NetUtils.getMachineAddress(true);
    String addrStr = addr != null ? addr.getHostAddress() : "127.0.0.1";
    ServerSocket sock = ServerSocketFactory.getDefault().createServerSocket(0, 1, addr);
    sock.setSoTimeout(10000);/*  w w  w .j  a v  a 2s .c o  m*/

    Pattern pattern = Pattern.compile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$");
    Matcher matcher = pattern.matcher(addrStr);
    if (!matcher.matches()) {
        throw new IOException("Invalid address: " + addrStr);
    }
    int p1 = (sock.getLocalPort() >>> FtpConstants.BYTE_LENGTH) & FtpConstants.BYTE_MASK;
    int p2 = sock.getLocalPort() & FtpConstants.BYTE_MASK;

    StringBuffer sb = new StringBuffer();
    sb.append("PORT ");
    sb.append(matcher.group(1));
    sb.append(",");
    sb.append(matcher.group(2));
    sb.append(",");
    sb.append(matcher.group(3));
    sb.append(",");
    sb.append(matcher.group(4));
    sb.append(",");
    sb.append(p1);
    sb.append(",");
    sb.append(p2);

    resetDataSockets();
    activeModeServerSocket = sock;

    sendCommand(sb.toString());

    return getResponse();

}

From source file:com.lithium.flow.vault.AgentServer.java

public AgentServer(@Nonnull Config config) throws IOException {
    checkNotNull(config);/*w  ww .j  a  v  a2  s .  c o m*/

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(System.in, baos);
    byte[] bytes = baos.toByteArray();

    ServerSocket server = new ServerSocket(config.getInt("agent.port"), -1, InetAddress.getByName(null));
    long endTime = System.currentTimeMillis() + config.getTime("agent.maximumTime", "1d");
    long inactiveTime = config.getTime("agent.inactiveTime", "8h");
    AtomicLong lastTime = new AtomicLong(System.currentTimeMillis());

    new LoopThread(() -> {
        try {
            Socket socket = server.accept();
            log.info("accepted connection: {}", socket);
            try (OutputStream out = socket.getOutputStream()) {
                IOUtils.copy(new ByteArrayInputStream(bytes), out);
            }
        } catch (IOException e) {
            //
        }

        lastTime.set(System.currentTimeMillis());
    });

    new LoopThread(1000, () -> {
        long time = System.currentTimeMillis();
        if (time > endTime) {
            log.info("maximum time reached");
            System.exit(0);
        }

        if (time > lastTime.get() + inactiveTime) {
            log.info("inactive time reached");
            System.exit(0);
        }
    });

    log.info("started agent on port {}", server.getLocalPort());
    Sleep.forever();
}