org.xlcloud.openstack.model.climate.json.OpenStackDateDeserializer.java Source code

Java tutorial

Introduction

Here is the source code for org.xlcloud.openstack.model.climate.json.OpenStackDateDeserializer.java

Source

/*
 * Copyright 2012 AMG.lab, a Bull Group Company
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xlcloud.openstack.model.climate.json;

import java.io.IOException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.codehaus.jackson.map.JsonMappingException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class OpenStackDateDeserializer extends JsonDeserializer<Date> {

    private static final String[] DATE_PATTERNS = { "yyyy-MM-dd'T'HH:mm:ss.S", "yyyy-MM-dd HH:mm:ss.S" };

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        String input = jp.readValueAs(String.class);
        if (input == null) {
            return null;
        }

        try {
            return parseDate(input, DATE_PATTERNS); // We cannot use DateUtils.parseDate(), because it uses local timezone, instead of UTC.
        } catch (ParseException e) {
            throw new JsonMappingException("Could not parse date: " + input, e);
        }
    }

    private Date parseDate(String input, String[] datePatterns) throws ParseException {
        SimpleDateFormat parser = new SimpleDateFormat();
        parser.setLenient(true);
        parser.setTimeZone(DateUtils.UTC_TIME_ZONE);
        ParsePosition position = new ParsePosition(0);
        for (String datePattern : datePatterns) {
            parser.applyPattern(datePattern);
            Date date = parser.parse(input, position);
            if (date != null && position.getIndex() == input.length()) {
                return date;
            }
        }
        throw new ParseException("Unable to parse the date: " + input, -1);
    }
}