1   package org.mortbay.util.ajax;
2   
3   import java.text.DateFormatSymbols;
4   import java.text.SimpleDateFormat;
5   import java.util.Date;
6   import java.util.Locale;
7   import java.util.Map;
8   import java.util.TimeZone;
9   
10  import org.mortbay.log.Log;
11  import org.mortbay.util.DateCache;
12  import org.mortbay.util.ajax.JSON.Output;
13  
14  /* ------------------------------------------------------------ */
15  /**
16  * Convert a {@link Date} to JSON.
17  * If fromJSON is true in the constructor, the JSON generated will
18  * be of the form {class="java.util.Date",value="1/1/1970 12:00 GMT"}
19  * If fromJSON is false, then only the string value of the date is generated.
20  */
21  public class JSONDateConvertor implements JSON.Convertor
22  {
23      private boolean _fromJSON;
24      DateCache _dateCache;
25      SimpleDateFormat _format;
26  
27      public JSONDateConvertor()
28      {
29          this(false);
30      }
31  
32      public JSONDateConvertor(boolean fromJSON)
33      {
34          this(DateCache.DEFAULT_FORMAT,TimeZone.getTimeZone("GMT"),fromJSON);
35      }
36      
37      public JSONDateConvertor(String format,TimeZone zone,boolean fromJSON)
38      {
39          _dateCache=new DateCache(format);
40          _dateCache.setTimeZone(zone);
41          _fromJSON=fromJSON;
42          _format=new SimpleDateFormat(format);
43          _format.setTimeZone(zone);
44      }
45      
46      public JSONDateConvertor(String format, TimeZone zone, boolean fromJSON, Locale locale)
47      {
48          _dateCache = new DateCache(format, locale);
49          _dateCache.setTimeZone(zone);
50          _fromJSON = fromJSON;
51          _format = new SimpleDateFormat(format, new DateFormatSymbols(locale));
52          _format.setTimeZone(zone);
53      }
54      
55      public Object fromJSON(Map map)
56      {
57          if (!_fromJSON)
58              throw new UnsupportedOperationException();
59          try
60          {
61              synchronized(_format)
62              {
63                  return _format.parseObject((String)map.get("value"));
64              }
65          }
66          catch(Exception e)
67          {
68              Log.warn(e);  
69          }
70          return null;
71      }
72  
73      public void toJSON(Object obj, Output out)
74      {
75          String date = _dateCache.format((Date)obj);
76          if (_fromJSON)
77          {
78              out.addClass(obj.getClass());
79              out.add("value",date);
80          }
81          else
82          {
83              out.add(date);
84          }
85      }
86  
87  }