Example usage for java.net ServerSocket close

List of usage examples for java.net ServerSocket close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:com.nesscomputing.service.discovery.client.TestServiceDiscovery.java

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

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

    return port;
}

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();/*from w  ww . j av  a2  s. com*/
    serverSocket.close();
    return port;
}

From source file:com.aqnote.shared.cryptology.util.lang.StreamUtil.java

public static void close(ServerSocket ssocket) {
    try {/*from w w  w.jav a 2 s.  c  om*/
        if (ssocket != null && !ssocket.isClosed())
            ssocket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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 w w.  j  a  v a 2 s  .c  o  m

    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:org.kiji.schema.cassandra.TestingCassandraFactory.java

/**
 * Find an available port.//from w w  w .  ja v  a  2 s .  co  m
 *
 * @return an open port number.
 * @throws IllegalArgumentException if it can't find an open port.
 */
private static int findOpenPort() {
    try {
        ServerSocket serverSocket = new ServerSocket(0);
        int portNumber = serverSocket.getLocalPort();
        serverSocket.setReuseAddress(true);
        serverSocket.close();
        LOG.debug("Found usable port {}", portNumber);
        return portNumber;
    } catch (IOException ioe) {
        throw new RuntimeException("Could not find open port.");
    }
}

From source file:de.undercouch.gradle.tasks.download.TestBase.java

/**
 * Find a free socket port/* ww w  . jav  a  2 s  . c  o  m*/
 * @return the number of the free port
 * @throws IOException if an IO error occurred
 */
protected static int findPort() throws IOException {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:org.eclipse.wst.xsl.jaxp.debug.debugger.DebugRunner.java

private static Socket getSocket(int port) throws IOException {
    InetAddress localhost = InetAddress.getByName("localhost"); //$NON-NLS-1$
    ServerSocket serverSocket = new ServerSocket(port, 5, localhost);
    Socket clientSocket = serverSocket.accept();
    serverSocket.close();
    return clientSocket;
}

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

private static void tryCloseSocket(@Nullable ServerSocket socket) {
    try {// w  w w  . ja  v  a 2  s  .c  o m
        if (socket != null) {
            socket.close();
        }
    } catch (IOException e) {
        throw new AssertionError(
                "Problem while enumerating ports (specifically, port " + socket.getLocalPort() + ")", e);
    }
}

From source file:AvailablePortFinder.java

/**
 * Returns the {@link Set} of currently avaliable port numbers ({@link Integer})
 * between the specified port range.//from w  w w. jav a2s .co  m
 *
 * @throws IllegalArgumentException if port range is not between
 * {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER} or
 * <code>fromPort</code> if greater than <code>toPort</code>.
 */
public static Set<Integer> getAvailablePorts(int fromPort, int toPort) {
    if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) {
        throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort);
    }

    Set<Integer> result = new TreeSet<Integer>();

    for (int i = fromPort; i <= toPort; i++) {
        ServerSocket s = null;

        try {
            s = new ServerSocket(i);
            result.add(new Integer(i));
        } catch (IOException e) {
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    /* should not be thrown */
                }
            }
        }
    }

    return result;
}

From source file:org.alexlg.bankit.Launcher.java

/**
 * Check if a tcp port is open on localhost interface.
 * @param port Port to check//from ww  w.  j ava  2 s.c  om
 * @return True if port is open, false otherwise
 */
private static boolean isPortOpen(int port) {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(port);
        socket.setReuseAddress(true);
    } catch (IOException e) {
        return false;
    } finally {
        // Clean up
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
        }
    }

    return true;
}