Skip to content

Instantly share code, notes, and snippets.

@shekhargulati
Last active September 13, 2019 05:26
Show Gist options
  • Save shekhargulati/97055cd117b9d88daedfc8d52d37df43 to your computer and use it in GitHub Desktop.
Save shekhargulati/97055cd117b9d88daedfc8d52d37df43 to your computer and use it in GitHub Desktop.
Refactoring Example 2 - Status Checker
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
public class StatusChecker {
public WebsiteStatus getStatus(String url) {
WebsiteStatus websiteStatus = new WebsiteStatus();
String status = "DOWN";
HttpURLConnection connection = null;
long responseTime = 0;
try {
URL u = new URL(url);
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
long t1 = System.currentTimeMillis();
int code = connection.getResponseCode();
// You can determine on HTTP return code received. 200 is success.
responseTime = System.currentTimeMillis() - t1;
if (code == 200 || code == 301)
status = "UP";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
websiteStatus.setResponseTime(responseTime);
websiteStatus.setCurrentStatus(status);
websiteStatus.setCurrentTimestamp(new Date());
return websiteStatus;
}
}
class WebsiteStatus {
private long responseTime;
private String currentStatus;
private Date currentTimestamp;
public long getResponseTime() {
return responseTime;
}
public void setResponseTime(long responseTime) {
this.responseTime = responseTime;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
public Date getCurrentTimestamp() {
return currentTimestamp;
}
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment