The example of this article describes the Java implementation to monitor whether Tomcat is down and control the restart method. Share to everyone for your reference. Specifically as follows:
Detector.java:
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.util.Date; /** * * @author James * */public class Detector {private static void Keeptomcatalive () throws NullPointerException {St
Ring S;
String t = new string ("Tomcat6");
Boolean istomcatalive = false;
Java.io.BufferedReader in;
System.setproperty ("Sun.net.client.defaultConnectTimeout", "8000");
System.setproperty ("Sun.net.client.defaultReadTimeout", "10000");
try {URL url = new URL ("http://localhost:8080/test.jsp");
URLConnection con = url.openconnection ();
in = new Java.io.BufferedReader (New Java.io.InputStreamReader (Con.getinputstream ()));
Con.setconnecttimeout (1000);
Con.setreadtimeout (4000);
while (s = in.readline ())!= null) {if (s.length () > 0) {//accessed page successful.
Return
} in.close ();
catch (Exception ex) {//ex.printstacktrace ();
try {java.lang.Process p = java.lang.Runtime.getRuntime (). EXEC ("Ps-aux"); in = new Java.io.BufferedReader (new Java. Io.
InputStreamReader (P.getinputstream ()));
while ((s = in.readline ())!= null) {if (S.startswith (t)) {istomcatalive = true;
Break
} in.close (); }catch (Exception e) {e.printstacktrace ();} if (istomcatalive) {System.out.println ("<" + new Date () + > TOMC
At are alive but not response! ");
Stoptomcat ();
} starttomcat (); public static void Stoptomcat () {try {java.lang.Process P = java.lang.Runtime.getRuntime (). EXEC ("/etc/init.d/tom
Cat6 stop ");
Java.io.BufferedReader in = new Java.io.BufferedReader (New Java.io.InputStreamReader (P.getinputstream ()));
String s;
String t = "stopping";
Boolean restart = false;
while ((s = in.readline ())!= null) {if (S.indexof (t)!=-1) {restart = true;
Break } System.out.println ("<" + new Date () + > Tomcat is stop + (restart?)
OK ":" ERROR "));
catch (Exception e) {e.printstacktrace ();
The public static void Starttomcat () {try { Java.lang.Process p = java.lang.Runtime.getRuntime (). EXEC ("/etc/init.d/tomcat6 start");
Java.io.BufferedReader in = new Java.io.BufferedReader (New Java.io.InputStreamReader (P.getinputstream ()));
String s;
String t = "starting";
Boolean restart = false;
while ((s = in.readline ())!= null) {if (S.indexof (t)!=-1) {restart = true;
Break } System.out.println ("<" + new Date () + > Tomcat is start + (restart?)
OK ":" ERROR "));
catch (Exception e) {e.printstacktrace ();
} private static void Debug (String msg) {System.out.println ("debug::;" +msg);} public static void Main (string[] args {while (true) {try {Debug) ("Detect Agin <" +new Date (
) + ">");
Detector.keeptomcatalive ();
Debug ("Sleep ...");
Thread.Sleep (30000);
catch (Exception ex) {ex.printstacktrace ();
}
}
}
}
I hope this article will help you with your Java programming.