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.sentry.service.thrift.SentryService.java

private static int findFreePort() {
    int attempts = 0;
    while (attempts++ <= 1000) {
        try {//  w w w.j a  v  a2  s .  c o  m
            ServerSocket s = new ServerSocket(0);
            int port = s.getLocalPort();
            s.close();
            return port;
        } catch (IOException e) {
            // ignore and retry
        }
    }
    throw new IllegalStateException("Unable to find a port after 1000 attempts");
}

From source file:org.ngrinder.recorder.util.NetworkUtil.java

/**
 * Get the available port using the given default port. If it's not available, it chooses the
 * random port./* w  w w . ja  v a2 s . co m*/
 * 
 * @param localHostAddress
 *            address in which the port will be assigned.
 * @param defaultPort
 *            default port.
 * @return usable port.
 */
public static int getAvailablePort(InetAddress localHostAddress, int defaultPort) {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(defaultPort, 50, localHostAddress);

        return socket.getLocalPort();
    } catch (IOException e) {
        LOGGER.error("Error during openning port. {}", e.getMessage());
        LOGGER.debug("Details:{}", e.getMessage(), e);
        return getAvailablePort(localHostAddress);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                LOGGER.error("Error during port close");
            }
        }
    }
}

From source file:org.apache.beam.sdk.io.jdbc.JdbcIOTest.java

@BeforeClass
public static void startDatabase() throws Exception {
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();/* w  ww  . j a v  a 2s.  com*/

    LOG.info("Starting Derby database on {}", port);

    // by default, derby uses a lock timeout of 60 seconds. In order to speed up the test
    // and detect the lock faster, we decrease this timeout
    System.setProperty("derby.locks.waitTimeout", "2");
    System.setProperty("derby.stream.error.file", "target/derby.log");

    derbyServer = new NetworkServerControl(InetAddress.getByName("localhost"), port);
    StringWriter out = new StringWriter();
    derbyServer.start(new PrintWriter(out));
    boolean started = false;
    int count = 0;
    // Use two different methods to detect when server is started:
    // 1) Check the server stdout for the "started" string
    // 2) wait up to 15 seconds for the derby server to start based on a ping
    // on faster machines and networks, this may return very quick, but on slower
    // networks where the DNS lookups are slow, this may take a little time
    while (!started && count < 30) {
        if (out.toString().contains("started")) {
            started = true;
        } else {
            count++;
            Thread.sleep(500);
            try {
                derbyServer.ping();
                started = true;
            } catch (Throwable t) {
                // ignore, still trying to start
            }
        }
    }

    dataSource = new ClientDataSource();
    dataSource.setCreateDatabase("create");
    dataSource.setDatabaseName("target/beam");
    dataSource.setServerName("localhost");
    dataSource.setPortNumber(port);

    readTableName = DatabaseTestHelper.getTestTableName("UT_READ");

    DatabaseTestHelper.createTable(dataSource, readTableName);
    addInitialData(dataSource, readTableName);
}

From source file:org.exoplatform.addons.es.integration.BaseIntegrationTest.java

/**
 * Get a random available port//from ww  w .j a  v a 2s .  c  o  m
 * @return
 * @throws IOException
 */
private static int getAvailablePort() throws IOException {
    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(0);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(0);
        ds.setReuseAddress(true);
        return ss.getLocalPort();
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }
}

From source file:org.glowroot.tests.WebDriverSetup.java

private static int getAvailablePort() throws Exception {
    if (SauceLabs.useSauceLabs()) {
        // glowroot must listen on one of the ports that sauce connect proxies
        // see https://saucelabs.com/docs/connect#localhost
        return 4000;
    } else {/*  w  w w . j  a  v a  2s. c om*/
        ServerSocket serverSocket = new ServerSocket(0);
        int port = serverSocket.getLocalPort();
        serverSocket.close();
        return port;
    }
}

From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerTest.java

@org.junit.BeforeClass
public static void setup() throws Exception {
    // Create keys
    String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE";
    String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE";

    // Create a truststore
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, "security".toCharArray());

    serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30),
            "sspass", "myservicekey", "skpass", keystore);
    clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass",
            "myclientkey", "ckpass", keystore);

    File truststoreFile = File.createTempFile("kafkatruststore", ".jks");
    try (OutputStream output = new FileOutputStream(truststoreFile)) {
        keystore.store(output, "security".toCharArray());
    }/*from   w  ww.  j  a v a 2s  .  com*/
    truststorePath = truststoreFile.getPath();

    zkServer = new TestingServer();

    // Get a random port
    ServerSocket serverSocket = new ServerSocket(0);
    port = serverSocket.getLocalPort();
    serverSocket.close();

    tempDir = Files.createTempDirectory("kafka");

    final Properties props = new Properties();
    props.put("broker.id", 1);
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", tempDir.toString());
    props.put("zookeeper.connect", zkServer.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    props.put("controlled.shutdown.enable", Boolean.TRUE.toString());
    // Enable SSL
    props.put("listeners", "SSL://localhost:" + port);
    props.put("ssl.keystore.location", serviceKeystorePath);
    props.put("ssl.keystore.password", "sspass");
    props.put("ssl.key.password", "skpass");
    props.put("ssl.truststore.location", truststorePath);
    props.put("ssl.truststore.password", "security");
    props.put("security.inter.broker.protocol", "SSL");
    props.put("ssl.client.auth", "required");

    // Plug in Apache Ranger authorizer
    props.put("authorizer.class.name",
            "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer");

    // Create users for testing
    UserGroupInformation.createUserForTesting(clientDN, new String[] { "public" });
    UserGroupInformation.createUserForTesting(serviceDN, new String[] { "IT" });

    KafkaConfig config = new KafkaConfig(props);
    kafkaServer = new KafkaServerStartable(config);
    kafkaServer.startup();

    // Create some topics
    ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$);

    final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false);
    AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
    AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
}

From source file:com.google.gwt.dev.shell.tomcat.EmbeddedTomcatServer.java

/**
 * Returns what local port the Tomcat connector is running on.
 * //from  w  w w.j  a  v  a  2 s.  c om
 * When starting Tomcat with port 0 (i.e. choose an open port), there is just
 * no way to figure out what port it actually chose. So we're using pure
 * hackery to steal the port via reflection. The only works because we bundle
 * Tomcat with GWT and know exactly what version it is.
 */
private static int computeLocalPort(Connector connector) {
    Throwable caught = null;
    try {
        Field phField = CoyoteConnector.class.getDeclaredField("protocolHandler");
        phField.setAccessible(true);
        Object protocolHandler = phField.get(connector);

        Field epField = protocolHandler.getClass().getDeclaredField("ep");
        epField.setAccessible(true);
        Object endPoint = epField.get(protocolHandler);

        Field ssField = endPoint.getClass().getDeclaredField("serverSocket");
        ssField.setAccessible(true);
        ServerSocket serverSocket = (ServerSocket) ssField.get(endPoint);

        return serverSocket.getLocalPort();
    } catch (SecurityException e) {
        caught = e;
    } catch (NoSuchFieldException e) {
        caught = e;
    } catch (IllegalArgumentException e) {
        caught = e;
    } catch (IllegalAccessException e) {
        caught = e;
    }
    throw new RuntimeException("Failed to retrieve the startup port from Embedded Tomcat", caught);
}

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 w  ww  .ja va 2  s .co 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:TestHTTPSource.java

private static int findFreePort() throws IOException {
    ServerSocket socket = new ServerSocket(0);
    int port = socket.getLocalPort();
    socket.close();//from  w  w  w  .j a v  a2 s . c  o m
    return port;
}

From source file:org.onosproject.incubator.rpc.grpc.GrpcRemoteServiceTest.java

public static int pickListenPort() {
    try {// w  ww .ja  v a 2  s  .  c  om
        // pick unused port
        ServerSocket socket = new ServerSocket(0);
        int port = socket.getLocalPort();
        socket.close();
        return port;
    } catch (IOException e) {
        // something went wrong, try picking randomly
        return RandomUtils.nextInt(49152, 0xFFFF + 1);
    }
}