1

I just made a url connection to local host:8080 and checked the http response code between 200-209 using JBOSS server.

public class Welcome extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
URL url = new URL("http://localhost:8080");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
System.out.println("code=="+code);
if (code>=200 && code <= 209){

       pw.println("<h1>Welcome....</h1>");
       pw.println("<p>Service is accessable</p>");


    }
else 

{System.out.println("service is denied");}
    }}

If HTTP Response code outside of 200-209 or unable to make connection, then it has to perform the following steps:

1)If Jboss Service is running, then restart.

2)If Jboss Service is not running, then start it.

Now here I want to know how can programmatically know whether Server is running or not in order to perform above 2 steps.. Please help me..Thanks you

AB Bolim
  • 1,997
  • 2
  • 23
  • 47

2 Answers2

2

You should catch the IOException that rise when a timeout (server not running at all) occurs.

Something like this:

public class Welcome extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
URL url = new URL("http://localhost:8080");

try {
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
} catch (IOException ex) {
    // (probably) service is not running 
    // start service
    return;
}

connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
System.out.println("code=="+code);
if (code>=200 && code <= 209){

       pw.println("<h1>Welcome....</h1>");
       pw.println("<p>Service is accessable</p>");


    }
else 

{System.out.println("service is denied");}
    }}
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
  • Thanks.. but I am not understanding clearly about that...could you please describe briefly about this steps :If HTTP Response code outside of 200-209, then it has to perform the following steps: 1)If Jboss Service is running, then restart. 2)If Jboss Service is not running, then start it – user2249134 Apr 06 '13 at 11:11
1

I think this is something already discussed. You need to catch exception for that. You may want to look into something like this

Community
  • 1
  • 1
IndoKnight
  • 1,846
  • 1
  • 21
  • 29
  • Could you please have a look on this: If HTTP Response code outside of 200-209 or unable to make connection, then it has to perform the following steps: 1)If Jboss Service is running, then restart. 2)If Jboss Service is not running, then start it. – user2249134 Apr 06 '13 at 11:08