01: import java.text.DateFormat;
02: import java.util.ArrayList;
03: import java.util.Date;
04: import java.util.TimeZone;
05: 
06: /**
07:    This bean formats the local times of day for a given date
08:    and list of cities.
09: */
10: public class MultiZoneBean
11: { 
12:    /**
13:       Initializes the formatter and city list.
14:    */
15:    public MultiZoneBean()
16:    {
17:       timeFormatter = DateFormat.getTimeInstance();
18:       cities = new ArrayList();
19:    }
20: 
21:    /**
22:       Write-only date property. 
23:       @param aDate the date to be formatted.
24:    */
25:    public void setDate(Date aDate)
26:    {
27:       theDate = aDate;
28:    }
29: 
30:    /**
31:       Write-only city property. 
32:       @param aCity the city to add to the city list
33:    */
34:    public void setCity(String aCity)
35:    {
36:       cities.add(aCity);
37:    }
38: 
39:    /**
40:       Read-only times property.
41:       @return a string containing the HTML code for an unnumbered
42:       list of cities and local times
43:    */
44:    public String getTimes()
45:    {
46:       StringBuffer buffer = new StringBuffer();
47:       for (int i = 0; i < cities.size(); i++)
48:       {
49:          String city = (String)cities.get(i);
50: 
51:          buffer.append("<li>");
52:          buffer.append(city);
53:          buffer.append(": ");
54: 
55:          TimeZone zone = getTimeZone(city);
56:          if (zone == null) 
57:             buffer.append("not available");
58:          else
59:          { 
60:             timeFormatter.setTimeZone(zone);
61:             String timeString = timeFormatter.format(theDate);
62:             buffer.append(timeString);
63:          }
64:          buffer.append("</li>");            
65:       }
66:       return buffer.toString();
67:    }
68: 
69:    /**
70:       Looks up the time zone for a city
71:       @param aCity the city for which to find the time zone
72:       @return the time zone or null if no match is found
73:    */
74:    private static TimeZone getTimeZone(String city)
75:    {
76:       String[] ids = TimeZone.getAvailableIDs();
77:       for (int i = 0; i < ids.length; i++)
78:          if (timeZoneIDmatch(ids[i], city))
79:             return TimeZone.getTimeZone(ids[i]);
80:       return null;
81:    }
82: 
83:    /**
84:       Checks whether a time zone ID matches a city
85:       @param id the time zone ID (e.g. "America/Los_Angeles")
86:       @param aCity the city to match (e.g. "Los Angeles")
87:       @return true if the ID and city match
88:    */
89:    private static boolean timeZoneIDmatch(String id, String city)
90:    {
91:       String idCity = id.substring(id.indexOf('/') + 1);
92:       return idCity.replace('_', ' ').equals(city);
93:    }
94: 
95:    private DateFormat timeFormatter;
96:    private Date theDate;
97:    private ArrayList cities;
98: }
99: