001/*
002 *  Copyright 2010, 2011 Chris Pheby
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.jadira.bindings.core.jdk;
017
018import java.text.ParseException;
019import java.text.SimpleDateFormat;
020import java.util.Date;
021import java.util.TimeZone;
022
023import org.jadira.bindings.core.api.Binding;
024
025/**
026 * Binds a Date to a String. Date String binding always uses the GMT zone to render.... if you 
027 * want control over the zone, use CalendarStringBinding instead or better still use JodaTime or JSR310.
028 */
029public class DateStringBinding extends AbstractStringBinding<Date> implements Binding<Date, String> {
030
031    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
032        @Override
033        public SimpleDateFormat initialValue() {
034            final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
035            formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
036            return formatter;
037        }
038    };
039
040    /**
041     * {@inheritDoc}
042     */
043    @Override
044    public Date unmarshal(String object) {
045
046        if (object.length() != 29) {
047            throw new IllegalArgumentException("Invalid date: " + object);
048        }
049        final String result = object.substring(0, 26) + object.substring(27);
050
051        try {
052            return DATE_FORMAT.get().parse(result);
053        } catch (ParseException ex) {
054            throw new IllegalArgumentException("Invalid date: " + object);
055        }
056    }
057
058    /**
059     * {@inheritDoc}
060     */
061    @Override
062    public String marshal(Date object) {
063
064        String output = DATE_FORMAT.get().format(object);
065        return output.substring(0, 26) + ":" + output.substring(26);
066    }
067
068    /**
069     * {@inheritDoc}
070     */
071    /* @Override */
072        public Class<Date> getBoundClass() {
073                return Date.class;
074        }
075}