/* Example Servlet provides an hourly hit counter */

import java.util.*;
import java.text.DateFormat;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class WebCounter extends HttpServlet {
    static int counter;
    static int lasthour;
    public String getServletInfo() {
      return "WebCounter $Revision: 1.0 $.\nby Al Williams " ;
    }
  /**
   * Set up initial count
   **/
   public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
    // Write message to servlet.log
    System.err.println("WebCounter initializing!");
    if (counter!=0) System.err.println(
      "WebCounter:Warning Init called more than once");
    lasthour=-1;  // make sure we start fresh
  }


    /**	
    * Service the request.
 	*
 	* @exception ServletException If a ServletException occurred
	*
	*/
    public void service(HttpServletRequest request,
			HttpServletResponse response)
	 throws IOException, ServletException
    {
            Date date=new Date(); // current date
	Calendar cal=Calendar.getInstance();
	DateFormat fmt=DateFormat.getDateTimeInstance();
	cal.setTime(date);
	// check to see if we have a new hour
	// this code assumes we get visitors every hour
	// (or at least every 12 hours)
	// so no need to check the day or AM/PM, etc.
	if (lasthour==cal.get(Calendar.HOUR))
	  {
	    counter++;
	  }
	else
	  {
	   lasthour=cal.get(Calendar.HOUR);
	   counter=1;
	  }
	// Write it out
	response.setContentType("text/html");

	ServletOutputStream out = response.getOutputStream();
	out.println("It is now " + fmt.format(date));
	out.println("You are visitor # " + counter + " this hour.");
    }

}