Created
September 13, 2019 09:40
-
-
Save shekhargulati/dad6fe76f09b5169834080bffa4fb0f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
public class HttpClient { | |
public int getHttResponseCode(String url) throws RuntimeException { | |
HttpURLConnection connection = null; | |
try { | |
URL u = new URL(url); | |
connection = (HttpURLConnection) u.openConnection(); | |
connection.setRequestMethod("HEAD"); | |
return connection.getResponseCode(); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} finally { | |
if (connection != null) { | |
connection.disconnect(); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Date; | |
public class StatusChecker { | |
HttpClient httpClient; | |
public StatusChecker(HttpClient httpClient) { | |
this.httpClient = httpClient; | |
} | |
public WebsiteStatus getWebsiteStatus(String url) { | |
String status = "DOWN"; | |
long startTime = System.currentTimeMillis(); | |
int httpResponseCode = httpClient.getHttResponseCode(url); | |
long responseTime = System.currentTimeMillis() - startTime; | |
if (isStatusGood(httpResponseCode)) { | |
status = "UP"; | |
} | |
return new WebsiteStatus(responseTime, status); | |
} | |
private boolean isStatusGood(int httpResponseCode) { | |
return httpResponseCode == 200 || httpResponseCode == 301; | |
} | |
public static void main(String[] args) { | |
StatusChecker statusChecker= new StatusChecker(new HttpClient()); | |
WebsiteStatus googleStatus = statusChecker.getWebsiteStatus("google.com"); | |
WebsiteStatus xebiaStatus = statusChecker.getWebsiteStatus("xebia.com"); | |
} | |
} | |
class WebsiteStatus { | |
private final long responseTime; | |
private final String currentStatus; | |
private final Date currentTimestamp; | |
public WebsiteStatus(long responseTime, String status) { | |
this.responseTime = responseTime; | |
this.currentStatus = status; | |
this.currentTimestamp = new Date(); | |
} | |
public long getResponseTime() { | |
return responseTime; | |
} | |
public String getCurrentStatus() { | |
return currentStatus; | |
} | |
public Date getCurrentTimestamp() { | |
return currentTimestamp; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment