View Javadoc
1   /*
2    *  Copyright 2010, 2011 Chris Pheby
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package org.jadira.bindings.core.jdk;
17  
18  import java.text.ParseException;
19  import java.text.SimpleDateFormat;
20  import java.util.Date;
21  import java.util.TimeZone;
22  
23  import org.jadira.bindings.core.api.Binding;
24  
25  /**
26   * Binds a Date to a String. Date String binding always uses the GMT zone to render.... if you 
27   * want control over the zone, use CalendarStringBinding instead or better still use JodaTime or JSR310.
28   */
29  public class DateStringBinding extends AbstractStringBinding<Date> implements Binding<Date, String> {
30  
31      private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
32          @Override
33          public SimpleDateFormat initialValue() {
34              final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
35              formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
36              return formatter;
37          }
38      };
39  
40      /**
41       * {@inheritDoc}
42       */
43      @Override
44      public Date unmarshal(String object) {
45  
46          if (object.length() != 29) {
47              throw new IllegalArgumentException("Invalid date: " + object);
48          }
49          final String result = object.substring(0, 26) + object.substring(27);
50  
51          try {
52              return DATE_FORMAT.get().parse(result);
53          } catch (ParseException ex) {
54              throw new IllegalArgumentException("Invalid date: " + object);
55          }
56      }
57  
58      /**
59       * {@inheritDoc}
60       */
61      @Override
62      public String marshal(Date object) {
63  
64          String output = DATE_FORMAT.get().format(object);
65          return output.substring(0, 26) + ":" + output.substring(26);
66      }
67  
68      /**
69       * {@inheritDoc}
70       */
71      /* @Override */
72  	public Class<Date> getBoundClass() {
73  		return Date.class;
74  	}
75  }