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.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Before
public void setUp() throws Exception {
    ConfigurationManager.getConfigInstance().setProperty("janus.errorThresholdPerSec", 3);
    ConfigurationManager.getConfigInstance().setProperty("janus.shortCircuitDuration", 1000);
    ConfigurationManager.getConfigInstance().setProperty("janus.refreshIntervalInMillis", 500);

    Server server = new ContainerServer(forwardingServerContainer);
    server1Connection = new SocketConnection(server);

    ServerSocket socketServer = new ServerSocket(0);
    server1Port = socketServer.getLocalPort();
    socketServer.close();/*from w  w  w .j  a  va2s. co m*/

    server1Connection.connect(new InetSocketAddress(server1Port));

    server = new ContainerServer(forwardingServerContainer);
    server2Connection = new SocketConnection(server);

    socketServer = new ServerSocket(0);
    server2Port = socketServer.getLocalPort();
    socketServer.close();

    server2Connection.connect(new InetSocketAddress(server2Port));
}

From source file:com.nike.vault.client.VaultClientTest.java

@Test(expected = VaultClientException.class)
public void read_throws_runtime_exception_if_unexpected_error_encountered() throws IOException {
    final ServerSocket serverSocket = new ServerSocket(0);
    final String vaultUrl = "http://localhost:" + serverSocket.getLocalPort();
    final VaultCredentialsProvider vaultCredentialsProvider = mock(VaultCredentialsProvider.class);
    final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS);
    vaultClient = new VaultClient(new StaticVaultUrlResolver(vaultUrl), vaultCredentialsProvider, httpClient);

    when(vaultCredentialsProvider.getCredentials()).thenReturn(new TestVaultCredentials());

    vaultClient.read("app/api-key");
}

From source file:com.nike.vault.client.VaultClientTest.java

@Test(expected = VaultClientException.class)
public void delete_throws_runtime_exception_if_unexpected_error_encountered() throws IOException {
    final ServerSocket serverSocket = new ServerSocket(0);
    final String vaultUrl = "http://localhost:" + serverSocket.getLocalPort();
    final VaultCredentialsProvider vaultCredentialsProvider = mock(VaultCredentialsProvider.class);
    final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS);
    vaultClient = new VaultClient(new StaticVaultUrlResolver(vaultUrl), vaultCredentialsProvider, httpClient);

    when(vaultCredentialsProvider.getCredentials()).thenReturn(new TestVaultCredentials());

    vaultClient.delete("app/api-key");
}

From source file:com.nike.vault.client.VaultClientTest.java

@Test(expected = VaultClientException.class)
public void write_throws_runtime_exception_if_unexpected_error_encountered() throws IOException {
    final ServerSocket serverSocket = new ServerSocket(0);
    final String vaultUrl = "http://localhost:" + serverSocket.getLocalPort();
    final VaultCredentialsProvider vaultCredentialsProvider = mock(VaultCredentialsProvider.class);
    final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS);
    vaultClient = new VaultClient(new StaticVaultUrlResolver(vaultUrl), vaultCredentialsProvider, httpClient);

    when(vaultCredentialsProvider.getCredentials()).thenReturn(new TestVaultCredentials());

    Map<String, String> data = new HashMap<>();
    data.put("key", "value");
    vaultClient.write("app/api-key", data);
}

From source file:org.apache.flink.runtime.taskexecutor.TaskManagerRunnerStartupTest.java

/**
 * Tests that the TaskManagerRunner startup fails if the network stack cannot be initialized.
 *///from w  w w .  j a v  a2s  . com
@Test
public void testStartupWhenNetworkStackFailsToInitialize() throws Exception {
    final ServerSocket blocker = new ServerSocket(0, 50, InetAddress.getByName(LOCAL_HOST));

    try {
        final Configuration cfg = new Configuration();
        cfg.setInteger(NetworkEnvironmentOptions.DATA_PORT, blocker.getLocalPort());

        startTaskManager(cfg, rpcService, highAvailabilityServices);

        fail("Should throw IOException when the network stack cannot be initialized.");
    } catch (IOException e) {
        // ignored
    } finally {
        IOUtils.closeQuietly(blocker);
    }
}

From source file:org.eredlab.g4.ccl.net.bsd.RExecClient.java

InputStream _createErrorStream() throws IOException {
    ServerSocket server;
    Socket socket;/*from w  w w . ja  v a 2  s.c o  m*/

    server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());

    _output_.write(Integer.toString(server.getLocalPort()).getBytes());
    _output_.write('\0');
    _output_.flush();

    socket = server.accept();
    server.close();

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();
        throw new IOException("Security violation: unexpected connection attempt by "
                + socket.getInetAddress().getHostAddress());
    }

    return (new SocketInputStream(socket, socket.getInputStream()));
}

From source file:org.apache.servicemix.jbi.cluster.engine.AbstractClusterEndpointTest.java

protected int findFreePort() {
    int port = 61616;
    try {/*from w w  w .j  a  va2 s .c  o m*/
        ServerSocket ss = new ServerSocket(0);
        port = ss.getLocalPort();
        ss.close();
    } catch (Exception e) {
    }
    return port;
}

From source file:com.barchart.netty.server.http.TestHttpServer.java

@Before
public void setUp() throws Exception {

    basic = new TestRequestHandler("basic", false, 0, 0, false, false);
    async = new TestRequestHandler("async", true, 0, 0, false, false);
    asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false);
    clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false);
    error = new TestRequestHandler("error", false, 0, 0, true, false);
    channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true);

    infoHandler = new TestRequestHandler("info", false, 0, 0, false, false);
    serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false);

    chunkedHandler = new ChunkedRequestHandler("chunked");

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();
    s.close();/*from  w  w w.j  a v a 2  s.c o  m*/
    Thread.sleep(100);

    server = Servers.createHttpServer().requestHandler("/basic", basic).group(new NioEventLoopGroup(1))
            .requestHandler("/async", async).requestHandler("/async-delayed", asyncDelayed)
            .requestHandler("/client-disconnect", clientDisconnect)
            .requestHandler("/channel-error", channelError).requestHandler("/error", error)
            .requestHandler("/service/info", infoHandler).requestHandler("/service", serviceHandler)
            .requestHandler("/chunked", chunkedHandler).maxConnections(1);

    server.listen(port, "localhost").sync();

    connMgr = new PoolingClientConnectionManager();
    client = new DefaultHttpClient(connMgr);

}

From source file:fitnesse.testsystems.fit.CommandRunningFitClient.java

public void start() throws IOException {
    ServerSocket serverSocket = new PlainServerSocketFactory().createServerSocket(0);
    server = new SocketService(new SocketCatcher(this, ticketNumber), true, serverSocket);
    int port = serverSocket.getLocalPort();
    try {/*w  w w. j a v  a 2  s  . co m*/
        commandRunningStrategy.start(this, port, ticketNumber);
        waitForConnection();
    } catch (Exception e) {
        exceptionOccurred(e);
    }
}

From source file:org.apache.htrace.impl.TestDroppedSpans.java

/**
 * Test that we write to the dropped spans log when htraced is unreachable.
 *//*from ww w  .j a v  a 2  s .  c om*/
@Test(timeout = 60000)
public void testSpansDroppedBecauseOfUnreachableHTraced() throws Exception {
    final String logPath = new File(tempDir.toFile(), "testSpansDroppedBecauseOfUnreachableHTraced")
            .getAbsolutePath();
    // Open a local socket.  We know that nobody is listening on this socket, so
    // all attempts to send to it will fail.
    final ServerSocket serverSocket = new ServerSocket(0);
    HTracedSpanReceiver rcvr = null;
    try {
        HTraceConfiguration conf = HTraceConfiguration.fromMap(new HashMap<String, String>() {
            {
                put(Conf.ADDRESS_KEY, "127.0.0.1:" + serverSocket.getLocalPort());
                put(TracerId.TRACER_ID_KEY, "testSpansDroppedBecauseOfUnreachableHTraced");
                put(Conf.DROPPED_SPANS_LOG_PATH_KEY, logPath);
                put(Conf.DROPPED_SPANS_LOG_MAX_SIZE_KEY, "78");
                put(Conf.CONNECT_TIMEOUT_MS_KEY, "1");
                put(Conf.IO_TIMEOUT_MS_KEY, "1");
                put(Conf.FLUSH_RETRY_DELAYS_KEY, "1,1");
            }
        });
        rcvr = new HTracedSpanReceiver(conf);
        rcvr.receiveSpan(new MilliSpan.Builder().begin(123).end(456).description("FooBar").build());
        HTracedSpanReceiver tmpRcvr = rcvr;
        rcvr = null;
        tmpRcvr.close();
        List<String> lines = Files.readAllLines(Paths.get(logPath), StandardCharsets.UTF_8);
        Assert.assertTrue(lines.size() >= 1);
        Assert.assertTrue(lines.get(0).contains("Failed to flush "));
    } finally {
        serverSocket.close();
        if (rcvr != null) {
            rcvr.close();
        }
    }
}