// From "Big Java" (1st edition) by Cay Horstmann, Wiley & Sons
// Chapter 25

import java.io.PrintWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
   This servlet prints out the current local time.
   The city name must be posted as value of the
   "city" parameter.
*/
public class TimeZoneServlet extends HttpServlet
{
   public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
   {
      // Get information
      String cityName = request.getParameter("city");
      TimeZone zone = getTimeZone(cityName);

      // Set content type to HTML
      response.setContentType("text/html");

      // Print formatted information
      PrintWriter out = response.getWriter();

      String title = "Time Zone Servlet";
      out.println("<html><head><title>");
      out.println(title);
      out.println("</title></head><body><h1>");
      out.print(title);
      out.println("</h1><p>");

      if (zone == null)
         out.println("Sorry--unknown city");
      else
      {
         out.print("The current time in <b>");
         out.print(cityName);
         out.print("</b> is: ");
         DateFormat formatter = DateFormat.getTimeInstance();
         formatter.setTimeZone(zone);
         Date now = new Date();
         out.print(formatter.format(now));
      }
      out.println("</p></body></html>");

      out.close();
   }

   /**
      Looks up the time zone for a city
      @param aCity the city for which to find the time zone
      @return the time zone or null if no match is found
   */
   private static TimeZone getTimeZone(String city)
   {
      String[] ids = TimeZone.getAvailableIDs();
      for (int i = 0; i < ids.length; i++)
         if (timeZoneIDmatch(ids[i], city))
            return TimeZone.getTimeZone(ids[i]);
      return null;
   }

   /**
      Checks whether a time zone ID matches a city
      @param id the time zone ID (e.g. "America/Los_Angeles")
      @param aCity the city to match (e.g. "Los Angeles")
      @return true if the ID and city match
   */
   private static boolean timeZoneIDmatch(String id, String city)
   {
      String idCity = id.substring(id.indexOf('/') + 1);
      return idCity.replace('_', ' ').equals(city);
   }
}

