Java HTTP Port Find waitForLiveServer(String webContainerHostname, int webContainerPort, int timeoutMin)

Here you can find the source of waitForLiveServer(String webContainerHostname, int webContainerPort, int timeoutMin)

Description

wait For Live Server

License

Open Source License

Declaration

public static void waitForLiveServer(String webContainerHostname, int webContainerPort, int timeoutMin) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Main {
    public static void waitForLiveServer(String webContainerHostname, int webContainerPort, int timeoutMin) {
        InetSocketAddress address = new InetSocketAddress(webContainerHostname, webContainerPort);

        System.out.println("Waiting " + timeoutMin + " min for web server...");

        long beginTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis() + (timeoutMin * 60 * 1000);

        boolean portOpened = false;
        while ((!portOpened) && (System.currentTimeMillis() < endTime)) {
            portOpened = trySocket(address);

            if (portOpened) {
                System.out.println("Web server has opened the port in "
                        + (System.currentTimeMillis() - beginTime) / 1000.0 / 60.0 + " min.");
            } else {
                try {
                    Thread.sleep(2000); // 2 seconds
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }//ww  w  . j  a va  2  s  . c  o m
            }
        }
        if (!portOpened) {
            throw new RuntimeException("Timed out waiting for webapp server to initialize");
        }
    }

    private static boolean trySocket(InetSocketAddress address) {
        boolean success = false;

        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(address);
            success = true;
        } catch (ConnectException e) {
            // this is expected
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
}

Related

  1. sendCommand(String host, Integer port, String cmd)
  2. serverIsUp(int port)
  3. ServerListening(String host, int port)
  4. serverListening(String host, int port)
  5. serverListening(String hostName, int port)
  6. waitForPort(String host, int port)
  7. waitForResponseCode(int code, String name, String host, int port)
  8. waitForRespose(String name, String host, int port)
  9. waitForServerDown(String host, int port, long timeout)