package com.fasterxml.jackson.datatype.joda.deser;
import java.io.IOException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.ReadableDateTime;
import org.joda.time.ReadableInstant;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.core.StreamReadCapability;
import com.fasterxml.jackson.core.io.NumberInput;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
public class DateTimeDeserializer
extends JodaDateDeserializerBase<ReadableInstant>
{
private static final long serialVersionUID = 1L;
public DateTimeDeserializer(Class<?> cls, JacksonJodaDateFormat format) {
super(cls, format);
}
@SuppressWarnings("unchecked")
public static <T extends ReadableInstant> JsonDeserializer<T> forType(Class<T> cls)
{
return (JsonDeserializer<T>) new DateTimeDeserializer(cls,
FormatConfig.DEFAULT_DATETIME_PARSER);
}
@Override
public JodaDateDeserializerBase<?> withFormat(JacksonJodaDateFormat format) {
return new DateTimeDeserializer(_valueClass, format);
}
@Override
public ReadableInstant deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException
{
switch (p.currentTokenId()) {
case JsonTokenId.ID_NUMBER_INT:
return _fromTimestamp(ctxt, p.getLongValue());
case JsonTokenId.ID_STRING:
return _fromString(p, ctxt, p.getText());
case JsonTokenId.ID_START_OBJECT:
return _fromString(p, ctxt,
ctxt.extractScalarFromObject(p, this, handledType()));
}
return _handleNotNumberOrString(p, ctxt);
}
protected ReadableInstant _fromString(final JsonParser p, final DeserializationContext ctxt,
String value)
throws IOException
{
value = value.trim();
if (value.isEmpty()) {
return _fromEmptyString(p, ctxt, value);
}
int ix = value.indexOf('[');
if (ix > 0) {
DateTimeZone tz;
int ix2 = value.lastIndexOf(']');
String tzId = (ix2 < ix)
? value.substring(ix+1)
: value.substring(ix+1, ix2);
try {
tz = DateTimeZone.forID(tzId);
} catch (IllegalArgumentException e) {
ctxt.reportInputMismatch(handledType(), "Unknown DateTimeZone id '%s'", tzId);
tz = null;
}
value = value.substring(0, ix);
DateTime result = _format.createParser(ctxt)
.withZone(tz)
.parseDateTime(value)
;
if (_format.shouldAdjustToContextTimeZone(ctxt)) {
result = result.withZone(_format.getTimeZone());
}
return result;
}
if (ctxt.isEnabled(StreamReadCapability.UNTYPED_SCALARS)
&& _isValidTimestampString(value)) {
return _fromTimestamp(ctxt, NumberInput.parseLong(value));
}
return _format.createParser(ctxt).parseDateTime(value);
}
protected DateTime _fromTimestamp(DeserializationContext ctxt, long ts) {
DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone()
: DateTimeZone.forTimeZone(ctxt.getTimeZone());
return new DateTime(ts, tz);
}
}