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.flink.runtime.taskmanager.TestManagerStartupTest.java

/**
 * Tests that the TaskManager fails synchronously when the actor system port
 * is in use./*from  w w w  .  ja  v a2s.  c om*/
 */
@Test
public void testStartupWhenTaskmanagerActorPortIsUsed() {
    ServerSocket blocker = null;
    try {
        final String localHostName = "localhost";
        final InetAddress localAddress = InetAddress.getByName(localHostName);

        // block some port
        blocker = new ServerSocket(0, 50, localAddress);
        final int port = blocker.getLocalPort();

        try {
            TaskManager.runTaskManager(localHostName, port, new Configuration(), StreamingMode.BATCH_ONLY,
                    TaskManager.class);
            fail("This should fail with an IOException");
        } catch (IOException e) {
            // expected. validate the error message
            assertNotNull(e.getMessage());
            assertTrue(e.getMessage().contains("Address already in use"));
        }

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (blocker != null) {
            try {
                blocker.close();
            } catch (IOException e) {
                // no need to log here
            }
        }
    }
}

From source file:brooklyn.util.ssh.BashCommandsIntegrationTest.java

License:asdf

@Test(groups = "Integration", dependsOnMethods = "testSudo")
public void testWaitForPortFreeWhenAbortingOnTimeout() throws Exception {
    ServerSocket serverSocket = openServerSocket();
    try {//w w w  .java 2  s .com
        int port = serverSocket.getLocalPort();
        String cmd = BashCommands.waitForPortFree(port, Duration.ONE_SECOND, true);

        int exitcode = loc.execCommands("test", ImmutableList.of(cmd));
        assertEquals(exitcode, 1);

        serverSocket.close();
        assertTrue(Networking.isPortAvailable(port));
        int exitcode2 = loc.execCommands("test", ImmutableList.of(cmd));
        assertEquals(exitcode2, 0);
    } finally {
        serverSocket.close();
    }
}

From source file:brooklyn.util.ssh.BashCommandsIntegrationTest.java

License:asdf

@Test(groups = "Integration", dependsOnMethods = "testSudo")
public void testWaitForPortFreeWhenNotAbortingOnTimeout() throws Exception {
    ServerSocket serverSocket = openServerSocket();
    try {//from  ww  w.j a  v  a2 s .co  m
        int port = serverSocket.getLocalPort();
        String cmd = BashCommands.waitForPortFree(port, Duration.ONE_SECOND, false);

        String output = execRequiringZeroAndReturningStdout(loc, cmd).get();
        assertTrue(output.contains(port + " still in use"), "output=" + output);

        serverSocket.close();
        assertTrue(Networking.isPortAvailable(port));
        String output2 = execRequiringZeroAndReturningStdout(loc, cmd).get();
        assertFalse(output2.contains("still in use"), "output=" + output2);
    } finally {
        serverSocket.close();
    }
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

public void testServerTimeouts() throws Exception {
    final ServerSocket srvSocket = new ServerSocket(0);
    int srvPort = srvSocket.getLocalPort();
    Thread serverThread = new Thread() {
        @Override/*from   w  ww . j av a  2s.c o m*/
        public void run() {
            try {
                Socket clientSocket = srvSocket.accept();
                // Sleep 1s (timeout applied on client is 0.1s)
                Thread.sleep(1000);
                clientSocket.getOutputStream().write(0);
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    serverThread.setDaemon(true);
    try {
        serverThread.start();
        EmailActionExecutor email = new EmailActionExecutor();
        Context ctx = createNormalContext("email-action");
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.port", srvPort);
        // Apply a 0.1s timeout to induce a very quick "Read timed out" error
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.socket.timeout.ms",
                100);
        try {
            email.validateAndMail(ctx, prepareEmailElement(false, false));
            fail("Should have failed with a socket timeout error!");
        } catch (Exception e) {
            Throwable rootCause = e;
            while (rootCause.getCause() != null) {
                rootCause = rootCause.getCause();
            }
            assertTrue("Expected exception type to be a SocketTimeoutException, but received: " + rootCause,
                    rootCause instanceof SocketTimeoutException);
            assertTrue("Expected error to be that of a socket read timeout, but got: " + rootCause.getMessage(),
                    rootCause.getMessage().contains("Read timed out"));
        }
    } finally {
        serverThread.interrupt();
        srvSocket.close();
    }
}

From source file:brooklyn.util.ssh.BashCommandsIntegrationTest.java

License:asdf

@Test(groups = "Integration", dependsOnMethods = "testSudo")
public void testWaitForPortFreeWhenFreedAfterStart() throws Exception {
    ServerSocket serverSocket = openServerSocket();
    try {/*from   w ww  .j a va 2  s  .  c o  m*/
        int port = serverSocket.getLocalPort();

        String cmd = BashCommands.waitForPortFree(port, Duration.THIRTY_SECONDS, false);
        ProcessTaskWrapper<String> t = execRequiringZeroAndReturningStdout(loc, cmd);
        exec.submit(t);

        // sleep for long enough to ensure the ssh command is definitely executing
        Thread.sleep(5 * 1000);
        assertFalse(t.isDone());

        serverSocket.close();
        assertTrue(Networking.isPortAvailable(port));
        String output = t.get();
        assertFalse(output.contains("still in use"), "output=" + output);
    } finally {
        serverSocket.close();
    }
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

@Before
public void findFreePort() throws Exception {
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();//from w  ww.  j a v  a2s . co m
}

From source file:org.apache.sshd.PortForwardingLoadTest.java

@Test
public void testRemoteForwardingPayload() throws Exception {
    final int NUM_ITERATIONS = 100;
    final String PAYLOAD = "This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. ";
    Session session = createSession();//  w w w.j  ava2  s.c o m
    final ServerSocket ss = new ServerSocket(0);
    int forwardedPort = ss.getLocalPort();
    int sinkPort = getFreePort();
    session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
    final boolean started[] = new boolean[1];
    started[0] = false;
    final AtomicInteger conCount = new AtomicInteger(0);

    new Thread() {
        public void run() {
            started[0] = true;
            try {
                for (int i = 0; i < NUM_ITERATIONS; ++i) {
                    Socket s = ss.accept();
                    conCount.incrementAndGet();
                    s.getOutputStream().write(PAYLOAD.getBytes());
                    s.getOutputStream().flush();
                    s.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    Thread.sleep(50);
    Assert.assertTrue("Server not started", started[0]);

    final boolean lenOK[] = new boolean[NUM_ITERATIONS];
    final boolean dataOK[] = new boolean[NUM_ITERATIONS];
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        final int ii = i;
        Socket s = null;
        try {
            s = new Socket("localhost", sinkPort);
            byte b1[] = new byte[PAYLOAD.length() / 2];
            byte b2[] = new byte[PAYLOAD.length()];
            int read1 = s.getInputStream().read(b1);
            Thread.sleep(50);
            int read2 = s.getInputStream().read(b2);
            lenOK[ii] = PAYLOAD.length() == read1 + read2;
            dataOK[ii] = PAYLOAD.equals(new String(b1, 0, read1) + new String(b2, 0, read2));
            if (!lenOK[ii] || !dataOK[ii]) {
                throw new Exception("Bad data");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
    int ok = 0;
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        ok += lenOK[i] ? 1 : 0;
    }
    Thread.sleep(50);
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        Assert.assertTrue(lenOK[i]);
        Assert.assertTrue(dataOK[i]);
    }
    session.delPortForwardingR(forwardedPort);
}

From source file:org.apache.sshd.PortForwardingLoadTest.java

@Test
public void testLocalForwardingPayload() throws Exception {
    final int NUM_ITERATIONS = 100;
    final String PAYLOAD_TMP = "This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. ";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 1000; i++) {
        sb.append(PAYLOAD_TMP);// w ww.jav  a  2s.co  m
    }
    final String PAYLOAD = sb.toString();
    Session session = createSession();
    final ServerSocket ss = new ServerSocket(0);
    int forwardedPort = ss.getLocalPort();
    int sinkPort = getFreePort();
    session.setPortForwardingL(sinkPort, "localhost", forwardedPort);
    final AtomicInteger conCount = new AtomicInteger(0);

    new Thread() {
        public void run() {
            try {
                for (int i = 0; i < NUM_ITERATIONS; ++i) {
                    Socket s = ss.accept();
                    conCount.incrementAndGet();
                    InputStream is = s.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[8192];
                    int l;
                    while (baos.size() < PAYLOAD.length() && (l = is.read(buf)) > 0) {
                        baos.write(buf, 0, l);
                    }
                    if (!PAYLOAD.equals(baos.toString())) {
                        assertEquals(PAYLOAD, baos.toString());
                    }
                    is = new ByteArrayInputStream(baos.toByteArray());
                    OutputStream os = s.getOutputStream();
                    while ((l = is.read(buf)) > 0) {
                        os.write(buf, 0, l);
                    }
                    s.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    Thread.sleep(50);

    for (int i = 0; i < NUM_ITERATIONS; i++) {
        Socket s = null;
        try {
            LoggerFactory.getLogger(getClass()).info("Iteration {}", i);
            s = new Socket("localhost", sinkPort);
            s.getOutputStream().write(PAYLOAD.getBytes());
            s.getOutputStream().flush();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int l;
            while (baos.size() < PAYLOAD.length() && (l = s.getInputStream().read(buf)) > 0) {
                baos.write(buf, 0, l);
            }
            assertEquals(PAYLOAD, baos.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
    session.delPortForwardingL(sinkPort);
}

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private int detectPort() throws IOException {
    final ServerSocket socket = new ServerSocket(0);
    try {/*w w  w  . j av a 2  s.c om*/
        return socket.getLocalPort();
    } finally {
        socket.close();
    }
}

From source file:org.kde.kdeconnect.Backends.LanBackend.LanLink.java

private void sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback,
        PublicKey key) {//from   w  w w . ja va  2  s.  co  m
    if (session == null) {
        Log.e("KDE/sendPackage", "Not yet connected");
        callback.sendFailure(new NotYetConnectedException());
        return;
    }

    try {

        //Prepare socket for the payload
        final ServerSocket server;
        if (np.hasPayload()) {
            server = openTcpSocketOnFreePort();
            JSONObject payloadTransferInfo = new JSONObject();
            payloadTransferInfo.put("port", server.getLocalPort());
            np.setPayloadTransferInfo(payloadTransferInfo);
        } else {
            server = null;
        }

        //Encrypt if key provided
        if (key != null) {
            np = np.encrypt(key);
        }

        //Send body of the network package
        WriteFuture future = session.write(np.serialize());
        future.awaitUninterruptibly();
        if (!future.isWritten()) {
            //Log.e("KDE/sendPackage", "!future.isWritten()");
            callback.sendFailure(future.getException());
            return;
        }

        //Send payload
        if (server != null) {
            OutputStream socket = null;
            try {
                //Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards
                server.setSoTimeout(10 * 1000);
                socket = server.accept().getOutputStream();

                Log.i("KDE/LanLink", "Beginning to send payload");

                byte[] buffer = new byte[4096];
                int bytesRead;
                long progress = 0;
                InputStream stream = np.getPayload();
                while ((bytesRead = stream.read(buffer)) != -1) {
                    //Log.e("ok",""+bytesRead);
                    progress += bytesRead;
                    socket.write(buffer, 0, bytesRead);
                    if (np.getPayloadSize() > 0) {
                        callback.sendProgress((int) (progress / np.getPayloadSize()));
                    }
                }
                socket.flush();
                stream.close();
                Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)");
            } catch (Exception e) {
                Log.e("KDE/sendPackage", "Exception: " + e);
                callback.sendFailure(e);
                return;
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
                try {
                    server.close();
                } catch (Exception e) {
                }
            }
        }

        callback.sendSuccess();

    } catch (Exception e) {
        if (callback != null) {
            callback.sendFailure(e);
        }
    } finally {
        //Make sure we close the payload stream, if any
        InputStream stream = np.getPayload();
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}