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:com.ngdata.hbaseindexer.impl.IndexerModelImplTest.java

public static int getFreePort() {
    ServerSocket socket = null;
    try {/*from  w ww.  j a v  a2 s .  c  o m*/
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException("Error finding a free port", e);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Error closing ServerSocket used to detect a free port.", e);
            }
        }
    }
}

From source file:com.nokia.dempsy.mpcluster.zookeeper.ZookeeperTestServer.java

public static int findNextPort() throws IOException {
    // find an unused ehpemeral port
    InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
    ServerSocket serverSocket = new ServerSocket();
    serverSocket.setReuseAddress(true); // this allows the server port to be bound to even if it's in TIME_WAIT
    serverSocket.bind(inetSocketAddress);
    port = serverSocket.getLocalPort();
    serverSocket.close();/*from  w w  w .  j  a v  a  2s  . c om*/
    return port;
}

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

@org.junit.BeforeClass
public static void setup() throws Exception {
    // JAAS Config file
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//from  w  ww . j a  va2s.  com

    File f = new File(basedir + "/src/test/resources/kafka_plain.jaas");
    System.setProperty("java.security.auth.login.config", f.getPath());

    // 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());
    }
    truststorePath = truststoreFile.getPath();

    zkServer = new TestingServer();

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

    final Properties props = new Properties();
    props.put("broker.id", 1);
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", "/tmp/kafka");
    props.put("zookeeper.connect", zkServer.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    props.put("controlled.shutdown.enable", Boolean.TRUE.toString());
    // Enable SASL_SSL
    props.put("listeners", "SASL_SSL://localhost:" + port);
    props.put("security.inter.broker.protocol", "SASL_SSL");
    props.put("sasl.enabled.mechanisms", "PLAIN");
    props.put("sasl.mechanism.inter.broker.protocol", "PLAIN");

    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");

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

    // Create users for testing
    UserGroupInformation.createUserForTesting("alice", 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.nesscomputing.service.discovery.server.TestStaticAnnounce.java

private static final int findUnusedPort() {
    int port;//  ww w .  j av a 2 s .co m

    ServerSocket socket = null;
    try {
        socket = new ServerSocket();
        socket.bind(new InetSocketAddress(0));
        port = socket.getLocalPort();
    } catch (final IOException ioe) {
        throw Throwables.propagate(ioe);
    } finally {
        try {
            socket.close();
        } catch (final IOException ioe) {
            // GNDN
        }
    }

    return port;
}

From source file:gobblin.service.FlowConfigTest.java

private static int chooseRandomPort() throws IOException {
    ServerSocket socket = null;
    try {/*  www .ja  va  2 s.  com*/
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:org.apache.hadoop.mapred.MiniMRHACluster.java

private static int findEphemeralPort() throws IOException {
    ServerSocket socket = null;
    try {/*  www. j  a v  a 2s. c  o m*/
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.graphaware.test.util.TestUtils.java

/**
 * Get some available port./*  ww  w .ja v  a2s . c o m*/
 *
 * @return port number.
 */
public static int getAvailablePort() {
    try {
        ServerSocket socket = new ServerSocket(0);
        try {
            return socket.getLocalPort();
        } finally {
            socket.close();
        }
    } catch (IOException e) {
        throw new IllegalStateException("Cannot find available port: " + e.getMessage(), e);
    }
}

From source file:org.apache.pulsar.functions.utils.Utils.java

public static int findAvailablePort() {
    // The logic here is a little flaky. There is no guarantee that this
    // port returned will be available later on when the instance starts
    // TODO(sanjeev):- Fix this
    try {//from  ww  w.  j  av a2  s.  c om
        ServerSocket socket = new ServerSocket(0);
        int port = socket.getLocalPort();
        socket.close();
        return port;
    } catch (IOException ex) {
        throw new RuntimeException("No free port found", ex);
    }
}

From source file:org.codice.ddf.catalog.ui.forms.SearchFormsSymbolsIT.java

/**
 * Return an available port number after binding and releasing it.
 *
 * <p>The discovered port should be available for another client to bind to by the time this
 * function has returned. Given this detail, running unit tests on environments that are in the
 * process of being provisioned or are otherwise in a state of flux may cause erroneous failures
 * due to port binding race conditions.//from  w w w . jav a 2s  .  c om
 *
 * @return a port number the caller can <b>reasonably</b> assume is available to bind to.
 * @throws AssertionError if no port was available to bind to or the binding operation failed.
 */
private static int getAvailablePort() {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new AssertionError("Could not autobind to available port", e);
    } finally {
        tryCloseSocket(socket);
    }
}

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

/**
 * Get a available port.//from   www. ja va2s .c om
 * 
 * @param localHostAddress
 *            localHostAddress
 * 
 * @return min port available from scanStartPort
 */
public static int getAvailablePort(InetAddress localHostAddress) {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0, 50, localHostAddress);
        return socket.getLocalPort();
    } catch (IOException e) {
        LOGGER.error("Error during openning port. {}", e.getMessage());
        LOGGER.debug("Details:{}", e.getMessage(), e);
        return 16000;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                LOGGER.error("Error during closing port");
            }
        }
    }
}