Example usage for java.net ServerSocket getLocalSocketAddress

List of usage examples for java.net ServerSocket getLocalSocketAddress

Introduction

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

Prototype


public SocketAddress getLocalSocketAddress() 

Source Link

Document

Returns the address of the endpoint this socket is bound to.

Usage

From source file:Main.java

/**
 * Renders the details of a server socket in the returned string
 * @param socket The server socket to render
 * @return the details of the server socket as a string
 *///  ww  w .  ja  v  a 2 s .c  o m
public static String render(ServerSocket socket) {
    if (socket == null)
        return "NULL";
    StringBuilder b = new StringBuilder("\nSocket [");
    b.append("\n\tLocalPort:").append(socket.getLocalPort());
    b.append("\n\tLocalAddress:").append(socket.getInetAddress());
    b.append("\n\tLocalSocketAddress:").append(socket.getLocalSocketAddress());
    b.append("\n\tChannel:").append(socket.getChannel());
    b.append("\n\tHashCode:").append(socket.hashCode());
    b.append("\n]");
    return b.toString();
}

From source file:com.cloudant.tests.CloudantClientTests.java

/**
 * Check that the connection timeout throws a SocketTimeoutException when it can't connect
 * within the timeout.//from w w w.  ja v a 2 s  .  co m
 */
@Test(expected = SocketTimeoutException.class)
public void connectionTimeout() throws Throwable {

    ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 1);

    //block the single connection to our server
    Socket socket = new Socket();
    socket.connect(serverSocket.getLocalSocketAddress());

    //now try to connect, but should timeout because there is no connection available
    try {
        CloudantClient c = ClientBuilder.url(new URL("http://127.0.0.1:" + serverSocket.getLocalPort()))
                .connectTimeout(100, TimeUnit.MILLISECONDS).build();

        // Make a request
        c.getAllDbs();
    } catch (CouchDbException e) {
        //unwrap the CouchDbException
        if (e.getCause() != null) {
            //whilst it would be really nice to actually assert that this was a connect
            //exception and not some other SocketTimeoutException there are JVM differences in
            //this respect (i.e. OpenJDK does not appear to distinguish between read/connect)
            //in its exception messages
            throw e.getCause();
        } else {
            throw e;
        }
    } finally {
        //make sure we close the sockets
        IOUtils.closeQuietly(serverSocket);
        IOUtils.closeQuietly(socket);
    }
}

From source file:org.apache.camel.itest.http.HttpTestServer.java

/**
 * Obtains the local address the server is listening on
 *
 * @return the service address//from w w w.  j av  a  2 s  .co  m
 */
public InetSocketAddress getServiceAddress() {
    ServerSocket ssock = servicedSocket; // avoid synchronization
    if (ssock == null) {
        throw new IllegalStateException("not running");
    }
    return (InetSocketAddress) ssock.getLocalSocketAddress();
}

From source file:org.apache.http.localserver.LocalTestServer.java

/**
 * Obtains the local address the server is listening on
 *
 * @return the service address/*from  w w w  .  j  av  a2 s  . c  om*/
 */
public SocketAddress getServiceAddress() {
    ServerSocket ssock = servicedSocket; // avoid synchronization
    if (ssock == null)
        throw new IllegalStateException("not running");

    return ssock.getLocalSocketAddress();
}

From source file:org.apache.http.localserver.LocalTestServer.java

/**
 * Obtains the hostname of the server.//from w ww.  j  a v a2s.  com
 *
 * @return  the hostname
 */
public String getServiceHostName() {
    ServerSocket ssock = servicedSocket; // avoid synchronization
    if (ssock == null)
        throw new IllegalStateException("not running");

    return ((InetSocketAddress) ssock.getLocalSocketAddress()).getHostName();
}

From source file:org.apache.camel.itest.http.HttpTestServer.java

@Override
public String toString() {
    ServerSocket ssock = servicedSocket; // avoid synchronization
    StringBuilder sb = new StringBuilder(80);
    sb.append("LocalTestServer/");
    if (ssock == null) {
        sb.append("stopped");
    } else {/*from  w  w w  .  j  a  va 2s .c  om*/
        sb.append(ssock.getLocalSocketAddress());
    }
    return sb.toString();
}

From source file:org.apache.http.localserver.LocalTestServer.java

@Override
public String toString() {
    ServerSocket ssock = servicedSocket; // avoid synchronization
    StringBuffer sb = new StringBuffer(80);
    sb.append("org.apache.http.localserver.LocalTestServer/");
    if (ssock == null)
        sb.append("stopped");
    else/*  w w  w  . j  a  va2s.  c  o m*/
        sb.append(ssock.getLocalSocketAddress());
    return sb.toString();
}

From source file:org.apache.hadoop.hdfs.server.datanode.CachingDataNode.java

private void reconfigureDataXceiver(final Configuration conf) throws IOException {

    final ServerSocket ss = ((DataXceiverServer) this.dataNode.dataXceiverServer.getRunnable()).ss;

    // Shut down old dataXceiverServer and replace it with our version
    if (this.dataNode.dataXceiverServer != null) {
        ((DataXceiverServer) this.dataNode.dataXceiverServer.getRunnable()).kill();
        this.dataNode.dataXceiverServer.interrupt();

        // wait for all data receiver threads to exit
        if (this.dataNode.threadGroup != null) {
            int sleepMs = 2;
            while (true) {
                this.dataNode.threadGroup.interrupt();
                LOG.info("Waiting for threadgroup to exit, active threads is "
                        + this.dataNode.threadGroup.activeCount());
                if (this.dataNode.threadGroup.activeCount() == 0) {
                    break;
                }// www .  j a v a2 s  . c o m
                try {
                    Thread.sleep(sleepMs);
                } catch (InterruptedException e) {
                }
                sleepMs = sleepMs * 3 / 2; // exponential backoff
                if (sleepMs > 1000) {
                    sleepMs = 1000;
                }
            }
        }
        // wait for dataXceiveServer to terminate
        try {
            this.dataNode.dataXceiverServer.join();
        } catch (InterruptedException ie) {
        }
    }

    // find free port or use privileged port provided
    final ServerSocket newServerSocket = (dnConf.socketWriteTimeout > 0) ? ServerSocketChannel.open().socket()
            : new ServerSocket();
    newServerSocket.setReceiveBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE);
    Server.bind(newServerSocket, (InetSocketAddress) ss.getLocalSocketAddress(), 0);
    newServerSocket.setReceiveBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE);

    this.dataNode.threadGroup = new ThreadGroup("cachingDataXceiverServer");
    this.dataNode.dataXceiverServer = new Daemon(this.dataNode.threadGroup,
            new CachingDataXceiverServer(newServerSocket, conf, this.dataNode, this.blockCache));
    this.dataNode.threadGroup.setDaemon(true); // auto destroy when empty
}

From source file:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java

@After
public void tearDown() {
    for (Map.Entry<String, Executor> entry : executorList.entrySet()) {
        try {//from  ww w .jav a  2s.  c o m
            String commandText = entry.getKey();
            Executor executor = entry.getValue();
            ExecuteWatchdog watchdog = executor.getWatchdog();
            if (watchdog != null) {
                log.info("Terminating process: " + commandText);
                watchdog.destroyProcess();
            }
            //                File workingDirectory = executor.getWorkingDirectory();
            //                if (workingDirectory != null) {
            //                    log.info("Cleaning working directory: " + workingDirectory.getAbsolutePath());
            //                    FileUtils.deleteDirectory(workingDirectory);
            //                }
        } catch (Exception ignore) {
        }
    }
    for (ServerSocket serverSocket : serverSocketList) {
        try {
            log.info("Stopping socket server: " + serverSocket.getLocalSocketAddress());
            serverSocket.close();
        } catch (IOException e) {
            log.info("Couldn't stop socket server " + serverSocket.getLocalSocketAddress() + ", "
                    + e.getMessage());
        }
    }

    try {
        log.info("Deleting source checkout folder...");
        FileUtils.deleteDirectory(new File("/tmp/test-jca-source"));
    } catch (Exception ignore) {
    }

    //this.instanceStatusEventReceiver.terminate();
    //  this.topologyEventReceiver.terminate();

    this.instanceActivated = false;
    this.instanceStarted = false;
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

/**
 * TearDown method for test method testPythonCartridgeAgent
 *///from  w  ww.j  a v  a2s.co m
protected void tearDown(String sourcePath) {
    for (Map.Entry<String, Executor> entry : executorList.entrySet()) {
        try {
            String commandText = entry.getKey();
            Executor executor = entry.getValue();
            log.info("Terminating process: " + commandText);
            executor.setExitValue(0);
            executor.getWatchdog().destroyProcess();
        } catch (Exception ignore) {
        }
    }
    // wait until everything cleans up to avoid connection errors
    sleep(1000);
    for (ServerSocket serverSocket : serverSocketMap.values()) {
        try {
            log.info("Stopping socket server: " + serverSocket.getLocalSocketAddress());
            serverSocket.close();
        } catch (IOException ignore) {
        }
    }
    try {
        if (thriftTestServer != null) {
            thriftTestServer.stop();
        }
    } catch (Exception ignore) {
    }

    if (sourcePath != null) {
        try {
            log.info("Deleting source checkout folder...");
            FileUtils.deleteDirectory(new File(sourcePath));
        } catch (Exception ignore) {
        }
    }
    log.info("Terminating event receivers...");
    this.instanceStatusEventReceiver.terminate();
    this.topologyEventReceiver.terminate();
    this.initializerEventReceiver.terminate();

    this.instanceStatusEventReceiver = null;
    this.topologyEventReceiver = null;
    this.initializerEventReceiver = null;

    this.instanceActivated = false;
    this.instanceStarted = false;

    // stop the broker services
    for (Map.Entry<String, BrokerService> entry : this.messageBrokers.entrySet()) {
        try {
            log.debug("Stopping broker service [" + entry.getKey() + "]");
            entry.getValue().stop();
        } catch (Exception ignore) {
        }
    }

    this.messageBrokers = null;

    // TODO: use thread synchronization and assert all connections are properly closed
    // leave some room to clear up active connections
    sleep(1000);
}