Skip to content

Instantly share code, notes, and snippets.

@rkuzsma
Created December 30, 2016 03:54
Show Gist options
  • Save rkuzsma/a5f45dcb5bfde6a2fea94ba73c755e3e to your computer and use it in GitHub Desktop.
Save rkuzsma/a5f45dcb5bfde6a2fea94ba73c755e3e to your computer and use it in GitHub Desktop.
Java utility class to wait for ports and URL responses to be available
/**
* General utilities to wait for ports and URL responses to be available.
* Especially useful when waiting for container services to be fully "up".
*/
public class WaitFor {
private static final Logger logger = LoggerFactory.getLogger(WaitFor.class.getClass());
public static void waitForPort(String hostname, int port, long timeoutMs) {
logger.info("Waiting for port " + port);
long startTs = System.currentTimeMillis();
boolean scanning=true;
while(scanning)
{
if (System.currentTimeMillis() - startTs > timeoutMs) {
throw new RuntimeException("Timeout waiting for port " + port);
}
try
{
SocketAddress addr = new InetSocketAddress(hostname, port);
Selector.open();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
try {
socketChannel.connect(addr);
}
finally {
socketChannel.close();
}
scanning=false;
}
catch(IOException e)
{
logger.debug("Still waiting for port " + port);
try
{
Thread.sleep(2000);//2 seconds
}
catch(InterruptedException ie){
logger.error("Interrupted", ie);
}
}
}
logger.info("Port " + port + " ready.");
}
public static void waitForResponse(String url, String response, int timeoutMS) {
logger.info("Waiting " + timeoutMS + "ms for " + url + " to respond with '" + response + '"');
long startTS = System.currentTimeMillis();
while (System.currentTimeMillis() - startTS < timeoutMS) {
try {
URL urlConnect = new URL(url);
URLConnection conn = urlConnect.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
try {
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
if (sb.toString().contains(response)) return;
}
finally {
try {
in.close();
}
catch (IOException e) {
// ignore and retry ...
}
}
} catch (IOException e) {
// assume site is not available yet, retry ...
}
}
throw new RuntimeException("Operation timed out");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment