Unix Script + Java = Solve tasks easily.
The example given below shows the way the unix scripts and other programs (in this case, it is java program) can be combined to tackle simple problems.
The example script calls a java program to check the status of a URL. The Shell script gets the list of all URLs that needs to be checked via a file urlList and checks the status of each of the URL via the java program com.util.GetHttpResponse and then if the response is not equal to 200, sends a mail.
The java program to check the status of the URL can be replaced by any program that provides the same functionality. This program shows how unix shell scripts can be combined effortlessly to solve tasks.
There are a numerous way to get the status code of a HTTP URL. The post shows using Java. This simple tool can be used to check the status of a list of URLs and if down send information to the concerned person. This script can be invoked through cron to regularly check the state of URLs. This can be extended to check the state of other protocols also.
The unix shell script.
#!/bin/ksh
# Visit http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for
# more information in HTTP Status Response Code
# Response of 200 specifies successful Request
for eachUrl in `cat urlList`
do
responseStatusCode=`java com.util.GetHttpResponse $eachUrl`
echo "URL: $eachUrl RESPONSE CODE: $responseStatusCode"
if [[ $responseStatusCode != "200" ]]
then
mailx -s "The URL $eachUrl did not return successful
 request status. The HTTP response status is
$responseStatusCode. Please Check."
someone@somewhere.com
fi
done
The java Class com.util.GetHttpResponse.
package com.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class GetHttpResponse {
public static void main(String[] args) {
new GetHttpResponse().getWebPage(args[0]);
}
public void getWebPage(String pageUrl) {
if (pageUrl == null) {
throw new IllegalArgumentException("pageUrl cannot be null");
}
try {
URL webPageUrl = new URL(pageUrl);
HttpURLConnection conn = (HttpURLConnection) webPageUrl.openConnection();
conn.setRequestMethod("GET");
System.out.println(conn.getResponseCode());
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
For Complete details on HTTP Status response code, visit
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

