01: import java.io.PrintWriter;
02: import java.io.IOException;
03: import java.text.DateFormat;
04: import java.util.Date;
05: import java.util.TimeZone;
06: import javax.servlet.ServletException;
07: import javax.servlet.http.HttpServlet;
08: import javax.servlet.http.HttpServletRequest;
09: import javax.servlet.http.HttpServletResponse;
10: 
11: /**
12:    This servlet prints out the current local time.
13:    The city name must be posted as value of the 
14:    "city" parameter.
15: */
16: public class TimeZoneServlet extends HttpServlet 
17: { 
18:    public void doPost(HttpServletRequest request, 
19:       HttpServletResponse response) 
20:       throws ServletException, IOException
21:    {
22:       // get information 
23: 
24:       String cityName = request.getParameter("city");
25:       TimeZone zone = getTimeZone(cityName);
26: 
27:       // set content type to HTML
28:       response.setContentType("text/html");  
29: 
30:       // print formatted information
31:       PrintWriter out = response.getWriter();  
32: 
33:       String title = "Time Zone Servlet";
34:       out.println("<html><head><title>");
35:       out.println(title);
36:       out.println("</title></head><body><h1>");
37:       out.print(title);
38:       out.println("</h1><p>");
39: 
40:       if (zone == null)
41:          out.println("Sorry--unknown city");
42:       else
43:       {
44:          out.print("The current time in <b>");
45:          out.print(cityName);
46:          out.print("</b> is: ");
47:          DateFormat formatter = DateFormat.getTimeInstance();
48:          formatter.setTimeZone(zone);
49:          Date now = new Date();
50:          out.print(formatter.format(now));
51:       }
52:       out.println("</p></body></html>");
53: 
54:       out.close();
55:    }
56: 
57:    /**
58:       Looks up the time zone for a city 
59:       @param aCity the city for which to find the time zone
60:       @return the time zone or null if no match is found
61:    */
62:    private static TimeZone getTimeZone(String city)
63:    {
64:       String[] ids = TimeZone.getAvailableIDs();
65:       for (int i = 0; i < ids.length; i++)
66:          if (timeZoneIDmatch(ids[i], city))
67:             return TimeZone.getTimeZone(ids[i]);
68:       return null;
69:    }
70: 
71:    /**
72:       Checks whether a time zone ID matches a city
73:       @param id the time zone ID (e.g. "America/Los_Angeles")
74:       @param aCity the city to match (e.g. "Los Angeles")
75:       @return true if the ID and city match
76:    */
77:    private static boolean timeZoneIDmatch(String id, String city)
78:    {
79:       String idCity = id.substring(id.indexOf('/') + 1);
80:       return idCity.replace('_', ' ').equals(city);
81:    }
82: }
83: