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:org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java

/**
 * Function to wait and verify iteratively whether port is successfully closed, till timeout reaches
 *
 * @param port target port/*  ww w . j a v  a2  s .  c  om*/
 * @param portCloseVerifyTimeout iterative verification timeout
 * @return
 */
private boolean isPortCloseSuccess(int port, int portCloseVerifyTimeout) {
    boolean portCloseSuccess = false;
    for (int i = 0; i < portCloseVerifyTimeout; i++) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Verify port [" + port + "] close status. Attempt: " + i);
            }
            //Try to bind ServerSocket to port and verify whether port is successfully closed
            ServerSocket srv = new ServerSocket(port);
            srv.close();
            srv = null;
            //If reach here, port close successful
            portCloseSuccess = true;
            break;
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug("The port " + port + " is not closed yet, verify again after waiting 1s", e);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptException) {
                //log and ignore
            }
        }
    }
    return portCloseSuccess;
}

From source file:IntergrationTest.OCSPIntegrationTest.java

/**
 * Method to test a port is available.//  ww w .  ja  v  a 2 s .c o m
 *
 * @param port
 *
 * @return
 */
private boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }
    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }
        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }
    return false;
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void connectTimeout() throws Exception {
    // Pick a free port with no server running
    ServerSocket ss = new ServerSocket(0);
    int serverPort = ss.getLocalPort();
    ss.close();

    set(client + ".niws.client.ConnectTimeout", "100");
    int code = 200;
    statusCode.set(code);//www  .java2  s.  co  m

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get("niws://test/http://localhost:" + serverPort + "/empty").subscribe(Actions.empty(),
            new Action1<Throwable>() {
                @Override
                public void call(Throwable t) {
                    throwable.set(t);
                    latch.countDown();
                }
            }, new Action0() {
                @Override
                public void call() {
                    latch.countDown();
                }
            });

    latch.await();
    Assert.assertTrue(throwable.get() instanceof ConnectException);
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Close an server socket without exceptions.
 * <p>/* w  w  w.  ja v  a2  s  . co m*/
 * For Java 6 backward comparability.
 *
 * @param socket
 *            server socket to close
 */
public static void close(ServerSocket socket) {
    if (socket != null) {
        try {
            socket.close();
        } catch (IOException exc) {

        }
    }
}

From source file:hudson.plugins.selenium.PluginImpl.java

public Object readResolve() {
    // Update from plugin 2.0 to 2.1 where browsers were introduced
    if (rcFirefoxProfileTemplate != null || rcBrowserSessionReuse != null || rcTrustAllSSLCerts != null
            || rcBrowserSideLog != null) {
        String rcFirefoxProfileTemplate = getDefaultForNull(this.rcFirefoxProfileTemplate, "");
        Boolean rcBrowserSessionReuse = getDefaultForNull(this.rcBrowserSessionReuse, Boolean.FALSE);
        Boolean rcTrustAllSSLCerts = getDefaultForNull(this.rcTrustAllSSLCerts, Boolean.FALSE);
        Boolean rcBrowserSideLog = getDefaultForNull(this.rcBrowserSideLog, Boolean.FALSE);

        List<SeleniumBrowser> browsers = new ArrayList<SeleniumBrowser>();
        browsers.add(new IEBrowser(5, "", ""));
        browsers.add(new FirefoxBrowser(5, "", ""));
        browsers.add(new ChromeBrowser(5, "", ""));

        int port = 4445;
        try {/*from  w w w  .j  a v a2s.  c o m*/
            ServerSocket ss = new ServerSocket(0);
            port = ss.getLocalPort();
            ss.close();
        } catch (IOException e) {
        }

        SeleniumNodeConfiguration c = new CustomRCConfiguration(port, rcBrowserSideLog, rcDebug,
                rcTrustAllSSLCerts, rcBrowserSessionReuse, -1, rcFirefoxProfileTemplate, browsers, null);

        synchronized (configurations) {
            configurations.add(
                    new SeleniumGlobalConfiguration("Selenium v2.0 configuration", new MatchAllMatcher(), c));
        }

    }

    // update to 2.3 where hostname options were introduced
    if (hostnameResolver == null) {
        hostnameResolver = new JenkinsRootHostnameResolver();
    }

    return this;
}

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

/**
 * TearDown method for test method testPythonCartridgeAgent
 *///from   ww w . ja v  a 2  s  .  com
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);
}

From source file:hudson.remoting.Launcher.java

/**
 * Listens on an ephemeral port, record that port number in a port file,
 * then accepts one TCP connection./* w w w  . j a v  a 2s .  c  o  m*/
 */
private void runAsTcpServer() throws IOException, InterruptedException {
    // if no one connects for too long, assume something went wrong
    // and avoid hanging foreever
    ServerSocket ss = new ServerSocket(0, 1);
    ss.setSoTimeout(30 * 1000);

    // write a port file to report the port number
    FileWriter w = new FileWriter(tcpPortFile);
    w.write(String.valueOf(ss.getLocalPort()));
    w.close();

    // accept just one connection and that's it.
    // when we are done, remove the port file to avoid stale port file
    Socket s;
    try {
        s = ss.accept();
        ss.close();
    } finally {
        tcpPortFile.delete();
    }

    runOnSocket(s);
}

From source file:uk.co.unclealex.persistence.hbase.testing.HBaseTestContainer.java

/**
 * Configure ports either statically or dynamically. This method is called
 * recursively (and hence why an {@link Iterator} is an argument) to allow the
 * compiler to correctly check that all port resources are closed.
 * //from ww  w  . jav  a 2  s. c o  m
 * @param portIterator
 *          An {@link Iterator} for the remaining ports to configure.
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
protected void configurePorts(Iterator<Port> portIterator) throws IOException {
    if (portIterator.hasNext()) {
        Port port = portIterator.next();
        Integer portNumber = getFixedPorts().get(port);
        if (portNumber == null) {
            portNumber = 0;
        }
        ServerSocket serverSocket = new ServerSocket(portNumber);
        try {
            int localPort = serverSocket.getLocalPort();
            LOG.info("Using port " + localPort + " for property " + port.getPropertyName());
            getConfiguration().setInt(port.getPropertyName(), localPort);
            getPorts().put(port, localPort);
            configurePorts(portIterator);
        } finally {
            serverSocket.close();
        }
    }
}

From source file:org.reficio.cougar.impl.ConnectionFactoryTest.java

private int startMockServer() {
    final int port = TestUtil.getFreePort();
    final CountDownLatch latch = new CountDownLatch(1);
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                ServerSocket srv = new ServerSocket(port, 0, InetAddress.getByName(null));
                latch.countDown();//from w w  w  . j  a  v  a 2s  . co  m
                try {
                    srv.setSoTimeout(15000);
                    Socket comm = srv.accept();
                    Frame response = new Frame(Command.CONNECTED);
                    response.session(UUID.randomUUID().toString());
                    StompWireFormat wireFormat = new WireFormatImpl();
                    OutputStream out = comm.getOutputStream();
                    Writer writer = new OutputStreamWriter(out);
                    wireFormat.marshal(response, writer);
                    writer.close();
                } finally {
                    srv.close();
                }
            } catch (IOException e) {
                log.error("IO exception", e);
            }
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
    try {
        latch.await();
    } catch (InterruptedException e) {
    }
    return port;
}