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:pl.nask.hsn2.server.ServerTest.java

@Test
public void testServerStartsWithSocketConflict() throws Exception {
    ServerSocket s = null;
    try {//from  w  w w. j  av  a2s. co m
        s = tryToOpenServerSocket();
        TestHttpServer.startServer();
    } finally {
        if (s != null) {
            s.close();
        }
        TestHttpServer.stopServer();
    }
}

From source file:atg.tools.dynunit.nucleus.NucleusUtils.java

/**
 * This method returns a free port number on the current machine. There is
 * some chance that the port number could be taken by the time the caller
 * actually gets around to using it.// w  ww. ja va 2  s. c om
 * <p/>
 * This method returns -9999 if it's not able to find a port.
 */
public static int findFreePort() {
    ServerSocket socket = null;
    int freePort = -9999;
    try {
        socket = new ServerSocket(0);
        freePort = socket.getLocalPort();
    } catch (IOException e) {
        logger.catching(e);
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            logger.catching(e);
        }
    }
    return freePort;
}

From source file:org.sonatype.nexus.index.DownloadRemoteIndexerManagerTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    fakeCentral = new File(getBasedir(), "target/repos/fake-central");
    fakeCentral.mkdirs();//from w w w .  ja  v  a2 s.  co m

    // create proxy server
    ServerSocket s = new ServerSocket(0);
    int port = s.getLocalPort();
    s.close();

    server = new Server(port);

    ResourceHandler resource_handler = new ResourceHandler() {
        @Override
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            System.out.print("JETTY: " + target);
            super.handle(target, request, response, dispatch);
            System.out.println("  ::  " + ((Response) response).getStatus());
        }
    };
    resource_handler.setResourceBase(fakeCentral.getAbsolutePath());
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
    server.setHandler(handlers);

    System.out.print("JETTY Started on port: " + port);
    server.start();

    // update central to use proxy server
    central.setDownloadRemoteIndexes(true);
    central.setRemoteUrl("http://localhost:" + port);
    central.setRepositoryPolicy(RepositoryPolicy.SNAPSHOT);

    nexusConfiguration.saveConfiguration();

    Thread.sleep(100);

    wairForAsyncEventsToCalmDown();
    waitForTasksToStop();
}

From source file:org.apache.hadoop.mapred.TestHAWebUI.java

private Server createJettyServer() throws Exception {
    InetAddress localhost = InetAddress.getByName("localhost");
    String host = "localhost";
    ServerSocket ss = new ServerSocket(0, 50, localhost);
    int port = ss.getLocalPort();
    ss.close();
    Server server = new Server(0);
    server.getConnectors()[0].setHost(host);
    server.getConnectors()[0].setPort(port);
    return server;
}

From source file:com.zxy.commons.hystrix.HystrixProperties.java

/**
 * get hystrix stream port//  w w  w.  jav  a2s.  c  om
 * 
 * @return port
 * @throws IOException IOException
*/
public int getHystrixStreamPort() throws IOException {
    String portStr = env.getProperty(HYSTRIX_STREAM_PORT);
    if (StringUtils.isBlank(portStr)) {
        ServerSocket socket = new ServerSocket(0);
        try {
            return socket.getLocalPort();
        } finally {
            socket.close();
        }
    }
    return Integer.parseInt(portStr);
}

From source file:org.tdod.ether.ta.telnet.TelnetService.java

/**
 * Method to prepare the PortListener.<br>
 *
 * Creates and prepares and runs a PortListener, with settings from the
 * passed in Properties. Yet the Listener will not accept any incoming
 * connections before startServing() has been called. this has the advantage
 * that whenever a TelnetD Singleton has been factorized, it WILL 99% not
 * fail any longer (e.g. serve its purpose).
 *
 * @param   name            Name of listner.
 * @param     settings        Properties object that holds main settings.
 * @throws     BootException    Preparation failed.
 *///ww w .jav a 2s.  co  m
private void prepareListener(final String name, final Properties settings) throws BootException {

    int port = 0;
    try {
        port = Integer.parseInt(settings.getProperty(name + ".port"));
        ServerSocket socket = new ServerSocket(port);
        socket.close();
    } catch (NumberFormatException e) {
        _log.fatal(e, e);
        throw new BootException(
                "Failure while parsing port number for \"" + name + ".port\": " + e.getMessage());
    } catch (IOException e) {
        _log.fatal(e, e);
        throw new BootException(
                "Failure while starting listener for port number " + port + ": " + e.getMessage());
    }
    // factorize PortListener
    final PortListener listener = PortListener.createPortListener(name, settings);
    // start the Thread derived PortListener
    try {
        _listeners.add(listener);
    } catch (Exception e) {
        _log.fatal(e, e);
        throw new BootException("Failure while starting PortListener thread: " + e.getMessage());
    }

}

From source file:org.apache.solr.prometheus.exporter.SolrExporterTest.java

@Test
public void testExecute() throws Exception {
    // solr client
    CloudSolrClient cloudSolrClient = cluster.getSolrClient();

    int port;//from w  w w . j a v  a 2s . c  o m
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        port = socket.getLocalPort();
    } finally {
        socket.close();
    }

    // index sample docs
    File exampleDocsDir = new File(getFile("exampledocs").getAbsolutePath());
    List<File> xmlFiles = Arrays.asList(exampleDocsDir.listFiles((dir, name) -> name.endsWith(".xml")));
    for (File xml : xmlFiles) {
        ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update");
        req.addFile(xml, "application/xml");
        cloudSolrClient.request(req, "collection1");
    }
    cloudSolrClient.commit("collection1");

    // start exporter
    SolrExporter solrExporter = new SolrExporter(port, cloudSolrClient,
            getFile("conf/solr-exporter-config.xml").toPath(), 1);
    try {
        solrExporter.start();

        URI uri = new URI("http://localhost:" + String.valueOf(port) + "/metrics");

        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpGet request = new HttpGet(uri);
            response = httpclient.execute(request);

            int expectedHTTPStatusCode = HttpStatus.SC_OK;
            int actualHTTPStatusCode = response.getStatusLine().getStatusCode();
            assertEquals(expectedHTTPStatusCode, actualHTTPStatusCode);
        } finally {
            response.close();
            httpclient.close();
        }
    } finally {
        solrExporter.stop();
    }
}

From source file:com.netflix.hystrix.contrib.metrics.controller.HystricsMetricsControllerTest.java

@Override
protected Application configure() {
    int port = 0;
    try {/*from w  w w  .j a v a 2 s  . c  om*/
        final ServerSocket socket = new ServerSocket(0);
        port = socket.getLocalPort();
        socket.close();
    } catch (IOException e1) {
        throw new RuntimeException("Failed to find port to start test server");
    }
    set(TestProperties.CONTAINER_PORT, port);
    try {
        SystemConfiguration.setSystemProperties("test.properties");
    } catch (Exception e) {
        throw new RuntimeException("Failed to load config file");
    }
    return new ResourceConfig(HystricsMetricsControllerTest.class, HystrixStreamFeature.class);
}

From source file:com.splout.db.engine.EmbeddedMySQL.java

/**
 * TODO MySQL Hangs if port is busy, we should perform a timeout in a separate thred.
 *///from www  .  j  a  va2s  .  c  o  m
@SuppressWarnings({ "unchecked", "rawtypes" })
public void start(boolean deleteFilesIfExist) throws IOException, InterruptedException {
    if (deleteFilesIfExist && config.residentFolder.exists()) {
        File pidFile = new File(config.residentFolder, "data/MysqldResource.pid");
        if (pidFile.exists()) {
            // Issue "kill -9" if process is still alive
            String pid = Files.toString(pidFile, Charset.defaultCharset());
            log.info("Killing existing process: " + pid);
            Runtime.getRuntime().exec("kill -9 " + pid).waitFor();
        }
        log.info("Deleting contents of: " + config.residentFolder);
        FileUtils.deleteDirectory(config.residentFolder);
    }
    log.info("Using config: " + config);
    MysqldResource mysqldResource = new MysqldResource(config.residentFolder);
    Map<String, String> database_options = new HashMap();
    database_options.put(MysqldResourceI.PORT, Integer.toString(config.port));
    database_options.put(MysqldResourceI.INITIALIZE_USER, "true");
    database_options.put(MysqldResourceI.INITIALIZE_USER_NAME, config.user);
    database_options.put(MysqldResourceI.INITIALIZE_PASSWORD, config.pass);
    database_options.put("innodb-file-per-table", "true");

    if (config.customConfig != null) {
        for (Map.Entry<String, Object> entry : config.customConfig.entrySet()) {
            database_options.put(entry.getKey(), entry.getValue().toString());
        }
    }

    log.info("Using the following MySQL Configuration:");
    for (Map.Entry<String, String> entry : database_options.entrySet()) {
        log.info("MySQLConf: " + entry.getKey() + " -> " + entry.getValue());
    }
    // I have to do this checking myself, otherwise in some cases mysqldResource will block undefinitely...
    try {
        ServerSocket serverSocket = new ServerSocket(config.port);
        serverSocket.close();
    } catch (IOException e) {
        throw new RuntimeException("Port already in use: " + config.port);
    }
    if (mysqldResource.isRunning()) {
        throw new RuntimeException("MySQL already running!");
    }
    mysqldResource.start("test-mysqld-thread", database_options);
    if (!mysqldResource.isRunning()) {
        throw new RuntimeException("MySQL did not start successfully!");
    }
    log.info("MySQL is running.");
    resource = mysqldResource;
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnectorTest.java

/**
 * Find and return a free TCP port./*from www.j a v a 2s . co m*/
 *
 * @return port number
 */
private static Integer getFreePort() {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        socket.setReuseAddress(true);
        int port = socket.getLocalPort();
        try {
            socket.close();
        } catch (IOException e) {
            // Ignore IOException on close()
        }
        return port;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    throw new IllegalStateException("Unable to find a free TCP port.");
}