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.springframework.security.ldap.server.ApacheDSContainerTests.java

private List<Integer> getDefaultPorts(int count) throws IOException {
    List<ServerSocket> connections = new ArrayList<ServerSocket>();
    List<Integer> availablePorts = new ArrayList<Integer>(count);
    try {//w w w .  ja  v a2 s  . c o  m
        for (int i = 0; i < count; i++) {
            ServerSocket socket = new ServerSocket(0);
            connections.add(socket);
            availablePorts.add(socket.getLocalPort());
        }
        return availablePorts;
    } finally {
        for (ServerSocket conn : connections) {
            conn.close();
        }
    }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnectorManager.java

/**
 * This method will create a tunnel of a type defined by the properties
 * facade and will then bind a local temporary port for a client app to use
 * to communicate through the proxy tunnel.  Returns an address to the
 * local server a client can talk to./*from  w w  w  . ja  v a2s .  c  o  m*/
 *
 * @param token
 * @param serverProxyAddress
 * @param serverProxyPort
 * @return
 * @throws IOException
 */
public InetSocketAddress startConnector(RequestToken token, InetAddress serverProxyAddress, int serverProxyPort,
        int bufferSize, ConsumerProxyPropertiesFacade props, SocketClientManagerController controller)
        throws IOException {
    /*
     * Attempts to start up a connection with the desired server proxy.
     */

    // Note that both client and server are closed when the thread completes
    log.debug("Creating Client instance to connect to server proxy: " + serverProxyAddress + ":"
            + serverProxyPort);
    Client client = props.getClientInstance(serverProxyAddress, serverProxyPort, token);

    /*
     * Start up a socket server bound to the local proxy hostname and to a
     * port unique to this request.
     */
    InetAddress localProxyAddress = props.getClientProxyAddress();
    log.debug("Local client proxy address set as: " + localProxyAddress);

    InetSocketAddress connectorAddress = new InetSocketAddress(localProxyAddress, 0);
    log.debug("Starting server socket for client to access on port: " + connectorAddress.getPort());

    // Note that both client and server are closed when the thread completes
    ServerSocket server = new ServerSocket();
    server.bind(connectorAddress);
    log.debug("Creating Server bound: " + server.getInetAddress() + ": " + server.getLocalPort());

    ClientConnector connector = new ClientConnector(server, client, bufferSize, controller);
    Thread conn = new Thread(connector);

    log.debug("Starting new Client Connector thread.");
    conn.start();

    return new InetSocketAddress(server.getInetAddress(), server.getLocalPort());
}

From source file:org.apache.karaf.itests.MavenTest.java

private int getAvailablePort(int min, int max) {
    for (int i = min; i <= max; i++) {
        try {/*  w  ww  .j  av a 2 s  . c  o m*/
            ServerSocket socket = new ServerSocket(i);
            return socket.getLocalPort();
        } catch (Exception ignored) {
        }
    }
    throw new IllegalStateException("Can't find available network ports");
}

From source file:org.apache.hadoop.hdfs.server.datanode.SecureDataNodeStarter.java

@Override
public void init(DaemonContext context) throws Exception {
    System.err.println("Initializing secure datanode resources");
    // We should only start up a secure datanode in a Kerberos-secured cluster
    Configuration conf = new Configuration(); // Skip UGI method to not log in
    if (!conf.get(HADOOP_SECURITY_AUTHENTICATION).equals("kerberos"))
        throw new RuntimeException("Cannot start secure datanode in unsecure cluster");

    // Stash command-line arguments for regular datanode
    args = context.getArguments();/*from www. j  a v  a 2s. co m*/

    // Obtain secure port for data streaming to datanode
    InetSocketAddress socAddr = DataNode.getStreamingAddr(conf);
    int socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT);

    ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
    ss.bind(socAddr, 0);

    // Check that we got the port we need
    if (ss.getLocalPort() != socAddr.getPort())
        throw new RuntimeException("Unable to bind on specified streaming port in secure " + "context. Needed "
                + socAddr.getPort() + ", got " + ss.getLocalPort());

    // Obtain secure listener for web server
    SelectChannelConnector listener = (SelectChannelConnector) HttpServer.createDefaultChannelConnector();
    InetSocketAddress infoSocAddr = DataNode.getInfoAddr(conf);
    listener.setHost(infoSocAddr.getHostName());
    listener.setPort(infoSocAddr.getPort());
    // Open listener here in order to bind to port as root
    listener.open();
    if (listener.getPort() != infoSocAddr.getPort())
        throw new RuntimeException("Unable to bind on specified info port in secure " + "context. Needed "
                + socAddr.getPort() + ", got " + ss.getLocalPort());

    if (ss.getLocalPort() >= 1023 || listener.getPort() >= 1023)
        throw new RuntimeException(
                "Cannot start secure datanode on non-privileged " + " ports. (streaming port = " + ss
                        + " ) (http listener port = " + listener.getConnection() + "). Exiting.");

    System.err.println("Successfully obtained privileged resources (streaming port = " + ss
            + " ) (http listener port = " + listener.getConnection() + ")");

    resources = new SecureResources(ss, listener);
}

From source file:org.coltram.nsd.bonjour.BonjourProcessor.java

public void exposeService(String serviceType, String friendlyName, String deviceType, JSONObject service,
        AtomConnection connection) throws JSONException {
    try {//from   www . ja v a2s .  c  o m
        String type = serviceType.substring(9);
        final HashMap<String, String> values = new HashMap<String, String>();
        values.put("DName", friendlyName);
        String desc = service.toString();
        values.put("Desc", topManager.getHttpServer().addResource(UUID.randomUUID().toString() + ".json",
                desc.getBytes()));
        values.put("txtvers", "1");
        Random random = new Random();
        byte[] name = new byte[6];
        random.nextBytes(name);
        ServerSocket serverSocket = new ServerSocket(0);
        int bonjourServicePort = serverSocket.getLocalPort();
        ServiceInfo si = ServiceInfo.create(type, deviceType + "_" + toHex(name), bonjourServicePort, 0, 0,
                values);
        LocalExposedBonjourService exposedService = new LocalExposedBonjourService(topManager, serverSocket, si,
                si.getQualifiedName(), service);
        connection.add(exposedService);
        topManager.getConnectionManager().getJmdns().registerService(si);
        exposedService.start();
        connection.setExposedService(si.getQualifiedName());
        log.fine("register " + si.getQualifiedName());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java

protected int getLocalPort() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    int ret = ss.getLocalPort();
    ss.close();/*  w  w w  .ja va2  s. c om*/
    return ret;
}

From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java

protected void testPerformance(TestCase basisJob, TestCase testJob) throws Throwable {

    //cache serialized form to save time on repeated test iterations
    byte[] controlData = serializeJob(new TestProcess(testThreads, testLoop, basisJob));
    byte[] testData = serializeJob(new TestProcess(testThreads, testLoop, testJob));
    StatisticsMBean controlStats = new StatisticsMBean();
    controlStats.setUnits("nanoseconds");
    StatisticsMBean testStats = new StatisticsMBean();
    testStats.setUnits("nanoseconds");

    ServerSocket listener = new ServerSocket(0);
    try {/*from w  w  w.  j  av a 2 s .co m*/
        int port = listener.getLocalPort();

        ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + separator + "/bin/java",
                "-server", "-cp", System.getProperty("java.class.path"), TestProcess.class.getName(),
                String.valueOf(port));
        pb.redirectErrorStream(false);

        //run several iterations of the test, alternating between instrumented and not
        //to absorb the affects of garbage collection.
        for (int i = 0; i < TEST_ITERATIONS; ++i) {
            System.out.println("iteration " + i);
            //switch the order of test / control runs during iteration to reduce any
            //bias that order might cause
            if (i % 2 == 0) {
                runTest(listener, pb, testStats, testData);
                runTest(listener, pb, controlStats, controlData);
            } else {
                runTest(listener, pb, controlStats, controlData);
                runTest(listener, pb, testStats, testData);
            }
            assertEquals("basis and test have same sample size after iteration " + i, controlStats.getCount(),
                    testStats.getCount());
        }
    } finally {
        listener.close();
    }

    double basisNanos = controlStats.getAverageTime();
    double cpuCoefficient = basisNanos / (double) expectedBasis;

    double expectedAverage = cpuCoefficient * averageOverhead;
    double expectedMax = cpuCoefficient * maxOverhead;

    System.out.println("control:\n" + controlStats);
    System.out.println("test:\n" + testStats);
    System.out.println("CPU Coefficient: " + cpuCoefficient);
    System.out.println("basisNanos: " + basisNanos);

    //compute the overhead as the difference between instrumented and uninstrumented
    //runs.  we want the per-event overhead to be less than .5 ms.
    double delta = testStats.getAverageTime() - basisNanos;
    //deltaWorst, my favorite sausage.  mmmmmm, dellltttaaaWwwwooorrsstt.
    double deltaWorst = testStats.getMaxTime() - controlStats.getMaxTime();

    System.out.println("Maximum expected average overhead: " + expectedAverage);
    System.out.println("Average overhead: " + delta);
    System.out.println("Maximum expected worst case overhead: " + expectedMax);
    System.out.println("Worst case overhead: " + deltaWorst);

    assertTrue("Average overhead per method cannot exceed " + expectedAverage + "ns [ " + delta + " ]",
            delta <= expectedAverage);

    assertTrue("Worst case per method overhead cannot exceed " + expectedMax + "ns [ " + deltaWorst + " ]",
            deltaWorst <= expectedMax);
}

From source file:org.apache.hadoop.thriftfs.ThriftPluginServer.java

/**
 * Start processing requests.// w ww  . j a  va2 s  .c  o m
 * 
 * @throws IllegalStateException if the server has already been started.
 * @throws IOException on network errors.
 */
public void start() throws IOException {
    String hostname = address.getAddress().getHostAddress();

    synchronized (this) {
        if (server != null) {
            throw new IllegalStateException("Thrift server already started");
        }
        LOG.info("Starting Thrift server");
        ServerSocket sock = new ServerSocket();
        sock.setReuseAddress(true);
        if (port == 0) {
            sock.bind(null);
            address = new InetSocketAddress(hostname, sock.getLocalPort());
            port = address.getPort();
        } else {
            sock.bind(address);
        }
        TServerTransport transport = new TServerSocket(sock, SOCKET_READ_TIMEOUT);
        SanerThreadPoolServer.Options options = new SanerThreadPoolServer.Options();
        options.minWorkerThreads = conf.getInt("dfs.thrift.threads.min", 5);
        options.maxWorkerThreads = conf.getInt("dfs.thrift.threads.max", 20);
        options.stopTimeoutVal = conf.getInt("dfs.thrift.timeout", 60);
        options.stopTimeoutUnit = TimeUnit.SECONDS;
        options.queueSize = conf.getInt("dfs.thrift.queue.size", 4 * options.maxWorkerThreads);

        server = new SanerThreadPoolServer(processorFactory, transport, new TTransportFactory(),
                new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), options);
    }

    Thread t = new Thread(this);
    t.start();
    LOG.info("Thrift server listening on " + hostname + ":" + port);
}

From source file:com.cloudera.branchreduce.impl.thrift.LordMain.java

@Override
public int run(String[] args) throws Exception {
    LOG.info("Initializing lord...");
    initialize(args);/*from  w ww.  ja va 2 s .com*/
    LOG.info("Lord initialized.");

    String hostname = InetAddress.getLocalHost().getHostName();
    ServerSocket socket = new ServerSocket(0);
    ApplicationMasterParameters appMasterParams = new LuaApplicationMasterParameters(getConf(),
            ImmutableMap.<String, Object>of("MASTER_HOSTNAME", hostname, "MASTER_PORT", socket.getLocalPort()));
    appMasterParams.setTrackingUrl(String.format("%s:%d", hostname, socket.getLocalPort()));
    ApplicationMasterService appMasterService = new ApplicationMasterServiceImpl(appMasterParams, getConf());
    LOG.info("Starting application master service");
    appMasterService.startAndWait();

    TaskMaster taskMaster = new TaskMaster(numVassals, initialTasks, globalState);
    LordHandler lordHandler = new LordHandler(taskMaster);
    TServerSocket serverTransport = new TServerSocket(socket);
    Lord.Processor lordProc = new Lord.Processor(lordHandler);
    final TServer thriftServer = new TThreadPoolServer(
            new TThreadPoolServer.Args(serverTransport).processor(lordProc));

    LOG.info("Starting lord thrift server");
    Thread thriftServerThread = new Thread("Lord Thrift Server") {
        @Override
        public void run() {
            thriftServer.serve();
        };
    };
    thriftServerThread.start();

    do {
        Thread.sleep(1000);
    } while (appMasterService.hasRunningContainers());

    // Send final notifications
    lordHandler.signalJobFinished();
    while (!lordHandler.finishedNotificationSent()) {
        Thread.sleep(1000);
    }
    thriftServerThread.join(1000);

    LOG.info("Stopping application master service");
    appMasterService.stopAndWait();
    return 0;
}

From source file:org.coltram.nsd.bonjour.BonjourProcessor.java

public void callAction(JSONObject object, String serviceId, final AtomConnection connection, String callBack)
        throws JSONException {
    final DiscoveredZCService bonjourService = topManager.getServiceManager().findBonjourService(serviceId);
    if (bonjourService == null) {
        log.info("no service with id " + serviceId + " in callAction");
        return;//from  ww w  .j a v a  2  s .  c  o m
    }
    if (bonjourService.isLocal()) {
        // find the LocalExposedBonjourService in question
        LocalExposedBonjourService localcbs = LocalExposedBonjourService.getServiceById(serviceId);
        // send the info to that service
        object.put("originAtom", connection.getId());
        localcbs.notifyListeners(object.toString());
    } else {
        try {
            Socket socket = bonjourService.getSocket();
            int replyPort = -1;
            final InetAddress inetAddress = socket.getInetAddress();
            if (callBack != null) {
                // wait for reply on the same socket
                ServerSocket serverSocket = connection.getServerSocket();
                replyPort = serverSocket.getLocalPort();
                log.finer("start server for reply " + serverSocket.getLocalPort());
                new Thread(new ReplyListener(serverSocket, connection.getConnection())).start();
                Thread.yield();
            }
            String ia = inetAddress.toString();
            if (ia.startsWith("/")) {
                ia = ia.substring(1);
            }
            object.put("address", LocalHost.name);
            object.put("replyPort", replyPort + "");
            object.put("originAtom", connection.getId());
            DataOutputStream dos = bonjourService.getSocketDOS();
            dos.writeBytes(object.toString() + "\n");
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}