pax_global_header00006660000000000000000000000064132320131620014503gustar00rootroot0000000000000052 comment=f76b47ad76164f7bba97f995723551cc06831b14 jackson-datatype-joda-jackson-datatype-joda-2.9.4/000077500000000000000000000000001323201316200220455ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/.gitattributes000066400000000000000000000001371323201316200247410ustar00rootroot00000000000000# Do not merge `pom.xml` from older version, as it will typically conflict pom.xml merge=ours jackson-datatype-joda-jackson-datatype-joda-2.9.4/.gitignore000066400000000000000000000002431323201316200240340ustar00rootroot00000000000000# use glob syntax. syntax: glob *.class *~ *.bak *.off *.old .DS_Store # building target # Eclipse .classpath .project .settings # IDEA *.iml *.ipr *.iws .idea jackson-datatype-joda-jackson-datatype-joda-2.9.4/.travis.yml000066400000000000000000000001731323201316200241570ustar00rootroot00000000000000language: java jdk: - openjdk7 - openjdk8 # no need to build all branches branches: only: - master - "2.8" jackson-datatype-joda-jackson-datatype-joda-2.9.4/README.md000066400000000000000000000050711323201316200233270ustar00rootroot00000000000000[Jackson](http://jackson.codehaus.org) module (jar) to support JSON serialization and deserialization of [Joda](http://joda-time.sourceforge.net/) data types. ## Status [![Build Status](https://travis-ci.org/FasterXML/jackson-datatype-joda.svg)](https://travis-ci.org/FasterXML/jackson-datatype-joda) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.fasterxml.jackson.datatype/jackson-datatype-joda/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.fasterxml.jackson.datatype/jackson-datatype-joda/) [![Javadoc](https://javadoc.io/badge/com.fasterxml.jackson.datatype/jackson-datatype-joda.svg)](http://www.javadoc.io/doc/com.fasterxml.jackson.datatype/jackson-datatype-joda) Module has been production-ready since version 2.0, and offers relatively extensive support for Joda datatypes. Contributions are always welcome -- not all types are yet supported; and we may want to support even wider alternative formats on input side. ## License [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) ## Usage Since this module extends basic [Jackson databind](../../../jackson-databind) functionality, you may want to check out documentation at [Jackson-docs](../../../jackson-docs) first. ### Maven dependency To use module on Maven-based projects, use following dependency: ```xml com.fasterxml.jackson.datatype jackson-datatype-joda 2.9.0 ``` (or whatever version is most up-to-date at the moment) ### Registering module To use Joda datatypes with Jackson, you will first need to register the module first (same as with all Jackson datatype modules): ```java ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); ``` ### Reading and Writing Joda types After registering Joda module, [Jackson Databind](../../../jackson-databind) will be able to write values of supported Joda types as JSON (and other formats Jackson supports), and read Joda values from same formats. With JSON, for example, following would work ```java public class Bean { public DateTime start; } final String INPUT_JSON = "{\"start\" : \"1972-12-28T12:00:01.000Z\"}"; Bean bean = mapper.readValue(INPUT_JSON, Bean.class); ``` and property `start` of Bean would have expected `DateTime` value. Conversely, you can produce JSON (and other supported formats) simply with: ```java String json = mapper.writeValueAsString(bean); Assert.assertEquals(INPUT_JSON, json); ``` ## More See [Wiki](../../wiki) for more information (javadocs, downloads). jackson-datatype-joda-jackson-datatype-joda-2.9.4/pom.xml000066400000000000000000000061001323201316200233570ustar00rootroot00000000000000 4.0.0 com.fasterxml.jackson jackson-base 2.9.4 com.fasterxml.jackson.datatype jackson-datatype-joda Jackson-datatype-Joda 2.9.4 bundle Add-on module for Jackson (http://jackson.codehaus.org) to support Joda (http://joda-time.sourceforge.net/) data types. http://wiki.fasterxml.com/JacksonModuleJoda scm:git:git@github.com:FasterXML/jackson-datatype-joda.git scm:git:git@github.com:FasterXML/jackson-datatype-joda.git http://github.com/FasterXML/jackson-datatype-joda jackson-datatype-joda-2.9.4 com/fasterxml/jackson/datatype/joda ${project.groupId}.joda ${project.groupId}.joda.* ${range;[===,+);${@}} com.fasterxml.jackson.core jackson-annotations com.fasterxml.jackson.core jackson-core com.fasterxml.jackson.core jackson-databind joda-time joda-time 2.7 junit junit test com.google.code.maven-replacer-plugin replacer process-packageVersion generate-sources jackson-datatype-joda-jackson-datatype-joda-2.9.4/release-notes/000077500000000000000000000000001323201316200246135ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/release-notes/CREDITS000066400000000000000000000043411323201316200256350ustar00rootroot00000000000000Here are people who have contributed to the development of Jackson JSON processor Joda datatype module. (version numbers in brackets indicate release in which the problem was fixed) Tatu Saloranta, tatu.saloranta@iki.fi: author ncjones@github.com: * Contributed #19: Add support for `MonthDay` and `YearMonth` (2.3.1) Łukasz D: * Suggested #23: package as a bundle (2.3.1) Lorcan C * Contributed #25: Add `KeyDeserializer` for `DateTime` (2.3.1) Hendy Irawan (ceefour@github) * Contributed #27: Allow support for `DateTimeZone` (2.3.1) Brad Kennedy (bkenned4@github) * Contributed #45: Can't use LocalTime, LocalDate & LocalDateTime as Key type for a Map (2.4.3) Charlie La Mothe (clamothe@github) * Contributed #51: Calling `JodaDateSerializerBase.isEmpty()` results in a `StackOverflowError`. (2.5.1) Thorsten Platz (ThorstenPlatz@github) * Reported #60: Configured date/time format not considered when serializing Joda Instant (2.5.4) Michał Ziober (ZioberMichal@github) * Contributed #62: Allow use of numbers-as-Strings for LocalDate (in array) (2.6.0) Jerry Yang (islanerman@github) * Contributed #68: TimeZone in DeserializationContext is ignored with `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` (2.6.0) jamesmcmillan@github * Reported #70: Default DateTime parser format is stricter than previous versions, causing incompatibility Luke Nezda (nezda@github) * Contributed #71: Adjust LocalDate / LocalDateTime deserializer to support `DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE` (2.6.2) Fabian Buch (fabianbuch@github) * Contributed #73: `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` writes inconsistent Zone Offset (2.6.3) Chris Plummer (strmer15@github) * Reported #82: Can't deserialize a serialized DateTimeZone with default typing (2.6.6 / 2.7.3) Jochen Schalanda (joschi@github) * Contributed #81: Add key deserializers for `Duration` and `Period` classes (2.7.2) Alexey Bychkov (joxerTMD@github) * Contributed #87: Add support for JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE (2.8.0) Daniel Qian (chanjarster@github) * Reported, contributed fix for #93: ADJUST_DATES_TO_CONTEXT_TIME_ZONE got wrong result when parse string contains zone id (2.9.0) jackson-datatype-joda-jackson-datatype-joda-2.9.4/release-notes/VERSION000066400000000000000000000131311323201316200256620ustar00rootroot00000000000000Project: jackson-datatype-joda ------------------------------------------------------------------------ === Releases === ------------------------------------------------------------------------ 2.9.4 (24-Jan-2018) 2.9.3 (09-Dec-2017) 2.9.2 (14-Oct-2017) 2.9.1 (07-Sep-2017) No changes since 2.9.0 2.9.0 (30-Jul-2017) #90: `DurationDeserializer` does not accept valid ISO8601 duration values (requested by bpelakh@github) #93: ADJUST_DATES_TO_CONTEXT_TIME_ZONE got wrong result when parse string contains zone id (contributed by Daniel Q) 2.8.9 (12-Jun-2017) 2.8.8 (05-Apr-2017) 2.8.7 (21-Feb-2017) 2.8.6 (12-Jan-2017) 2.8.5 (14-Nov-2016) 2.8.4 (14-Oct-2016) 2.8.3 (17-Sep-2016) 2.8.2 (30-Aug-2016) 2.8.1 (20-Jul-2016) No changes since 2.8.0. 2.8.0 (04-Jul-2016) #83: WRITE_DATES_WITH_ZONE_ID feature not working when applied on @JsonFormat annotation (reported by mandyWW@github) #87: Add support for JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE (contributed by Alexey B) - Support "config overrides" for `@JsonFormat.Value` added in databind - Upgrade joda-time dependency to 2.7 2.7.8 (26-Sep-2016) 2.7.7 (27-Aug-2016) 2.7.6 (23-Jul-2016) 2.7.5 (11-Jun-2016) 2.7.4 (29-Apr-2016) 2.7.3 (16-Mar-2016) No changes since 2.7.2 2.7.2 (27-Feb-2016) #81: Add key deserializers for `Duration` and `Period` classes (contributed by Jochen S) - Change build to produce JDK6-compatible jar, to allow use on JDK6 runtime 2.7.1 (02-Feb-2016) 2.7.0 (10-Jan-2016) No changes since 2.6. 2.6.6 (05-Apr-2016) #82: Can't deserialize a serialized DateTimeZone with default typing (reported by Chris P) 2.6.5 (19-Jan-2016) 2.6.4 (07-Dec-2015) 2.6.3 (12-Oct-2015) No changes since 2.6.2. 2.6.2 (15-Sep-2015) #71: Adjust LocalDate / LocalDateTime deserializer to support `DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE` (contributed by Luke N) #73: `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` writes inconsistent Zone Offset (contributed by Fabian B) 2.6.1 (09-Aug-2015) - Removed `final` from serializer implementations, to allow sub-class overriding 2.6.0-1 (29-Jul-2015) (micro-patch) #70: Default DateTime parser format is stricter than previous versions, causing incompatibility (reported by jamesmcmillan@github) 2.6.0 (19-Jul-2015) #49: testDateMidnightSerWithTypeInfo test dependent on $TZ (contributed by Michal Z) #58: Support timezone configuration for Interval deserializer #62: Allow use of numbers-as-Strings for LocalDate (in array) (contributed by Michal Z) #64: Support `@JsonFormat(pattern=...)` for deserialization #66: Support `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` #68: TimeZone in DeserializationContext is ignored with `SerializationFeature.WRITE_DATES_WITH_ZONE_ID` (contributed by Jerry Y, islanderman@github) 2.5.4 (09-Jun-2015) #60: Configured date/time format not considered when serializing Joda Instant (reported by Thorsten P) 2.5.3 (24-Apr-2015) 2.5.2 (29-Mar-2015) No changes since 2.5.1 2.5.1 (06-Feb-2015) #51: Calling `JodaDateSerializerBase.isEmpty()` results in a `StackOverflowError`. (reported, fix contributed by Charlie L-M) 2.5.0 (01-Jan-2015) 2.4.6 (23-Apr-2015) 2.4.5 (14-Jan-2015) 2.4.4 (24-Nov-2014) No changes since 2.4.3 2.4.3 (04-Oct-2014) #45: Can't use LocalTime, LocalDate & LocalDateTime as Key type for a Map (contributed by Brad K, reported by Guido M) #46: Interval deserialization fails for negative start instants (reported by Dan G, dgrabows@github) 2.4.2 (15-Aug-2014) No changes since 2.4.0 2.4.1 (17-Jun-2014) No changes since 2.4.0 2.4.0 (03-Jun-2014) #40: Add support for `ReadablePeriod` (contributed by 'wimdeblauwe@github') - Joda dependency now to 2.2 2.3.3 (14-Apr-2014) #32: Support use of `@JsonFormat(shape=...)` for timestamp/string choice 2.3.2 (01-Mar-2014) #16: Adjust existing Date/Time deserializers to support `DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE` (contributed by lukelukeluke@github) 2.3.1 (28-Dec-2013) #19: Add serializers and deserializers for MonthDay and YearMonth (contributed by ncjones@github) #21: Make `DateTimeSerializer` use configured timezone (contributed by pavax@github) #23: Package as a bundle (was accidentally not, just bare jar) (suggested by Łukasz D) #24: Allow serializing `Duration` using ISO-8601 notation (requested by cowwoc@github) #25: Add `KeyDeserializer` for `DateTime` (contributed by Lorcan C) #26: Implement `equals()` and `hashCode()` for JodaModule (suggested by Henning S) #27: Add support for `DateTimeZone` (requested by Hendy Irawan) 2.3.0 (14-Nov-2013) #18: Add `JodaMapper`, sub-class of basic `ObjectMapper` that auto-registers Joda module 2.2.3 (25-Aug-2013) 2.2.2 (27-May-2013) 2.2.1 (04-May-2013) No functional changes. 2.2.0 (23-Apr-2013) #8: Make DateTimeDeserializer abide by configured TimeZone - Upgraded version detection not to use VERSION.txt file 2.1.2 (08-Dec-2012) 2.1.1 (13-Nov-2012) No functional changes. 2.1.0 (08-Oct-2012) New minor version, based on Jackson core 2.1. Improvements: - [Issue#9]: Add support for (de)serialiazing Interval (submitted by jkolobok@github) 2.0.4 (26-Jun-2012) Improvements: - [Issue-6] Add support for handling Local date types (submitted by Chris Stivers) - Add support for Joda Instant data type 2.0.3 (15-Jun-2012) Fixes: - [Issue-3] Add support for Duration serialization, deserialization (reported by Marshall Pierce) 2.0.2 (18-May-2012) No fixes, just syncing up with core releases. 2.0.1 (29-Mar-2012) Fixes: * Issue-1: Deserializers registered so they would handle Object type, messing up 'untyped' Lists, Maps (reported by Pierre-Alexander M) 2.0.0 (25-Mar-2012) The first official release jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/000077500000000000000000000000001323201316200226345ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/000077500000000000000000000000001323201316200235605ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/000077500000000000000000000000001323201316200245015ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/000077500000000000000000000000001323201316200252575ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/000077500000000000000000000000001323201316200272645ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/000077500000000000000000000000001323201316200307145ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/000077500000000000000000000000001323201316200325275ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/000077500000000000000000000000001323201316200334445ustar00rootroot00000000000000JodaMapper.java000066400000000000000000000016721323201316200362600ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JodaMapper extends ObjectMapper { private static final long serialVersionUID = 1L; public JodaMapper() { registerModule(new JodaModule()); } /** * Convenience method that is shortcut for: *
     *  module.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
     *
     */
    public boolean getWriteDatesAsTimestamps() {
        return getSerializationConfig().isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    /**
     * Convenience method that is shortcut for:
     *
     *  configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, state)
     *
     */
    public void setWriteDatesAsTimestamps(boolean state) {
        configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, state);
    }
}
JodaModule.java000066400000000000000000000073461323201316200362650ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.joda.deser.*;
import com.fasterxml.jackson.datatype.joda.deser.key.*;
import com.fasterxml.jackson.datatype.joda.ser.*;

import org.joda.time.*;

public class JodaModule extends SimpleModule
{
    private static final long serialVersionUID = 1L;

    @SuppressWarnings({ "unchecked", "deprecation" })
    public JodaModule()
    {
        super(PackageVersion.VERSION);
        // first deserializers
        addDeserializer(DateTime.class, DateTimeDeserializer.forType(DateTime.class));
        addDeserializer(DateTimeZone.class, new DateTimeZoneDeserializer());

        addDeserializer(Duration.class, new DurationDeserializer());
        addDeserializer(Instant.class, new InstantDeserializer());
        addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        addDeserializer(LocalDate.class, new LocalDateDeserializer());
        addDeserializer(LocalTime.class, new LocalTimeDeserializer());
        JsonDeserializer deser = new PeriodDeserializer(true);
        addDeserializer(Period.class, (JsonDeserializer) deser);
        addDeserializer(ReadablePeriod.class, new PeriodDeserializer(false));
        addDeserializer(ReadableDateTime.class, DateTimeDeserializer.forType(ReadableDateTime.class));
        addDeserializer(ReadableInstant.class, DateTimeDeserializer.forType(ReadableInstant.class));
        addDeserializer(Interval.class, new IntervalDeserializer());
        addDeserializer(MonthDay.class, new MonthDayDeserializer());
        addDeserializer(YearMonth.class, new YearMonthDeserializer());

        // then serializers:
        final JsonSerializer stringSer = ToStringSerializer.instance;
        addSerializer(DateTime.class, new DateTimeSerializer());
        addSerializer(DateTimeZone.class, new DateTimeZoneSerializer());
        addSerializer(Duration.class, new DurationSerializer());
        addSerializer(Instant.class, new InstantSerializer());
        addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        addSerializer(LocalDate.class, new LocalDateSerializer());
        addSerializer(LocalTime.class, new LocalTimeSerializer());
        addSerializer(Period.class, new PeriodSerializer());
        addSerializer(Interval.class, new IntervalSerializer());
        addSerializer(MonthDay.class, stringSer);
        addSerializer(YearMonth.class, stringSer);

        // then key deserializers
        addKeyDeserializer(DateTime.class, new DateTimeKeyDeserializer());
        addKeyDeserializer(LocalTime.class, new LocalTimeKeyDeserializer());
        addKeyDeserializer(LocalDate.class, new LocalDateKeyDeserializer());
        addKeyDeserializer(LocalDateTime.class, new LocalDateTimeKeyDeserializer());
        addKeyDeserializer(Duration.class, new DurationKeyDeserializer());
        addKeyDeserializer(Period.class, new PeriodKeyDeserializer());

        // 26-Dec-2015, tatu: Joda has deprecated following types:
        
        // DateMidnight since at least Joda 2.4:
        addDeserializer(DateMidnight.class, new DateMidnightDeserializer());
        addSerializer(DateMidnight.class, new DateMidnightSerializer());
    }

    // yes, will try to avoid duplicate registrations (if MapperFeature enabled)
    @Override
    public String getModuleName() {
        return getClass().getSimpleName();
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }

    @Override
    public boolean equals(Object o) {
        return this == o;
    }
}
PackageVersion.java.in000066400000000000000000000011071323201316200375350ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/jodapackage @package@;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.core.Versioned;
import com.fasterxml.jackson.core.util.VersionUtil;

/**
 * Automatically generated from PackageVersion.java.in during
 * packageVersion-generate execution of maven-replacer-plugin in
 * pom.xml.
 */
public final class PackageVersion implements Versioned {
    public final static Version VERSION = VersionUtil.parseVersion(
        "@projectversion@", "@projectgroupid@", "@projectartifactid@");

    @Override
    public Version version() {
        return VERSION;
    }
}
cfg/000077500000000000000000000000001323201316200341245ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/jodaFormatConfig.java000066400000000000000000000060311323201316200373450ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/cfgpackage com.fasterxml.jackson.datatype.joda.cfg;

import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.joda.time.format.ISOPeriodFormat;

/**
 * Simple container class that holds both default formatter information
 * and explicit overrides caller has set for the Joda module to register.
 * Note that changes to configuration instance MUST be made before
 * registering the module; changes after registration may not have effect
 * on actual settings used.
 *
 * @since 2.5
 */
public class FormatConfig
{
    private final static DateTimeZone DEFAULT_TZ = DateTimeZone.getDefault();

    // Matching wrappers for more information needed with formatter
    
    public final static JacksonJodaDateFormat DEFAULT_DATEONLY_FORMAT
        = createUTC(ISODateTimeFormat.date());

    public final static JacksonJodaDateFormat DEFAULT_TIMEONLY_FORMAT
        = createUTC(ISODateTimeFormat.time());

    /* 28-Jul-2015, tatu: As per [datatype-joda#70], there is difference between
     *    "dateTime()" and "dateTimeParser()"... so we need to differentiate between
     *    parser/generator it seems.
     */
    public final static JacksonJodaDateFormat DEFAULT_DATETIME_PARSER
        = createUTC(ISODateTimeFormat.dateTimeParser());

    public final static JacksonJodaDateFormat DEFAULT_DATETIME_PRINTER
        = createUTC(ISODateTimeFormat.dateTime());

    /**
     * @deprecated Since 2.6.1
     */
    @Deprecated
    public final static JacksonJodaDateFormat DEFAULT_DATETIME_FORMAT = DEFAULT_DATETIME_PRINTER;
    
    // should these differ from ones above? Presumably should use local timezone or... ?

    public final static JacksonJodaDateFormat DEFAULT_LOCAL_DATEONLY_FORMAT
        = createDefaultTZ(ISODateTimeFormat.date());

    public final static JacksonJodaDateFormat DEFAULT_LOCAL_TIMEONLY_PRINTER
        = createDefaultTZ(ISODateTimeFormat.time());

    public final static JacksonJodaDateFormat DEFAULT_LOCAL_TIMEONLY_PARSER
        = createDefaultTZ(ISODateTimeFormat.localTimeParser());
    
    public final static JacksonJodaDateFormat DEFAULT_LOCAL_DATETIME_PRINTER
        = createDefaultTZ(ISODateTimeFormat.dateTime());

    public final static JacksonJodaDateFormat DEFAULT_LOCAL_DATETIME_PARSER
        = createDefaultTZ(ISODateTimeFormat.localDateOptionalTimeParser());

    public final static JacksonJodaPeriodFormat DEFAULT_PERIOD_FORMAT
        = new JacksonJodaPeriodFormat(ISOPeriodFormat.standard());

    // // // And then some wrapper methods for improved diagnostics, and possible
    // // // default settings for things like "withOffsetParsed()" (see
    // // // [dataformat-joda#75] for more information)
    
    private final static JacksonJodaDateFormat createUTC(DateTimeFormatter f)
    {
        f = f.withZoneUTC();
        return new JacksonJodaDateFormat(f);
    }

    private final static JacksonJodaDateFormat createDefaultTZ(DateTimeFormatter f)
    {
        f = f.withZone(DEFAULT_TZ);
        return new JacksonJodaDateFormat(f);
    }
}
JacksonJodaDateFormat.java000066400000000000000000000242571323201316200411360ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/cfgpackage com.fasterxml.jackson.datatype.joda.cfg;

import java.util.Locale;
import java.util.TimeZone;

import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * Simple container used to encapsulate (some of) gory details of
 * customizations related to date/time formatting.
 */
public class JacksonJodaDateFormat extends JacksonJodaFormatBase
{
    private final static String JODA_STYLE_CHARS = "SMLF-";

    protected final DateTimeFormatter _formatter;

    protected final TimeZone _jdkTimezone;

    protected transient DateTimeZone _jodaTimezone;
    
    protected final boolean _explicitTimezone;

    /**
     * Flag for JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE
     *
     * @since 2.8
     */
    protected final Boolean _adjustToContextTZOverride;

    /**
     * Flag for JsonFormat.Feature.WRITE_DATES_WITH_ZONE_ID
     *
     * @since 2.8
     */
    protected final Boolean _writeZoneId;
    
    public JacksonJodaDateFormat(DateTimeFormatter defaultFormatter)
    {
        super();
        _formatter = defaultFormatter;
        DateTimeZone tz = defaultFormatter.getZone();
        _jdkTimezone = (tz == null) ? null : tz.toTimeZone();
        _explicitTimezone = false;
        _adjustToContextTZOverride = null;
        _writeZoneId = null;
    }

    public JacksonJodaDateFormat(JacksonJodaDateFormat base,
            Boolean useTimestamp)
    {
        super(base, useTimestamp);
        _formatter = base._formatter;
        _jdkTimezone = base._jdkTimezone;
        _explicitTimezone = base._explicitTimezone;
        _adjustToContextTZOverride = base._adjustToContextTZOverride;
        _writeZoneId = base._writeZoneId;
    }

    public JacksonJodaDateFormat(JacksonJodaDateFormat base,
            DateTimeFormatter formatter)
    {
        super(base);
        _formatter = formatter;
        _jdkTimezone = base._jdkTimezone;
        _explicitTimezone = base._explicitTimezone;
        _adjustToContextTZOverride = base._adjustToContextTZOverride;
        _writeZoneId = base._writeZoneId;
    }

    public JacksonJodaDateFormat(JacksonJodaDateFormat base, TimeZone jdkTimezone)
    {
        super(base, jdkTimezone);
        _formatter = base._formatter.withZone(DateTimeZone.forTimeZone(jdkTimezone));
        _jdkTimezone = jdkTimezone;
        _explicitTimezone = true;
        _adjustToContextTZOverride = base._adjustToContextTZOverride;
        _writeZoneId = base._writeZoneId;
    }

    public JacksonJodaDateFormat(JacksonJodaDateFormat base, Locale locale)
    {
        super(base, locale);
        _formatter = base._formatter.withLocale(locale);
        _jdkTimezone = base._jdkTimezone;
        _explicitTimezone = base._explicitTimezone;
        _adjustToContextTZOverride = base._adjustToContextTZOverride;
        _writeZoneId = base._writeZoneId;
    }

    /**
     * @since 2.8
     */
    protected JacksonJodaDateFormat(JacksonJodaDateFormat base,
            Boolean adjustToContextTZOverride, Boolean writeZoneId)
    {
        super(base);
        _formatter = base._formatter;
        _jdkTimezone = base._jdkTimezone;
        _explicitTimezone = base._explicitTimezone;
        _adjustToContextTZOverride = adjustToContextTZOverride;
        _writeZoneId = writeZoneId;
    }

    /*
    /**********************************************************
    /* Factory methods
    /**********************************************************
     */

    public JacksonJodaDateFormat with(JsonFormat.Value ann) {
        JacksonJodaDateFormat format = this;
        format = format.withLocale(ann.getLocale());
        format = format.withTimeZone(ann.getTimeZone());
        format = format.withFormat(ann.getPattern().trim());
        Boolean adjustTZ = ann.getFeature(JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        Boolean writeZoneId = ann.getFeature(JsonFormat.Feature.WRITE_DATES_WITH_ZONE_ID);
        if ((adjustTZ != _adjustToContextTZOverride)
                || (writeZoneId != _writeZoneId)) {
            format = new JacksonJodaDateFormat(format, adjustTZ, writeZoneId);
        }
        return format;
    }

    public JacksonJodaDateFormat withUseTimestamp(Boolean useTimestamp) {
        if ((_useTimestamp != null) && _useTimestamp.equals(useTimestamp)) {
            return this;
        }
        return new JacksonJodaDateFormat(this, useTimestamp);
    }
    
    public JacksonJodaDateFormat withFormat(String format) {
        if (format == null || format.isEmpty()) {
            return this;
        }
        DateTimeFormatter formatter;

        if (_isStyle(format)) {
            formatter = DateTimeFormat.forStyle(format);
        } else {
            formatter = DateTimeFormat.forPattern(format);
        }
        if (_locale != null) {
            formatter = formatter.withLocale(_locale);
        }
        return new JacksonJodaDateFormat(this, formatter);
    }

    public JacksonJodaDateFormat withTimeZone(TimeZone tz) {
        if ((tz == null) || (_jdkTimezone != null && _jdkTimezone.equals(tz))) {
            return this;
        }
        return new JacksonJodaDateFormat(this, tz);
    }

    public JacksonJodaDateFormat withLocale(Locale locale) {
        if ((locale == null) || (_locale != null && _locale.equals(locale))) {
            return this;
        }
        return new JacksonJodaDateFormat(this, locale);
    }

    /**
     * @since 2.8
     */
    public JacksonJodaDateFormat withAdjustToContextTZOverride(Boolean adjustToContextTZOverride) {
        // minor efficiency check to avoid recreation if no change:
        if (adjustToContextTZOverride == _adjustToContextTZOverride) {
            return this;
        }
        return new JacksonJodaDateFormat(this, adjustToContextTZOverride, _writeZoneId);
    }

    /**
     * @since 2.8
     */
    public JacksonJodaDateFormat withWriteZoneId(Boolean writeZoneId) {
        // minor efficiency check to avoid recreation if no change:
        if (writeZoneId == _writeZoneId) {
            return this;
        }
        return new JacksonJodaDateFormat(this, _adjustToContextTZOverride, writeZoneId);
    }

    /*
    /**********************************************************
    /* Accessors
    /**********************************************************
     */

    /**
     * @since 2.6
     */
    public DateTimeZone getTimeZone() {
        if (_jodaTimezone != null) {
            return _jodaTimezone;
        }
        if (_jdkTimezone == null) {
            return null;
        }
        DateTimeZone tz = DateTimeZone.forTimeZone(_jdkTimezone);
        _jodaTimezone = tz;
        return tz;
    }

    public Locale getLocale() {
        return _locale;
    }

    /*
    /**********************************************************
    /* Factory methods for other types
    /**********************************************************
     */

    public DateTimeFormatter rawFormatter() {
        return _formatter;
    }

    public DateTimeFormatter createFormatter(SerializerProvider ctxt)
    {
        DateTimeFormatter formatter = createFormatterWithLocale(ctxt);
        if (!_explicitTimezone) {
            TimeZone tz = ctxt.getTimeZone();
            if ((tz != null) && !tz.equals(_jdkTimezone)) {
                formatter = formatter.withZone(DateTimeZone.forTimeZone(tz));
            }
        }
        return formatter;
    }

    public DateTimeFormatter createFormatterWithLocale(SerializerProvider ctxt)
    {
        DateTimeFormatter formatter = _formatter;
        if (!_explicitLocale) {
            Locale loc = ctxt.getLocale();
            if (loc != null && !loc.equals(_locale)) {
                formatter = formatter.withLocale(loc);
            }
        }
        return formatter;
    }

    /**
     * Accessor used during deserialization.
     */
    public DateTimeFormatter createParser(DeserializationContext ctxt)
    {
        DateTimeFormatter formatter = _formatter;
        if (!_explicitLocale) {
            Locale loc = ctxt.getLocale();
            if (loc != null && !loc.equals(_locale)) {
                formatter = formatter.withLocale(loc);
            }
        }
        if (!_explicitTimezone) {
            if (shouldAdjustToContextTimeZone(ctxt)) {
                TimeZone tz = ctxt.getTimeZone();
                if (tz != null && !tz.equals(_jdkTimezone)) {
                    formatter = formatter.withZone(DateTimeZone.forTimeZone(tz));
                }
            } else {
                formatter = formatter.withOffsetParsed();
            }
        }
        return formatter;
    }

    /**
     * @since 2.8
     */
    public boolean shouldAdjustToContextTimeZone(DeserializationContext ctxt) {
        return (_adjustToContextTZOverride != null) ? _adjustToContextTZOverride :
            ctxt.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    }

    /**
     * @since 2.8
     */
    public boolean shouldWriteWithZoneId(SerializerProvider ctxt) {
        return (_writeZoneId != null) ? _writeZoneId :
            ctxt.isEnabled(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
    }

    /**
     * Differentiate if TimeZone is specified by caller 
     * @return true if TimeZone is specified by caller; false otherwise.
     */
    public boolean isTimezoneExplicit() {
        return _explicitTimezone;
    }
    
    /*
    /**********************************************************
    /* Helper methods
    /**********************************************************
     */
    
    protected static boolean _isStyle(String formatStr) {
        if (formatStr.length() != 2) {
            return false;
        }
        return (JODA_STYLE_CHARS.indexOf(formatStr.charAt(0)) >= 0)
                && (JODA_STYLE_CHARS.indexOf(formatStr.charAt(0)) >= 0);
    }

    @Override
    public String toString() {
        return String.format("[JacksonJodaFormat, explicitTZ? %s, JDK tz = %s, formatter = %s]",
                _explicitTimezone, _jdkTimezone.getID(), _formatter);
    }
}
JacksonJodaFormatBase.java000066400000000000000000000046461323201316200411330ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/cfgpackage com.fasterxml.jackson.datatype.joda.cfg;

import java.util.Locale;
import java.util.TimeZone;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * Base object for different formatters (date-time, period, ...)
 */
abstract class JacksonJodaFormatBase
{
    protected final static Locale DEFAULT_LOCALE;
    static {
        DEFAULT_LOCALE = Locale.getDefault();
    }

    /**
     * Flag that indicates that serialization must be done as the
     * Java timestamp, regardless of other settings.
     */
    protected final Boolean _useTimestamp;
    
    protected final Locale _locale;

    protected final boolean _explicitLocale;

    protected JacksonJodaFormatBase(Boolean useTimestamp,
            Locale locale, boolean explicitLocale) {
        _useTimestamp = useTimestamp;
        _locale = locale;
        _explicitLocale = explicitLocale;
    }

    protected JacksonJodaFormatBase() {
        _useTimestamp = null;
        _locale = DEFAULT_LOCALE;
        _explicitLocale = false;
    }

    protected JacksonJodaFormatBase(JacksonJodaFormatBase base)
    {
        _useTimestamp = base._useTimestamp;
        _locale = base._locale;
        _explicitLocale = base._explicitLocale;
    }

    protected JacksonJodaFormatBase(JacksonJodaFormatBase base, Boolean useTimestamp)
    {
        _useTimestamp = useTimestamp;
        _locale = base._locale;
        _explicitLocale = base._explicitLocale;
    }

    protected JacksonJodaFormatBase(JacksonJodaFormatBase base, TimeZone jdkTimezone)
    {
        _useTimestamp = base._useTimestamp;
        _locale = base._locale;
        _explicitLocale = base._explicitLocale;
    }

    protected JacksonJodaFormatBase(JacksonJodaFormatBase base, Locale locale)
    {
        _useTimestamp = base._useTimestamp;
        if (locale == null) {
            _locale = DEFAULT_LOCALE;
            _explicitLocale = false;
        } else {
            _locale = locale;
            _explicitLocale = true;
        }
    }

    /*
    /**********************************************************
    /* Other public methods
    /**********************************************************
     */

    public boolean useTimestamp(SerializerProvider provider, SerializationFeature feat)
    {
        if (_useTimestamp != null) {
            return _useTimestamp.booleanValue();
        }
        return provider.isEnabled(feat);
    }
}
JacksonJodaPeriodFormat.java000066400000000000000000000057721323201316200415040ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/cfgpackage com.fasterxml.jackson.datatype.joda.cfg;

import java.io.IOException;
import java.util.Locale;

import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * Simple container used to encapsulate (some of) gory details of
 * customizations related to date/time formatting.
 */
public class JacksonJodaPeriodFormat extends JacksonJodaFormatBase
{
    protected final PeriodFormatter _formatter;

    // Constructor called by FormatConfig for baseline defaults
    public JacksonJodaPeriodFormat(PeriodFormatter defaultFormatter) {
        super();
        _formatter = defaultFormatter;
    }

    public JacksonJodaPeriodFormat(JacksonJodaPeriodFormat base, Locale locale)
    {
        super(base, locale);
        PeriodFormatter f = base._formatter;
        if (locale != null) {
            f = f.withLocale(locale);
        }
        _formatter = f;
    }

    public JacksonJodaPeriodFormat(JacksonJodaPeriodFormat base, Boolean useTimestamp)
    {
        super(base, useTimestamp);
        _formatter = base._formatter;
    }

    /**
     * @since 2.9
     */
    public PeriodFormatter nativeFormatter() {
        return _formatter;
    }

    /*
    /**********************************************************
    /* Factory methods
    /**********************************************************
     */

    // 30-Jun-2015, tatu: not 100% it's needed, but support for now...
    public JacksonJodaPeriodFormat withUseTimestamp(Boolean useTimestamp) {
        if (_useTimestamp != null && _useTimestamp.equals(useTimestamp)) {
            return this;
        }
        return new JacksonJodaPeriodFormat(this, useTimestamp);
    }
    
    public JacksonJodaPeriodFormat withFormat(String format) {
        /* 17-Nov-2014, tatu: Does not look like there is all that much
         *   that can be customized... At most we might be able to
         *   use "alternate" variant?
         */
        return this;
    }

    public JacksonJodaPeriodFormat withLocale(Locale locale) {
        if ((locale == null) || (_locale != null && _locale.equals(locale))) {
            return this;
        }
        return new JacksonJodaPeriodFormat(this, locale);
    }

    /*
    /**********************************************************
    /* Factory methods for other types
    /**********************************************************
     */

    public PeriodFormatter createFormatter(SerializerProvider provider)
    {
        PeriodFormatter formatter = _formatter;
        
        if (!_explicitLocale) {
            Locale loc = provider.getLocale();
            if (loc != null && !loc.equals(_locale)) {
                formatter = formatter.withLocale(loc);
            }
        }
        return formatter;
    }


    /**
     * @since 2.9
     */
    public Period parsePeriod(DeserializationContext ctxt, String str) throws IOException
    {
        return _formatter.parsePeriod(str);
    }
}
deser/000077500000000000000000000000001323201316200344675ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/jodaDateMidnightDeserializer.java000066400000000000000000000053741323201316200422470ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.DateMidnight;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;

/**
 * Note: Joda has DateMidnight deprecated since at least 2.4,
 * but we still support it for now.
 *
 * @deprecated Since 2.7
 */
@Deprecated // since Jackson 2.7 (and Joda 2.4)
public class DateMidnightDeserializer
    extends JodaDateDeserializerBase
{
    private static final long serialVersionUID = 1L;

    // final static DateTimeFormatter parser =
    // ISODateTimeFormat.localDateParser();

    public DateMidnightDeserializer() {
        this(FormatConfig.DEFAULT_DATEONLY_FORMAT);
    }

    public DateMidnightDeserializer(JacksonJodaDateFormat format) {
        super(DateMidnight.class, format);
    }

    @Override
    public JodaDateDeserializerBase withFormat(JacksonJodaDateFormat format) {
        return new DateMidnightDeserializer(format);
    }

    @Override
    public DateMidnight deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
    {
    	
        // We'll accept either long (timestamp) or array:
        if (p.isExpectedStartArrayToken()) {
            p.nextToken(); // VALUE_NUMBER_INT
            int year = p.getIntValue();
            p.nextToken(); // VALUE_NUMBER_INT
            int month = p.getIntValue();
            p.nextToken(); // VALUE_NUMBER_INT
            int day = p.getIntValue();
            if (p.nextToken() != JsonToken.END_ARRAY) {
                throw ctxt.wrongTokenException(p, JsonToken.END_ARRAY,
                        "after DateMidnight ints");
            }
            DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(ctxt.getTimeZone());

            return new DateMidnight(year, month, day, tz);
        }
        switch (p.getCurrentToken()) {
        case VALUE_NUMBER_INT:
            return new DateMidnight(p.getLongValue());
        case VALUE_STRING:
            String str = p.getText().trim();
            if (str.length() == 0) { // [JACKSON-360]
                return null;
            }
            LocalDate local = _format.createParser(ctxt).parseLocalDate(str);
            if (local == null) {
                return null;
            }
            return local.toDateMidnight();
        default:
        }
        throw ctxt.wrongTokenException(p, JsonToken.START_ARRAY,
                "expected JSON Array, Number or String");
    }
}DateTimeDeserializer.java000066400000000000000000000100141323201316200413650ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage 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.JsonToken;
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;

/**
 * Basic deserializer for {@link ReadableDateTime} and its subtypes.
 * Accepts JSON String and Number values and passes those to single-argument constructor.
 * Does not (yet?) support JSON object; support can be added if desired.
 */
public class DateTimeDeserializer
    extends JodaDateDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public DateTimeDeserializer(Class cls, JacksonJodaDateFormat format) {
        super(cls, format);
    }

    @SuppressWarnings("unchecked")
    public static  JsonDeserializer forType(Class cls)
    {
        return (JsonDeserializer) 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
    {
        JsonToken t = p.getCurrentToken();
        
        if (t == JsonToken.VALUE_NUMBER_INT) {
            DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(ctxt.getTimeZone());
            return new DateTime(p.getLongValue(), tz);
        }
        if (t == JsonToken.VALUE_STRING) {
            String str = p.getText().trim();
            if (str.length() == 0) {
                return null;
            }
            // 08-Jul-2015, tatu: as per [datatype-joda#44], optional TimeZone inclusion
            // NOTE: on/off feature only for serialization; on deser should accept both
            int ix = str.indexOf('[');
            if (ix > 0) {
                int ix2 = str.lastIndexOf(']');
                String tzId = (ix2 < ix)
                        ? str.substring(ix+1)
                        : str.substring(ix+1, ix2);
                DateTimeZone tz;
                try {
                    tz = DateTimeZone.forID(tzId);
                } catch (IllegalArgumentException e) {
                    ctxt.reportInputMismatch(handledType(), "Unknown DateTimeZone id '%s'", tzId);
                    tz = null; // never gets here
                }
                str = str.substring(0, ix);

                // 12-Jul-2015, tatu: Initially planned to support "timestamp[zone-id]"
                //    format as well as textual, but since JSR-310 datatype (Java 8 datetime)
                //    does not support it, was left out of 2.6.

                /*
                // One more thing; do we have plain timestamp?
                if (_allDigits(str)) {
                    return new DateTime(Long.parseLong(str), tz);
                }
                */

                DateTime result = _format.createParser(ctxt)
                        .withZone(tz)
                        .parseDateTime(str)
                        ;
                // 23-Jul-2017, tatu: As per [datatype-joda#93] only override tz if allowed to
                if (_format.shouldAdjustToContextTimeZone(ctxt)) {
                    result = result.withZone(_format.getTimeZone());
                }
                return result;
            }
            // Not sure if it should use timezone or not...
            // 15-Sep-2015, tatu: impl of 'createParser()' SHOULD handle all timezone/locale setup
            return _format.createParser(ctxt).parseDateTime(str);
        }
        return _handleNotNumberOrString(p, ctxt);
    }
}
DateTimeZoneDeserializer.java000066400000000000000000000020271323201316200422260ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.DateTimeZone;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;

/**
 * Deserializer for Joda {@link DateTimeZone}.
 */
public class DateTimeZoneDeserializer extends JodaDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public DateTimeZoneDeserializer() { super(DateTimeZone.class); }

    @Override
    public DateTimeZone deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
    {
        JsonToken t = p.getCurrentToken();
        if (t == JsonToken.VALUE_NUMBER_INT) {
            // for fun let's allow use of offsets...
            return DateTimeZone.forOffsetHours(p.getIntValue());
        }
        if (t == JsonToken.VALUE_STRING) {
            return DateTimeZone.forID(p.getText().trim());
        }
        return _handleNotNumberOrString(p, ctxt);
    }
}
DurationDeserializer.java000066400000000000000000000044741323201316200414730ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.Duration;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaPeriodFormat;

/**
 * Deserializes a Duration from either an int number of millis or using the {@link Duration#Duration(Object)}
 * constructor on a JSON string. By default the only supported string format is that used by {@link
 * Duration#toString()}. (That format for a 3,248 millisecond duration is "PT3.248S".)
 */
public class DurationDeserializer
    extends JodaDeserializerBase
{
    private static final long serialVersionUID = 1L;

    protected final JacksonJodaPeriodFormat _format;
    
    public DurationDeserializer() {
        this(FormatConfig.DEFAULT_PERIOD_FORMAT);
    }

    public DurationDeserializer(JacksonJodaPeriodFormat format) {
        super(Duration.class);
        _format = format;
    }

    @Override
    public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
    {
        switch (p.getCurrentTokenId()) {
        case JsonTokenId.ID_NUMBER_INT: // assume it's millisecond count
            return new Duration(p.getLongValue());
        case JsonTokenId.ID_STRING:
            return _format.parsePeriod(ctxt, p.getText().trim()).toStandardDuration();
        default:
        }
        return _handleNotNumberOrString(p, ctxt);
    }

    protected Duration _deserialize(DeserializationContext ctxt, String str)
            throws IOException
    {
        if (str.length() == 0) {
            if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {
                return null;
            }
        }
        return Duration.parse(str);
    }
}
InstantDeserializer.java000066400000000000000000000022411323201316200413140ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.Instant;

import com.fasterxml.jackson.core.*;

import com.fasterxml.jackson.databind.*;

/**
 * Basic deserializer for {@link org.joda.time.ReadableDateTime} and its subtypes.
 * Accepts JSON String and Number values and passes those to single-argument constructor.
 * Does not (yet?) support JSON object; support can be added if desired.
 */
public class InstantDeserializer
    extends JodaDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public InstantDeserializer() {
        super(Instant.class);
    }

    @Override
    public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
    {
        JsonToken t = p.getCurrentToken();
        if (t == JsonToken.VALUE_NUMBER_INT) {
            return new Instant(p.getLongValue());
        }
        if (t == JsonToken.VALUE_STRING) {
            String str = p.getText().trim();
            if (str.length() == 0) {
                return null;
            }
            return new Instant(str);
        }
        return _handleNotNumberOrString(p, ctxt);
    }
}
IntervalDeserializer.java000066400000000000000000000054371323201316200414720ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.DateTimeZone;
import org.joda.time.Interval;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;

public class IntervalDeserializer extends JodaDateDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public IntervalDeserializer() {
        // NOTE: not currently used, but must pass something
        this(FormatConfig.DEFAULT_DATETIME_PARSER);
    }

    public IntervalDeserializer(JacksonJodaDateFormat format) {
        super(Interval.class, format);
    }

    @Override
    public JodaDateDeserializerBase withFormat(JacksonJodaDateFormat format) {
        return new IntervalDeserializer(format);
    }

    @Override
    public Interval deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
    {
        if (!p.hasToken(JsonToken.VALUE_STRING)) {
            return (Interval) ctxt.handleUnexpectedToken(handledType(),
                    p.getCurrentToken(), p, "expected JSON String");
        }

        String v = p.getText().trim();

        /* 17-Nov-2014, tatu: Actually let's start with slash, instead of hyphen, because
         *   that is the separator for standard functionality...
         */
        int index = v.indexOf('/', 1);
        boolean hasSlash = (index > 0);
        if (!hasSlash) {
            index = v.indexOf('-', 1);
        }
        if (index < 0) {
            throw ctxt.weirdStringException(v, handledType(), "no slash or hyphen found to separate start, end");
        }
        long start, end;
        String str = v.substring(0, index);
        Interval result;

        try {
            // !!! TODO: configurable formats...
            if (hasSlash) {
                result = Interval.parse(v);
            } else {
                start = Long.valueOf(str);
                str = v.substring(index + 1);
                end = Long.valueOf(str);
                result = new Interval(start, end);
            }
        } catch (NumberFormatException e) {
            return (Interval) ctxt.handleWeirdStringValue(handledType(), str,
"Failed to parse number from '%s' (full source String '%s')",
                    str, v);
        }

        DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(ctxt.getTimeZone());
        if (tz != null) {
            if (!tz.equals(result.getStart().getZone())) {
                result = new Interval(result.getStartMillis(), result.getEndMillis(), tz);
            }
        }
        return result;
    }
}
JodaDateDeserializerBase.java000066400000000000000000000043401323201316200421440ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;

/**
 * Intermediate base class used by deserializers that allow configuration
 * via JsonFormat annotation
 *
 * @since 2.6
 */
public abstract class JodaDateDeserializerBase
    extends JodaDeserializerBase
//need contextualization to read per-property annotations
    implements ContextualDeserializer
{
    private static final long serialVersionUID = 1L;

    protected final JacksonJodaDateFormat _format;

    protected JodaDateDeserializerBase(Class type, JacksonJodaDateFormat format)
    {
        super(type);
        _format = format;
    }

    public abstract JodaDateDeserializerBase withFormat(JacksonJodaDateFormat format);

    @Override
    public JsonDeserializer createContextual(DeserializationContext ctxt,
            BeanProperty prop) throws JsonMappingException
    {
        JsonFormat.Value ann = findFormatOverrides(ctxt, prop, handledType());
        if (ann != null) {
            JacksonJodaDateFormat format = _format;
            Boolean useTimestamp;

            // Simple case first: serialize as numeric timestamp?
            if (ann.getShape().isNumeric()) {
                useTimestamp = Boolean.TRUE;
            } else if (ann.getShape() == JsonFormat.Shape.STRING) {
                useTimestamp = Boolean.FALSE;
            } else if (ann.getShape() == JsonFormat.Shape.ARRAY) {
                // 17-Nov-2014, tatu: also, arrays typically contain non-string representation
                useTimestamp = Boolean.TRUE;
            } else  {
                useTimestamp = null;
            }
            // must not call if flag defined, to rely on defaults:
            if (useTimestamp != null) {
                format = format.withUseTimestamp(useTimestamp);
            }
            // for others, safe to call, null/empty just ignored
            format = format.with(ann);
            if (format != _format) {
                return withFormat(format);
            }
        }
        return this;
    }
}
JodaDeserializerBase.java000066400000000000000000000021471323201316200413510ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;

@SuppressWarnings("serial")
abstract class JodaDeserializerBase extends StdScalarDeserializer
{
    protected JodaDeserializerBase(Class cls) {
        super(cls);
    }

    protected JodaDeserializerBase(JodaDeserializerBase src) {
        super(src);
    }
    
    @Override
    public Object deserializeWithType(JsonParser p, DeserializationContext ctxt,
            TypeDeserializer typeDeserializer) throws IOException
    {
        return typeDeserializer.deserializeTypedFromAny(p, ctxt);
    }

    @SuppressWarnings("unchecked")
    public T _handleNotNumberOrString(JsonParser p, DeserializationContext ctxt)
        throws IOException
    {
        return (T) ctxt.handleUnexpectedToken(handledType(),
                p.getCurrentToken(), p, "expected JSON Number or String");
    }
}
LocalDateDeserializer.java000066400000000000000000000050421323201316200415260ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.JsonTokenId;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;

public class LocalDateDeserializer
    extends JodaDateDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public LocalDateDeserializer() {
        this(FormatConfig.DEFAULT_LOCAL_DATEONLY_FORMAT);
    }
    
    public LocalDateDeserializer(JacksonJodaDateFormat format) {
        super(LocalDate.class, format);
    }

    @Override
    public JodaDateDeserializerBase withFormat(JacksonJodaDateFormat format) {
        return new LocalDateDeserializer(format);
    }

    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
    {
        switch (p.getCurrentTokenId()) {
        case JsonTokenId.ID_STRING:
            String str = p.getText().trim();
            return (str.length() == 0) ? null
                    : _format.createParser(ctxt).parseLocalDate(str);
        case JsonTokenId.ID_NUMBER_INT:
            {
                DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(ctxt.getTimeZone());
                return new LocalDate(p.getLongValue(), tz);
            }
        case JsonTokenId.ID_START_ARRAY:
            // [yyyy,mm,dd] or ["yyyy","mm","dd"]
            int year = p.nextIntValue(-1); // fast speculative case
            if (year == -1) { // either -1, or not an integral number; slow path
                year = _parseIntPrimitive(p, ctxt);
            }
            int month = p.nextIntValue(-1);
            if (month == -1) {
                month = _parseIntPrimitive(p, ctxt);
            }
            int day = p.nextIntValue(-1);
            if (day == -1) {
                day = _parseIntPrimitive(p, ctxt);
            }
            if (p.nextToken() != JsonToken.END_ARRAY) {
                throw ctxt.wrongTokenException(p, handledType(), JsonToken.END_ARRAY, "after LocalDate ints");
            }
            return new LocalDate(year, month, day);
        }
        return (LocalDate) ctxt.handleUnexpectedToken(handledType(), p.getCurrentToken(), p,
                "expected String, Number or JSON Array");
    }
}
LocalDateTimeDeserializer.java000066400000000000000000000066621323201316200423560ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;

import com.fasterxml.jackson.core.*;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;

public class LocalDateTimeDeserializer
    extends JodaDateDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public LocalDateTimeDeserializer() {
        this(FormatConfig.DEFAULT_LOCAL_DATETIME_PARSER);
    }
    
    public LocalDateTimeDeserializer(JacksonJodaDateFormat format) {
        super(LocalDateTime.class, format);
    }

    @Override
    public JodaDateDeserializerBase withFormat(JacksonJodaDateFormat format) {
        return new LocalDateTimeDeserializer(format);
    }

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
    {
        switch (p.getCurrentTokenId()) {
        case JsonTokenId.ID_STRING:
            {
                String str = p.getText().trim();
                return (str.length() == 0) ? null
                        : _format.createParser(ctxt).parseLocalDateTime(str);
            }
        case JsonTokenId.ID_NUMBER_INT:
            {
                DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(ctxt.getTimeZone());
                return new LocalDateTime(p.getLongValue(), tz);
            }
        case JsonTokenId.ID_START_ARRAY:
            // [yyyy,mm,dd,hh,MM,ss,ms]
            JsonToken t = p.nextToken();
            LocalDateTime dt = null;
            do {
                if (!t.isNumeric()) { break; }
                int year = p.getIntValue();
                t = p.nextToken(); // VALUE_NUMBER_INT
                if (!t.isNumeric()) { break; }
                int month = p.getIntValue();
                t = p.nextToken(); // VALUE_NUMBER_INT
                if (!t.isNumeric()) { break; }
                int day = p.getIntValue();
                t = p.nextToken(); // VALUE_NUMBER_INT
                if (!t.isNumeric()) { break; }
                int hour = p.getIntValue();
                t = p.nextToken(); // VALUE_NUMBER_INT
                if (!t.isNumeric()) { break; }
                int minute = p.getIntValue();
                t = p.nextToken(); // VALUE_NUMBER_INT
                if (!t.isNumeric()) { break; }
                int second = p.getIntValue();
                t = p.nextToken(); // VALUE_NUMBER_INT | END_ARRAY
                // let's leave milliseconds optional?
                int millisecond = 0;
                if (t.isNumeric()) { // VALUE_NUMBER_INT           
                    millisecond = p.getIntValue();
                    t = p.nextToken(); // END_ARRAY?
                }
                dt = new LocalDateTime(year, month, day, hour, minute, second, millisecond);                 
            } while (false); // bogus loop to allow break from within
            if (t == JsonToken.END_ARRAY) {
                return dt;
            }
            throw ctxt.wrongTokenException(p, handledType(), JsonToken.END_ARRAY, "after LocalDateTime ints");
        default:
        }
        return (LocalDateTime) ctxt.handleUnexpectedToken(handledType(), p.getCurrentToken(), p,
            "expected String, Number or JSON Array");
    }
}
LocalTimeDeserializer.java000066400000000000000000000047111323201316200415510ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.LocalTime;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;

public class LocalTimeDeserializer
    extends JodaDateDeserializerBase
{
    private static final long serialVersionUID = 1L;

    public LocalTimeDeserializer() {
        this(FormatConfig.DEFAULT_LOCAL_TIMEONLY_PARSER);
    }

    public LocalTimeDeserializer(JacksonJodaDateFormat format) {
        super(LocalTime.class, format);
    }

    @Override
    public JodaDateDeserializerBase withFormat(JacksonJodaDateFormat format) {
        return new LocalTimeDeserializer(format);
    }

    @Override
    public LocalTime deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
    {
        switch (p.getCurrentToken()) {
        case START_ARRAY:
            // [HH,MM,ss,ms?]
            if (p.isExpectedStartArrayToken()) {
                p.nextToken(); // VALUE_NUMBER_INT 
                int hour = p.getIntValue(); 
                p.nextToken(); // VALUE_NUMBER_INT
                int minute = p.getIntValue();
                p.nextToken(); // VALUE_NUMBER_INT
                int second = p.getIntValue();
                p.nextToken(); // VALUE_NUMBER_INT | END_ARRAY
                int millis = 0;
                if (p.getCurrentToken() != JsonToken.END_ARRAY) {
                    millis = p.getIntValue();
                    p.nextToken(); // END_ARRAY?
                }
                if (p.getCurrentToken() != JsonToken.END_ARRAY) {
                    throw ctxt.wrongTokenException(p, handledType(), JsonToken.END_ARRAY, "after LocalTime ints");
                }
                return new LocalTime(hour, minute, second, millis);
            }
            break;
        case VALUE_NUMBER_INT:
            return new LocalTime(p.getLongValue());            
        case VALUE_STRING:
            String str = p.getText().trim();
            return (str.length() == 0) ? null
                    : _format.createParser(ctxt).parseLocalTime(str);
        default:
        }
        return (LocalTime) ctxt.handleUnexpectedToken(handledType(), p.getCurrentToken(), p,
                "expected JSON Array, String or Number");
    }
}MonthDayDeserializer.java000066400000000000000000000022061323201316200414200ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser;

import java.io.IOException;

import org.joda.time.MonthDay;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;

/**
 * A Jackson deserializer for Joda MonthDay objects.
 * 

* Expects a string value compatible with MonthDay's parse operation. */ public class MonthDayDeserializer extends JodaDeserializerBase { private static final long serialVersionUID = 1L; public MonthDayDeserializer() { super(MonthDay.class); } @Override public MonthDay deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { JsonToken t = p.getCurrentToken(); if (t == JsonToken.VALUE_STRING) { String str = p.getText().trim(); if (str.isEmpty()) { return getNullValue(ctxt); } return MonthDay.parse(str); } return (MonthDay) ctxt.handleUnexpectedToken(handledType(), p.getCurrentToken(), p, "expected JSON String"); } } PeriodDeserializer.java000066400000000000000000000061421323201316200411220ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import org.joda.time.*; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaPeriodFormat; public class PeriodDeserializer extends JodaDeserializerBase { private static final long serialVersionUID = 1L; private final JacksonJodaPeriodFormat _format = FormatConfig.DEFAULT_PERIOD_FORMAT; private final boolean _requireFullPeriod; public PeriodDeserializer() { this(true); } public PeriodDeserializer(boolean fullPeriod) { super(fullPeriod ? Period.class : ReadablePeriod.class); _requireFullPeriod = fullPeriod; } @Override public ReadablePeriod deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonToken t = p.getCurrentToken(); if (t == JsonToken.VALUE_STRING) { String str = p.getText().trim(); if (str.isEmpty()) { return null; } return _format.parsePeriod(ctxt, str); } if (t == JsonToken.VALUE_NUMBER_INT) { return new Period(p.getLongValue()); } if (t != JsonToken.START_OBJECT && t != JsonToken.FIELD_NAME) { return (ReadablePeriod) ctxt.handleUnexpectedToken(handledType(), t, p, "expected JSON Number, String or Object"); } JsonNode treeNode = p.readValueAsTree(); String periodType = treeNode.path("fieldType").path("name").asText(); String periodName = treeNode.path("periodType").path("name").asText(); // any "weird" numbers we should worry about? int periodValue = treeNode.path(periodType).asInt(); ReadablePeriod rp; if (periodName.equals( "Seconds" )) { rp = Seconds.seconds( periodValue ); } else if (periodName.equals( "Minutes" )) { rp = Minutes.minutes( periodValue ); } else if (periodName.equals( "Hours" )) { rp = Hours.hours( periodValue ); } else if (periodName.equals( "Days" )) { rp = Days.days( periodValue ); } else if (periodName.equals( "Weeks" )) { rp = Weeks.weeks( periodValue ); } else if (periodName.equals( "Months" )) { rp = Months.months( periodValue ); } else if (periodName.equals( "Years" )) { rp = Years.years( periodValue ); } else { ctxt.reportInputMismatch(handledType(), "Don't know how to deserialize %s using periodName '%s'", handledType().getName(), periodName); rp = null; // never gets here } if (_requireFullPeriod && !(rp instanceof Period)) { rp = rp.toPeriod(); } return rp; } } YearMonthDeserializer.java000066400000000000000000000021721323201316200416050ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import org.joda.time.YearMonth; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; /** * A Jackson deserializer for Joda YearMonth objects. *

* Expects a string value compatible with YearMonth's parse operation. */ public class YearMonthDeserializer extends JodaDeserializerBase { private static final long serialVersionUID = 1L; public YearMonthDeserializer() { super(YearMonth.class); } @Override public YearMonth deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { JsonToken t = p.getCurrentToken(); if (t == JsonToken.VALUE_STRING) { String str = p.getText().trim(); if (str.isEmpty()) { return null; } return YearMonth.parse(str); } return (YearMonth) ctxt.handleUnexpectedToken(handledType(), p.getCurrentToken(), p, "expected JSON String"); } } key/000077500000000000000000000000001323201316200352575ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deserDateTimeKeyDeserializer.java000066400000000000000000000015371323201316200426400ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import java.io.IOException; import java.util.TimeZone; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; public class DateTimeKeyDeserializer extends JodaKeyDeserializer { private static final long serialVersionUID = 1L; @Override protected DateTime deserialize(String key, DeserializationContext ctxt) throws IOException { if (ctxt.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { TimeZone tz = ctxt.getTimeZone(); DateTimeZone dtz = (tz == null) ? DateTimeZone.UTC : DateTimeZone.forTimeZone(tz); return new DateTime(key, dtz); } return DateTime.parse(key); } } DurationKeyDeserializer.java000066400000000000000000000007141323201316200427250ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import com.fasterxml.jackson.databind.DeserializationContext; import java.io.IOException; public class DurationKeyDeserializer extends JodaKeyDeserializer { private static final long serialVersionUID = 1L; @Override protected Object deserialize(String key, DeserializationContext ctxt) throws IOException { return PERIOD_FORMAT.parsePeriod(ctxt, key).toStandardDuration(); } } JodaKeyDeserializer.java000066400000000000000000000016551323201316200420220ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.KeyDeserializer; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaPeriodFormat; import java.io.IOException; abstract class JodaKeyDeserializer extends KeyDeserializer implements java.io.Serializable { private static final long serialVersionUID = 1L; protected final static JacksonJodaPeriodFormat PERIOD_FORMAT = FormatConfig.DEFAULT_PERIOD_FORMAT; @Override public final Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { if (key.length() == 0) { // [JACKSON-360] return null; } return deserialize(key, ctxt); } protected abstract Object deserialize(String key, DeserializationContext ctxt) throws IOException; }LocalDateKeyDeserializer.java000066400000000000000000000012071323201316200427660ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import java.io.IOException; import com.fasterxml.jackson.databind.DeserializationContext; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class LocalDateKeyDeserializer extends JodaKeyDeserializer { private static final long serialVersionUID = 1L; private static final DateTimeFormatter parser = ISODateTimeFormat.localDateParser(); @Override protected LocalDate deserialize(String key, DeserializationContext ctxt) throws IOException { return parser.parseLocalDate(key); } }LocalDateTimeKeyDeserializer.java000066400000000000000000000012431323201316200436050ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import java.io.IOException; import com.fasterxml.jackson.databind.DeserializationContext; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class LocalDateTimeKeyDeserializer extends JodaKeyDeserializer { private static final long serialVersionUID = 1L; private static final DateTimeFormatter parser = ISODateTimeFormat.localDateOptionalTimeParser(); @Override protected LocalDateTime deserialize(String key, DeserializationContext ctxt) throws IOException { return parser.parseLocalDateTime(key); } }LocalTimeKeyDeserializer.java000066400000000000000000000012101323201316200430010ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import java.io.IOException; import com.fasterxml.jackson.databind.DeserializationContext; import org.joda.time.LocalTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class LocalTimeKeyDeserializer extends JodaKeyDeserializer { private static final long serialVersionUID = 1L; private static final DateTimeFormatter parser = ISODateTimeFormat.localTimeParser(); @Override protected LocalTime deserialize(String key, DeserializationContext ctxt) throws IOException { return parser.parseLocalTime(key); } }PeriodKeyDeserializer.java000066400000000000000000000006641323201316200423660ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/deser/keypackage com.fasterxml.jackson.datatype.joda.deser.key; import com.fasterxml.jackson.databind.DeserializationContext; import java.io.IOException; public class PeriodKeyDeserializer extends JodaKeyDeserializer { private static final long serialVersionUID = 1L; @Override protected Object deserialize(String key, DeserializationContext ctxt) throws IOException { return PERIOD_FORMAT.parsePeriod(ctxt, key); } }ser/000077500000000000000000000000001323201316200341565ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/jodaDateMidnightSerializer.java000066400000000000000000000041551323201316200414210ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.DateMidnight; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; /** * Note: Joda has DateMidnight deprecated since at least 2.4, * but we still support it for now. * * @deprecated Since 2.7 */ @Deprecated // since Jackson 2.7 (and Joda 2.4) public class DateMidnightSerializer extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; public DateMidnightSerializer() { this(FormatConfig.DEFAULT_LOCAL_DATEONLY_FORMAT, 0); } public DateMidnightSerializer(JacksonJodaDateFormat format, int shapeOverride) { // true -> use arrays super(DateMidnight.class, format, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, FORMAT_ARRAY, shapeOverride); } @Override public DateMidnightSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new DateMidnightSerializer(formatter, shapeOverride); } @Override public boolean isEmpty(SerializerProvider provider, DateMidnight value) { return (value.getMillis() == 0L); } @Override public void serialize(DateMidnight value, JsonGenerator gen, SerializerProvider provider) throws IOException { switch (_serializationShape(provider)) { case FORMAT_STRING: gen.writeString(_format.createFormatterWithLocale(provider).print(value)); break; case FORMAT_TIMESTAMP: gen.writeNumber(value.getMillis()); break; case FORMAT_ARRAY: // same as with other date-only values gen.writeStartArray(); gen.writeNumber(value.year().get()); gen.writeNumber(value.monthOfYear().get()); gen.writeNumber(value.dayOfMonth().get()); gen.writeEndArray(); } } } DateTimeSerializer.java000066400000000000000000000050501323201316200405470ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; public class DateTimeSerializer extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; public DateTimeSerializer() { this(FormatConfig.DEFAULT_DATETIME_PRINTER, 0); } public DateTimeSerializer(JacksonJodaDateFormat format, int shapeOverride) { // false -> no arrays (numbers) super(DateTime.class, format, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, FORMAT_TIMESTAMP, shapeOverride); } @Override public DateTimeSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new DateTimeSerializer(formatter, shapeOverride); } @Override public boolean isEmpty(SerializerProvider prov, DateTime value) { return (value.getMillis() == 0L); } @Override public void serialize(DateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException { boolean numeric = (_serializationShape(provider) != FORMAT_STRING); // First: simple, non-timezone-included output if (!writeWithZoneId(provider)) { if (numeric) { gen.writeNumber(value.getMillis()); } else { gen.writeString(_format.createFormatter(provider).print(value)); } } else { // and then as per [datatype-joda#44], optional TimeZone inclusion if (numeric) { /* 12-Jul-2015, tatu: Initially planned to support "timestamp[zone-id]" * format as well as textual, but since JSR-310 datatype (Java 8 datetime) * does not support it, was left out of 2.6. */ /* sb = new StringBuilder(20) .append(value.getMillis()); */ gen.writeNumber(value.getMillis()); return; } StringBuilder sb = new StringBuilder(40) .append(_format.createFormatter(provider).withOffsetParsed().print(value)); sb = sb.append('[') .append(value.getZone()) .append(']'); gen.writeString(sb.toString()); } } } DateTimeZoneSerializer.java000066400000000000000000000023741323201316200414110ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.WritableTypeId; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; public class DateTimeZoneSerializer extends JodaSerializerBase { private static final long serialVersionUID = 1L; public DateTimeZoneSerializer() { super(DateTimeZone.class); } @Override public void serialize(DateTimeZone value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(value.getID()); } // as per [datatype-joda#82], need to ensure we will indicate nominal, NOT physical type: @Override public void serializeWithType(DateTimeZone value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException { WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeSer.typeId(value, DateTimeZone.class, JsonToken.VALUE_STRING)); serialize(value, g, provider); typeSer.writeTypeSuffix(g, typeIdDef); } } DurationSerializer.java000066400000000000000000000035061323201316200406440ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.Duration; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; /** * Serializes a Duration; either as number of millis, or, if textual output * requested, using ISO-8601 format. */ public class DurationSerializer // non final since 2.6.1 extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; // NOTE: formatter is not really used directly for printing, but we do need // it as container for numeric/textual distinction public DurationSerializer() { this(FormatConfig.DEFAULT_DATEONLY_FORMAT, 0); } public DurationSerializer(JacksonJodaDateFormat formatter, int shapeOverride) { // false -> no arrays (numbers) super(Duration.class, formatter, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, FORMAT_TIMESTAMP, shapeOverride); } @Override public DurationSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new DurationSerializer(formatter, shapeOverride); } @Override public boolean isEmpty(SerializerProvider prov, Duration value) { return (value.getMillis() == 0L); } @Override public void serialize(Duration value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (_serializationShape(provider) == FORMAT_STRING) { gen.writeString(value.toString()); } else { gen.writeNumber(value.getMillis()); } } } InstantSerializer.java000066400000000000000000000031371323201316200404770ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.Instant; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; public class InstantSerializer // non final since 2.6.1 extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; // NOTE: formatter not used for printing at all, hence choice doesn't matter public InstantSerializer() { this(FormatConfig.DEFAULT_TIMEONLY_FORMAT, 0); } public InstantSerializer(JacksonJodaDateFormat format, int shapeOverride) { super(Instant.class, format, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, FORMAT_TIMESTAMP, shapeOverride); } @Override public InstantSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new InstantSerializer(formatter, shapeOverride); } // @since 2.5 @Override public boolean isEmpty(SerializerProvider prov, Instant value) { return (value.getMillis() == 0L); } @Override public void serialize(Instant value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (_serializationShape(provider) == FORMAT_STRING) { gen.writeString(value.toString()); } else { gen.writeNumber(value.getMillis()); } } } IntervalSerializer.java000066400000000000000000000037011323201316200406400ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; import org.joda.time.*; import org.joda.time.format.DateTimeFormatter; public class IntervalSerializer extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; public IntervalSerializer() { this(FormatConfig.DEFAULT_DATETIME_PRINTER, 0); } public IntervalSerializer(JacksonJodaDateFormat format, int shapeOverride) { super(Interval.class, format, SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, FORMAT_TIMESTAMP, shapeOverride); } @Override public IntervalSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new IntervalSerializer(formatter, shapeOverride); } @Override public boolean isEmpty(SerializerProvider prov, Interval value) { return (value.getStartMillis() == value.getEndMillis()); } @Override public void serialize(Interval interval, JsonGenerator gen, SerializerProvider provider) throws IOException { // 19-Nov-2014, tatu: Support textual representation similar to what Joda uses // (and why not exact one? In future we'll make it configurable) String repr; if (_serializationShape(provider) == FORMAT_STRING) { DateTimeFormatter f = _format.createFormatter(provider); repr = f.print(interval.getStart()) + "/" + f.print(interval.getEnd()); } else { // !!! TODO: maybe allow textual format too? repr = interval.getStartMillis() + "-" + interval.getEndMillis(); } gen.writeString(repr); } } JodaDateSerializerBase.java000066400000000000000000000131451323201316200413250ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.*; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; public abstract class JodaDateSerializerBase extends JodaSerializerBase // need contextualization to read per-property annotations implements ContextualSerializer { private static final long serialVersionUID = 1L; // // Since 2.9 protected final static int FORMAT_STRING = 1; protected final static int FORMAT_TIMESTAMP = 2; protected final static int FORMAT_ARRAY = 3; protected final JacksonJodaDateFormat _format; protected final SerializationFeature _featureForNumeric; /** * Shape to use for generic "use numeric" feature (instead of more specific * JsonFormat.shape). * * @since 2.9 */ protected final int _defaultNumericShape; /** * Marker set to non-0 if (and only if) property or type override exists. * * @since 2.9 */ protected final int _shapeOverride; protected JodaDateSerializerBase(Class type, JacksonJodaDateFormat format, SerializationFeature numericFeature, int defaultNumericShape, int shapeOverride) { super(type); _format = format; _featureForNumeric = numericFeature; _defaultNumericShape = defaultNumericShape; _shapeOverride = shapeOverride; } /** * @since 2.9 */ public abstract JodaDateSerializerBase withFormat(JacksonJodaDateFormat format, int shapeOverride); @Override public boolean isEmpty(SerializerProvider prov, T value) { return value == null; } @Override public JsonSerializer createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException { JsonFormat.Value ann = findFormatOverrides(prov, property, handledType()); if (ann != null) { int shapeOverride = 0; JacksonJodaDateFormat format = _format; Boolean useTimestamp; // Simple case first: serialize as numeric timestamp? final JsonFormat.Shape shape = ann.getShape(); if (shape.isNumeric()) { useTimestamp = Boolean.TRUE; shapeOverride = FORMAT_TIMESTAMP; } else if (shape == JsonFormat.Shape.STRING) { useTimestamp = Boolean.FALSE; shapeOverride = FORMAT_STRING; } else if (shape == JsonFormat.Shape.ARRAY) { // 17-Nov-2014, tatu: also, arrays typically contain non-string representation useTimestamp = Boolean.TRUE; shapeOverride = FORMAT_ARRAY; } else { useTimestamp = null; shapeOverride = 0; } // must not call if flag defined, to rely on defaults: if (useTimestamp != null) { format = format.withUseTimestamp(useTimestamp); } format = format.with(ann); if ((format != _format) || (shapeOverride != _shapeOverride)) { return withFormat(format, shapeOverride); } } return this; } @Override public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint) { switch (_serializationShape(provider)) { case FORMAT_TIMESTAMP: return createSchemaNode("array", true); case FORMAT_ARRAY: return createSchemaNode("number", true); case FORMAT_STRING: default: return createSchemaNode("string", true); } } @Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { switch (_serializationShape(visitor.getProvider())) { case FORMAT_TIMESTAMP: { JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint); if (v2 != null) { v2.numberType(JsonParser.NumberType.LONG); v2.format(JsonValueFormat.UTC_MILLISEC); } } break; case FORMAT_ARRAY: { JsonArrayFormatVisitor v2 = visitor.expectArrayFormat(typeHint); if (v2 != null) { v2.itemsFormat(JsonFormatTypes.INTEGER); } } break; case FORMAT_STRING: default: { JsonStringFormatVisitor v2 = visitor.expectStringFormat(typeHint); if (v2 != null) { v2.format(JsonValueFormat.DATE_TIME); } } } } /* /********************************************************** /* Helper methods /********************************************************** */ /** * @since 2.8 */ protected boolean writeWithZoneId(SerializerProvider provider) { return _format.shouldWriteWithZoneId(provider); } /** * @since 2.9 */ protected int _serializationShape(SerializerProvider provider) { int shape = _shapeOverride; if (shape == 0) { if (_format.useTimestamp(provider, _featureForNumeric)) { shape = _defaultNumericShape; } else { shape = FORMAT_STRING; } } return shape; } } JodaSerializerBase.java000066400000000000000000000022701323201316200405240ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.WritableTypeId; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; abstract class JodaSerializerBase extends StdSerializer { private static final long serialVersionUID = 1L; protected JodaSerializerBase(Class cls) { super(cls); } @Override public void serializeWithType(T value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException { // NOTE: we do not actually know the exact shape (or, rather, it varies by settings // and so should not claim particular shape) -- but need to make sure NOT to report // as `Shape.OBJECT` or `Shape.ARRAY` WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeSer.typeId(value, JsonToken.VALUE_STRING)); serialize(value, g, provider); typeSer.writeTypeSuffix(g, typeIdDef); } } LocalDateSerializer.java000066400000000000000000000037721323201316200407140ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.LocalDate; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; public class LocalDateSerializer // non final since 2.6.1 extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; public LocalDateSerializer() { this(FormatConfig.DEFAULT_LOCAL_DATEONLY_FORMAT, 0); } public LocalDateSerializer(JacksonJodaDateFormat format, int shapeOverride) { super(LocalDate.class, format, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, FORMAT_ARRAY, shapeOverride); } @Override public LocalDateSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new LocalDateSerializer(formatter, shapeOverride); } // is there a natural "empty" value to check against? /* @Override public boolean isEmpty(LocalDate value) { return (value.getMillis() == 0L); } */ @Override public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (_serializationShape(provider) == FORMAT_STRING) { gen.writeString(_format.createFormatter(provider).print(value)); return; } // 28-Jul-2017, tatu: Wrt [dataformat-joda#39]... we could perhaps support timestamps, // but only by specifying what to do with time (`LocalTime`) AND timezone. For now, // seems like asking for trouble really... so only use array notation. gen.writeStartArray(); gen.writeNumber(value.year().get()); gen.writeNumber(value.monthOfYear().get()); gen.writeNumber(value.dayOfMonth().get()); gen.writeEndArray(); } } LocalDateTimeSerializer.java000066400000000000000000000047431323201316200415320ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; public class LocalDateTimeSerializer // non final since 2.6.1 extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; public LocalDateTimeSerializer() { this(FormatConfig.DEFAULT_LOCAL_DATETIME_PRINTER, 0); } public LocalDateTimeSerializer(JacksonJodaDateFormat format, int shapeOverride) { super(LocalDateTime.class, format, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, FORMAT_ARRAY, shapeOverride); } @Override public LocalDateTimeSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new LocalDateTimeSerializer(formatter, shapeOverride); } // is there a natural "empty" value to check against? /* @Override public boolean isEmpty(LocalDateTime value) { return (value.getMillis() == 0L); } */ @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException { switch (_serializationShape(provider)) { case FORMAT_STRING: gen.writeString(_format.createFormatter(provider).print(value)); break; case FORMAT_TIMESTAMP: { // copied from `LocalDateTimeDeserializer`... DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(provider.getTimeZone()); gen.writeNumber(value.toDateTime(tz).getMillis()); } break; case FORMAT_ARRAY: // Timestamp here actually means an array of values gen.writeStartArray(); gen.writeNumber(value.year().get()); gen.writeNumber(value.monthOfYear().get()); gen.writeNumber(value.dayOfMonth().get()); gen.writeNumber(value.hourOfDay().get()); gen.writeNumber(value.minuteOfHour().get()); gen.writeNumber(value.secondOfMinute().get()); gen.writeNumber(value.millisOfSecond().get()); gen.writeEndArray(); } } }LocalTimeSerializer.java000066400000000000000000000036051323201316200407300ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.LocalTime; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; public class LocalTimeSerializer // non final since 2.6.1 extends JodaDateSerializerBase { private static final long serialVersionUID = 1L; public LocalTimeSerializer() { this(FormatConfig.DEFAULT_LOCAL_TIMEONLY_PRINTER, 0); } public LocalTimeSerializer(JacksonJodaDateFormat format, int shapeOverride) { super(LocalTime.class, format, SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, FORMAT_ARRAY, shapeOverride); } @Override public LocalTimeSerializer withFormat(JacksonJodaDateFormat formatter, int shapeOverride) { return new LocalTimeSerializer(formatter, shapeOverride); } // is there a natural "empty" value to check against? /* @Override public boolean isEmpty(LocalTime value) { return (value.getMillis() == 0L); } */ @Override public void serialize(LocalTime value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (_serializationShape(provider) == FORMAT_STRING) { gen.writeString(_format.createFormatter(provider).print(value)); return; } // Timestamp here actually means an array of values gen.writeStartArray(); gen.writeNumber(value.hourOfDay().get()); gen.writeNumber(value.minuteOfHour().get()); gen.writeNumber(value.secondOfMinute().get()); gen.writeNumber(value.millisOfSecond().get()); gen.writeEndArray(); } } PeriodSerializer.java000066400000000000000000000073421323201316200403030ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import org.joda.time.ReadablePeriod; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.*; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import com.fasterxml.jackson.datatype.joda.cfg.FormatConfig; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaPeriodFormat; /** * Serializes a {@link ReadablePeriod} using Joda default formatting. *

* TODO: allow serialization as an array of numbers, for numeric ("timestamp") * notation? */ public class PeriodSerializer // non final since 2.6.1 // alas, difficult to extend JodaDateSerializerBase extends JodaSerializerBase implements ContextualSerializer { private static final long serialVersionUID = 1L; protected final JacksonJodaPeriodFormat _format; public PeriodSerializer() { this(FormatConfig.DEFAULT_PERIOD_FORMAT); } protected PeriodSerializer(JacksonJodaPeriodFormat format) { super(ReadablePeriod.class); _format = format; } // anything naturally "empty" to check? /* @Override public boolean isEmpty(ReadablePeriod value) { return (value.getMillis() == 0L); } */ // Lots of work, although realistically, won't have much or any effect... @Override public JsonSerializer createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException { if (property != null) { JsonFormat.Value ann = findFormatOverrides(prov, property, handledType()); if (ann != null) { JacksonJodaPeriodFormat format = _format; Boolean useTimestamp; // Simple case first: serialize as numeric timestamp? if (ann.getShape().isNumeric()) { useTimestamp = Boolean.TRUE; } else if (ann.getShape() == JsonFormat.Shape.STRING) { useTimestamp = Boolean.FALSE; } else if (ann.getShape() == JsonFormat.Shape.ARRAY) { // 17-Nov-2014, tatu: also, arrays typically contain non-string representation useTimestamp = Boolean.TRUE; } else { useTimestamp = null; } // must not call if flag defined, to rely on defaults: if (useTimestamp != null) { format = format.withUseTimestamp(useTimestamp); } // for others, safe to call, null/empty just ignored format = format.withFormat(ann.getPattern().trim()); format = format.withLocale(ann.getLocale()); if (format != _format) { return new PeriodSerializer(format); } } } return this; } @Override public void serialize(ReadablePeriod value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(_format.createFormatter(provider).print(value)); } @Override public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint) { return createSchemaNode("string", true); } @Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { JsonStringFormatVisitor v2 = visitor.expectStringFormat(typeHint); // Alas, nothing really matches Periods; should not call DATE or DATE_TIME if (v2 != null) { // v2.format(JsonValueFormat.DATE); } } } jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/resources/000077500000000000000000000000001323201316200255725ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/resources/META-INF/000077500000000000000000000000001323201316200267325ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/resources/META-INF/LICENSE000066400000000000000000000005141323201316200277370ustar00rootroot00000000000000This copy of Jackson JSON processor streaming parser/generator is licensed under the Apache (Software) License, version 2.0 ("the License"). See the License for details about distribution rights, and the specific rights regarding derivate works. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/resources/META-INF/services/000077500000000000000000000000001323201316200305555ustar00rootroot00000000000000com.fasterxml.jackson.databind.Module000066400000000000000000000000571323201316200376250ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/main/resources/META-INF/servicescom.fasterxml.jackson.datatype.joda.JodaModule jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/000077500000000000000000000000001323201316200236135ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/000077500000000000000000000000001323201316200245345ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/000077500000000000000000000000001323201316200253125ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/000077500000000000000000000000001323201316200273175ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/000077500000000000000000000000001323201316200307475ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/000077500000000000000000000000001323201316200325625ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/000077500000000000000000000000001323201316200334775ustar00rootroot00000000000000DateMidnightTest.java000066400000000000000000000141551323201316200374720ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import java.io.IOException; import java.util.TimeZone; import org.joda.time.*; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @SuppressWarnings("deprecation") // because DateMidnight deprecated by Joda public class DateMidnightTest extends JodaTestBase { // let's default to String serialization private final ObjectMapper MAPPER = jodaMapper() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface MixInForTypeId { } static class AlternateFormat { @JsonFormat(pattern="dd'.'MM'.'YYYY") public DateMidnight value; public AlternateFormat() { } public AlternateFormat(DateMidnight v) { value = v; } } static class FormattedDateMidnight { @JsonFormat(timezone="EST") public DateMidnight dateMidnight; } static class FormattedDateAsTimestamp { @JsonFormat(shape=JsonFormat.Shape.NUMBER) public DateMidnight value; protected FormattedDateAsTimestamp() { } public FormattedDateAsTimestamp(DateMidnight d) { value = d; } } /* /********************************************************** /* Test methods /********************************************************** */ public void testDateMidnightDeserWithTimeZone() throws IOException { MAPPER.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); // couple of acceptable formats, so: DateMidnight date = MAPPER.readValue("[2001,5,25]", DateMidnight.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); DateMidnight date2 = MAPPER.readValue(quote("2005-07-13"), DateMidnight.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), DateMidnight.class)); MAPPER.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); // couple of acceptable formats, so: date = MAPPER.readValue("[2001,5,25]", DateMidnight.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); date2 = MAPPER.readValue(quote("2005-07-13"), DateMidnight.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), DateMidnight.class)); } public void testDateMidnightDeser() throws IOException { // couple of acceptable formats, so: DateMidnight date = MAPPER.readValue("[2001,5,25]", DateMidnight.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); DateMidnight date2 = MAPPER.readValue(quote("2005-07-13"), DateMidnight.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), DateMidnight.class)); } public void testDateMidnightDeserWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(DateMidnight.class, MixInForTypeId.class); // couple of acceptable formats, so: DateMidnight date = mapper.readValue("[\"org.joda.time.DateMidnight\",[2001,5,25]]", DateMidnight.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); DateMidnight date2 = mapper.readValue("[\"org.joda.time.DateMidnight\",\"2005-07-13\"]", DateMidnight.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); } public void testCustomFormat() throws Exception { String STR = "2015-06-19"; String ALT = "19.06.2015"; final DateMidnight inputDate = new DateMidnight(STR); AlternateFormat input = new AlternateFormat(inputDate); String json = MAPPER.writeValueAsString(input); if (!json.contains(ALT)) { fail("Should contain '"+ALT+"', did not: "+json); } AlternateFormat output = MAPPER.readValue(json, AlternateFormat.class); assertNotNull(output.value); assertEquals(inputDate, output.value); } public void testWithTimeZoneOverride() throws Exception { ObjectMapper mapper = jodaMapper(); DateMidnight date = mapper.readValue("[2001,5,25]", DateMidnight.class); FormattedDateMidnight input = new FormattedDateMidnight(); input.dateMidnight = date; String json = mapper.writeValueAsString(input); FormattedDateMidnight result = mapper.readValue(json, FormattedDateMidnight.class); assertNotNull(result); // Ensure timezone sticks: DateMidnight resultMidnight = result.dateMidnight; assertEquals(2001, resultMidnight.getYear()); assertEquals(5, resultMidnight.getMonthOfYear()); assertEquals(25, resultMidnight.getDayOfMonth()); DateTimeZone resultTz = resultMidnight.getZone(); // Is this stable enough for testing? assertEquals("America/New_York", resultTz.getID()); } public void testSerializeAsTimestamp() throws Exception { assertEquals(aposToQuotes("{'value':0}"), MAPPER.writeValueAsString(new FormattedDateAsTimestamp( new DateMidnight(0, DateTimeZone.UTC)))); } } DateTimeTest.java000066400000000000000000000205021323201316200366160ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import java.io.IOException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class DateTimeTest extends JodaTestBase { static class DateAsText { @JsonFormat(shape=JsonFormat.Shape.STRING) public DateTime date; public DateAsText(DateTime d) { date = d; } } static class DateTimeWrapper { public DateTime value; public DateTimeWrapper(DateTime v) { value = v; } protected DateTimeWrapper() { } } static class CustomDate { // note: 'SS' means 'short representation' @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="SS", locale="en") public DateTime date; public CustomDate(DateTime d) { date = d; } } static class EuroDate { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd.MM.YYYY' 'HH:mm") public DateTime date; public EuroDate() { } public EuroDate(DateTime d) { date = d; } } static class Beanie { public final DateTime jodaDateTime; public final java.util.Date javaUtilDate; @JsonCreator public Beanie(@JsonProperty("jodaDateTime") DateTime jodaDateTime, @JsonProperty("javaUtilDate") java.util.Date javaUtilDate) { this.jodaDateTime = jodaDateTime; this.javaUtilDate = javaUtilDate; } } static class FormattedDateTime { @JsonFormat(timezone="EST") public DateTime dateTime; } @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface TypeInfoMixIn { } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); private final static ObjectMapper STRING_MAPPER = jodaMapper(); static { STRING_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } private final DateTime DATE_JAN_1_1970_UTC = new DateTime(0L, DateTimeZone.UTC); /** * First: let's ensure that serialization does not fail * with an error (see [JACKSON-157]). */ public void testSerializationDefaultAsTimestamp() throws IOException { // let's use epoch time (Jan 1, 1970, UTC) // by default, dates use timestamp, so: assertEquals("0", MAPPER.writeValueAsString(DATE_JAN_1_1970_UTC)); } public void testSerializationFeatureNoTimestamp() throws IOException { String json = MAPPER.writer() .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(DATE_JAN_1_1970_UTC); assertEquals(quote("1970-01-01T00:00:00.000Z"), json); } public void testAnnotationAsText() throws IOException { ObjectMapper m = jodaMapper(); m.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // with annotations, doesn't matter if mapper configured to use timestamps assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000Z'}"), m.writeValueAsString(new DateAsText(DATE_JAN_1_1970_UTC))); } // for [datatype-joda#70] public void testAsTextNoMilliseconds() throws Exception { DateTime value = MAPPER.readValue(quote("2015-07-27T08:11:07-07:00"), DateTime.class); assertNotNull(value); } public void testCustomPatternStyle() throws IOException { // or, using annotations assertEquals(aposToQuotes("{'date':'1/1/70 12:00 AM'}"), STRING_MAPPER.writeValueAsString(new CustomDate(DATE_JAN_1_1970_UTC))); } public void testSerializationWithTypeInfo() throws IOException { // let's use epoch time (Jan 1, 1970, UTC) DateTime dt = new DateTime(0L, DateTimeZone.UTC); // by default, dates use timestamp, so: assertEquals("0", MAPPER.writeValueAsString(dt)); // but if re-configured, as regular ISO-8601 string ObjectMapper m = jodaMapper(); m.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); m.addMixIn(DateTime.class, TypeInfoMixIn.class); assertEquals("[\"org.joda.time.DateTime\",\"1970-01-01T00:00:00.000Z\"]", m.writeValueAsString(dt)); } public void testIso8601ThroughJoda() throws Exception { ObjectMapper mapper = new ObjectMapper() .registerModule(new JodaModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz"); java.util.Date targetDate = df.parse("2000-01-01 00:00:00 UTC"); Beanie expectedBean = new Beanie(new DateTime(targetDate.getTime()), targetDate); String expectedJSON = "{\"jodaDateTime\":\"2000-01-01T00:00:00.000Z\"," + "\"javaUtilDate\":\"2000-01-01T00:00:00.000+0000\"}"; String actualJSON = mapper.writeValueAsString(expectedBean); assertEquals(actualJSON, expectedJSON); Beanie actualBean = mapper.readValue(actualJSON, Beanie.class); assertEquals(actualBean.javaUtilDate, expectedBean.javaUtilDate); assertEquals(actualBean.jodaDateTime.getMillis(), expectedBean.jodaDateTime.getMillis()); assertEquals(expectedBean.jodaDateTime.getMillis(), actualBean.jodaDateTime.getMillis()); // note: timezone/offset may vary, shouldn't check: // assertEquals(expectedBean.jodaDateTime, actualBean.jodaDateTime); } public void testCustomFormat() throws Exception { String STR = "2015-06-19T19:05Z"; String ALT = "19.06.2015 19:05"; final DateTime inputDate = new DateTime(STR); EuroDate input = new EuroDate(inputDate); String json = MAPPER.writeValueAsString(input); if (!json.contains(ALT)) { fail("Should contain '"+ALT+"', did not: "+json); } EuroDate output = MAPPER.readValue(json, EuroDate.class); assertNotNull(output.date); // Timezone may (and most likely will) differ so... assertEquals(inputDate.getMillis(), output.date.getMillis()); } public void testWithTimeZoneOverride() throws Exception { DateTime date = MAPPER.readValue(quote("2014-01-20T08:59:01.000-0500"), DateTime.class); FormattedDateTime input = new FormattedDateTime(); input.dateTime = date; String json = MAPPER.writeValueAsString(input); FormattedDateTime result = MAPPER.readValue(json, FormattedDateTime.class); assertNotNull(result); // Ensure timezone sticks: DateTime resultMidnight = result.dateTime; assertEquals(2014, resultMidnight.getYear()); assertEquals(1, resultMidnight.getMonthOfYear()); assertEquals(20, resultMidnight.getDayOfMonth()); DateTimeZone resultTz = resultMidnight.getZone(); // Is this stable enough for testing? assertEquals("America/New_York", resultTz.getID()); } // since 2.8 public void testConfigOverrides() throws Exception { ObjectMapper mapper = jodaMapper(); mapper.configOverride(DateTime.class) .setFormat(JsonFormat.Value.forPattern("dd.MM.YYYY' 'HH:mm") .withShape(JsonFormat.Shape.STRING)); DateTimeWrapper input = new DateTimeWrapper(DATE_JAN_1_1970_UTC); final String EXP_DATE = "\"01.01.1970 00:00\""; final String json = "{\"value\":"+EXP_DATE+"}"; assertEquals(json, mapper.writeValueAsString(input)); assertEquals(EXP_DATE, mapper.writeValueAsString(DATE_JAN_1_1970_UTC)); // also read back DateTimeWrapper result = mapper.readValue(json, DateTimeWrapper.class); assertNotNull(result); assertEquals(input.value, result.value); DateTime resultDate = mapper.readValue(EXP_DATE, DateTime.class); assertEquals(DATE_JAN_1_1970_UTC, resultDate); } } IntervalSerializationTest.java000066400000000000000000000052521323201316200414510ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import java.io.IOException; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.*; public class IntervalSerializationTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } static class FormattedInterval { @JsonFormat(timezone="EST") public Interval interval; } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); { MAPPER.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); MAPPER.enable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS); } private final ObjectWriter WRITER = MAPPER.writer(); public void testIntervalSerBasic() throws IOException { Interval interval = new Interval(1396439982, 1396440001); assertEquals(quote("1396439982-1396440001"), MAPPER.writeValueAsString(interval)); // related to #48 assertEquals(quote("1970-01-17T03:53:59.982Z/1970-01-17T03:54:00.001Z"), WRITER.without(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) .writeValueAsString(interval)); } public void testIntervalSerWithTypeInfo() throws IOException { Interval interval = new Interval(1396439982, 1396440001); ObjectMapper mapper = jodaMapper(); mapper.addMixIn(Interval.class, ObjectConfiguration.class); assertEquals("[\"org.joda.time.Interval\"," + quote("1396439982-1396440001") + "]", mapper.writeValueAsString(interval)); } public void testWithTimeZoneOverride() throws Exception { Interval int1 = new Interval(1396439982, 1396440001); FormattedInterval input = new FormattedInterval(); input.interval = int1; String json = MAPPER.writeValueAsString(input); FormattedInterval result = MAPPER.readValue(json, FormattedInterval.class); assertNotNull(result); // Ensure timezone sticks: Interval resultInt = result.interval; assertEquals(1396439982, resultInt.getStartMillis()); assertEquals(1396440001, resultInt.getEndMillis()); DateTimeZone resultTz = resultInt.getStart().getZone(); // Is this stable enough for testing? assertEquals("America/New_York", resultTz.getID()); } } JodaMapperTest.java000066400000000000000000000017311323201316200371470ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class JodaMapperTest { @Test public void test_writeDatesAsTimestamps_property() { JodaMapper objectUnderTest = new JodaMapper(); objectUnderTest.setWriteDatesAsTimestamps(true); assertThat(objectUnderTest.getWriteDatesAsTimestamps(), is(true)); objectUnderTest.setWriteDatesAsTimestamps(false); assertThat(objectUnderTest.getWriteDatesAsTimestamps(), is(false)); } @Test public void setWriteDatesAsTimestamps_sets_the_WRITE_DATES_AS_TIMESTAMPS_configuration() { JodaMapper objectUnderTest = new JodaMapper(); objectUnderTest.setWriteDatesAsTimestamps(true); assertThat(objectUnderTest.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS), is(true)); } } JodaTestBase.java000066400000000000000000000031611323201316200365740ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import com.fasterxml.jackson.databind.ObjectMapper; import junit.framework.TestCase; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.*; public abstract class JodaTestBase extends TestCase { protected static ObjectMapper jodaMapper() { return new JodaMapper(); } /* /********************************************************** /* Additional assert methods /********************************************************** */ protected void assertEquals(int[] exp, int[] act) { assertArrayEquals(exp, act); } /* /********************************************************** /* Helper methods /********************************************************** */ protected void verifyException(Throwable e, String... matches) { String msg = e.getMessage(); String lmsg = (msg == null) ? "" : msg.toLowerCase(); for (String match : matches) { String lmatch = match.toLowerCase(); if (lmsg.indexOf(lmatch) >= 0) { return; } } fail("Expected an exception with one of substrings ("+Arrays.asList(matches)+"): got one with message \""+msg+"\""); } public String quote(String str) { return '"'+str+'"'; } protected String aposToQuotes(String json) { return json.replace("'", "\""); } protected T readAndMapFromString(ObjectMapper m, String input, Class cls) throws IOException { return (T) m.readValue("\""+input+"\"", cls); } } MixedListTest.java000066400000000000000000000024721323201316200370320ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import java.util.*; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class MixedListTest extends JodaTestBase { private final ObjectMapper MAPPER = jodaMapper(); public void testMixedList() throws Exception { final Map map = new HashMap(); DateTime dt = new DateTime(DateTimeZone.UTC); map.put("A", dt); map.put("B", 0); final String json = MAPPER.writeValueAsString(map); // by default, timestamps should come out as longs... final Map result = MAPPER.readValue(json, new TypeReference>() { }); assertEquals(2, result.size()); Object obB = result.get("B"); assertNotNull(obB); if (!(obB instanceof Number)) { fail("Expected 'B' to be a Number; instead of value of type "+obB.getClass().getName()); } assertEquals(Integer.valueOf(0), result.get("B")); Object obA = result.get("A"); assertNotNull(obA); if (!(obA instanceof Number)) { fail("Expected 'A' to be a number; instead of value of type "+obA.getClass().getName()); } } } TestVersions.java000066400000000000000000000011701323201316200367320ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import java.io.*; import com.fasterxml.jackson.core.Versioned; /** * Simple verification that version access works. */ public class TestVersions extends JodaTestBase { public void testVersions() throws IOException { JodaModule m = new JodaModule(); assertVersion(m); } /* /********************************************************** /* Helper methods /********************************************************** */ private void assertVersion(Versioned v) { assertEquals(PackageVersion.VERSION, v.version()); } } TimeZoneTest.java000066400000000000000000000152301323201316200366560ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodapackage com.fasterxml.jackson.datatype.joda; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.*; // for [datatype-joda#44] public class TimeZoneTest extends JodaTestBase { // November 3, 2013 at 1:00a is the fall back DST transition that year in much of the US. private static final int FALL_BACK_YEAR = 2013; private static final int FALL_BACK_MONTH = 11; private static final int FALL_BACK_DAY = 3; // The first one for America/Los_Angeles happens at 8:00 UTC. private static final int FIRST_FALL_BACK_HOUR = 8; // And the second one happens at 9:00 UTC private static final int SECOND_FALL_BACK_HOUR = 9; private static final DateTimeZone AMERICA_LOS_ANGELES = DateTimeZone.forID("America/Los_Angeles"); private final DateTime DATE_JAN_1_1970_UTC = new DateTime(0L, DateTimeZone.UTC); private final DateTime DATE_JAN_1_1970_UTC_IN_AMERICA_LA = new DateTime(0L, AMERICA_LOS_ANGELES); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface TypeInfoMixIn { } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); public void testSimple() throws Exception { // First, no zone id included ObjectWriter w = MAPPER.writer() .without(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); assertEquals("0", w.with(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(DATE_JAN_1_1970_UTC)); assertEquals(quote("1970-01-01T00:00:00.000Z"), w.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(DATE_JAN_1_1970_UTC)); // then with zone id w = w.with(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); // 12-Jul-2015, tatu: Despite initial plans, support for timezone id with timestamps // was not included in 2.6.0 final. /* assertEquals(quote("0[UTC]"), w.with(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(DATE_JAN_1_1970_UTC)); */ assertEquals(quote("1970-01-01T00:00:00.000Z[UTC]"), w.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(DATE_JAN_1_1970_UTC)); } /** * Make sure zoneId and zoneOffset are serialized consistently as jsr310 does. * * https://github.com/FasterXML/jackson-datatype-joda/issues/73 */ public void testWriteDatesWithZoneIdAndConsistentZoneOffset() throws Exception { ObjectWriter w = MAPPER.writer(); w = w.with(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); assertEquals(quote("1969-12-31T16:00:00.000-08:00[America/Los_Angeles]"), w.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(DATE_JAN_1_1970_UTC_IN_AMERICA_LA)); } public void testRoundTrip() throws Exception { ObjectWriter w = MAPPER.writer() .with(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); DateTime input = new DateTime(2014, 8, 24, 5, 17, 45, DateTimeZone.forID("America/Chicago")); // arbitrary String json; DateTime result; // Time zone id only supported as regular text json = w.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(input); ObjectMapper mapper = jodaMapper(); mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); result = mapper.readValue(json, DateTime.class); assertEquals("Actual timepoints differ", input.getMillis(), result.getMillis()); assertEquals("TimeZones differ", input, result); // Then timestamp: will not currently (2.6) write out timezone id json = w.with(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(input); result = mapper.readValue(json, DateTime.class); assertEquals("Actual timepoints differ", input.getMillis(), result.getMillis()); // .. meaning we can not test this: // assertEquals("TimeZones differ", input, result); } /** * Test that de/serializing an ambiguous time (e.g. a 'fall back' DST transition) works and preserves the proper * instants in time and time zones. */ public void testFallBackTransition() throws Exception { DateTime firstOneAmUtc = new DateTime(FALL_BACK_YEAR, FALL_BACK_MONTH, FALL_BACK_DAY, FIRST_FALL_BACK_HOUR, 0, 0, DateTimeZone.UTC); DateTime secondOneAmUtc = new DateTime(FALL_BACK_YEAR, FALL_BACK_MONTH, FALL_BACK_DAY, SECOND_FALL_BACK_HOUR, 0, 0, DateTimeZone.UTC); DateTime firstOneAm = new DateTime(firstOneAmUtc, AMERICA_LOS_ANGELES); DateTime secondOneAm = new DateTime(secondOneAmUtc, AMERICA_LOS_ANGELES); ObjectWriter w = MAPPER.writer() .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .with(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); String firstOneAmStr = w.writeValueAsString(firstOneAm); String secondOneAmStr = w.writeValueAsString(secondOneAm); ObjectMapper mapper = jodaMapper(); mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); DateTime firstRoundTrip = mapper.readValue(firstOneAmStr, DateTime.class); DateTime secondRoundTrip = mapper.readValue(secondOneAmStr, DateTime.class); assertEquals("Actual timepoints differ", firstOneAm.getMillis(), firstRoundTrip.getMillis()); assertEquals("TimeZones differ", firstOneAm, firstRoundTrip); assertEquals("Actual timepoints differ", secondOneAm.getMillis(), secondRoundTrip.getMillis()); assertEquals("TimeZones differ", secondOneAm, secondRoundTrip); } public void testSerializationWithTypeInfo() throws Exception { // but if re-configured to include the time zone ObjectMapper m = jodaMapper(); m.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); m.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); m.addMixIn(DateTime.class, TypeInfoMixIn.class); assertEquals("[\"org.joda.time.DateTime\",\"1970-01-01T00:00:00.000Z[UTC]\"]", m.writeValueAsString(DATE_JAN_1_1970_UTC)); } } deser/000077500000000000000000000000001323201316200345225ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodaDateTimeDeserTest.java000066400000000000000000000151421323201316200407070ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import com.fasterxml.jackson.annotation.JsonFormat; import org.joda.time.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; /** * Unit tests for verifying limited interoperability for Joda time. * Basic support is added for handling {@link DateTime}; more can be * added over time if and when requested. */ public class DateTimeDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } static class DateTimeZoneWrapper { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") public DateTimeZone tz; public DateTimeZoneWrapper() { } public DateTimeZoneWrapper(DateTimeZone tz0) { tz = tz0; } } static class ReadableDateTimeWithoutContextTZOverride { @JsonFormat(without = JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) public ReadableDateTime time; } static class ReadableDateTimeWithContextTZOverride { @JsonFormat(with = JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) public ReadableDateTime time; } static class Issue93Bean { @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public DateTime jodaDateTime; public DateTime getJodaDateTime() { return jodaDateTime; } } /* /********************************************************** /* Tests for DateTime (and closely related) /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); /** * Ok, then: should be able to convert from JSON String or Number, * with standard deserializer we provide. */ public void testDeserFromNumber() throws IOException { Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // use some arbitrary but non-default time point (after 1.1.1970) cal.set(Calendar.YEAR, 1972); long timepoint = cal.getTime().getTime(); // Ok, first: using JSON number (milliseconds since epoch) DateTime dt = MAPPER.readValue(String.valueOf(timepoint), DateTime.class); assertEquals(timepoint, dt.getMillis()); // And then ISO-8601 String dt = MAPPER.readValue(quote("1972-12-28T12:00:01.000+0000"), DateTime.class); assertEquals("1972-12-28T12:00:01.000Z", dt.toString()); } public void testDeserReadableDateTime() throws IOException { ReadableDateTime date = MAPPER.readValue(quote("1972-12-28T12:00:01.000+0000"), ReadableDateTime.class); assertNotNull(date); assertEquals("1972-12-28T12:00:01.000Z", date.toString()); assertNull(MAPPER.readValue(quote(""), ReadableDateTime.class)); } // [datatype-joda#8] public void testDeserReadableDateTimeWithTimeZoneInfo() throws IOException { TimeZone timeZone = TimeZone.getTimeZone("GMT-6"); DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timeZone); MAPPER.setTimeZone(timeZone); ReadableDateTime date = MAPPER.readValue(quote("1972-12-28T12:00:01.000-0600"), ReadableDateTime.class); assertNotNull(date); assertEquals("1972-12-28T12:00:01.000-06:00", date.toString()); assertEquals(dateTimeZone, date.getZone()); // default behavior is to ignore the timezone in serialized data ReadableDateTime otherTzDate = MAPPER.readValue(quote("1972-12-28T12:00:01.000-0700"), ReadableDateTime.class); assertEquals(dateTimeZone, otherTzDate.getZone()); assertNull(MAPPER.readValue(quote(""), ReadableDateTime.class)); } public void testDeserReadableDateTimeWithTimeZoneFromData() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); mapper.setTimeZone(TimeZone.getTimeZone("GMT-6")); ReadableDateTime date = mapper.readValue(quote("2014-01-20T08:59:01.000-0500"), ReadableDateTime.class); assertEquals(DateTimeZone.forOffsetHours(-5), date.getZone()); } public void testDeserReadableDateTimeWithContextTZOverride() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); mapper.setTimeZone(TimeZone.getTimeZone("UTC")); ReadableDateTimeWithContextTZOverride date = mapper.readValue("{ \"time\" : \"2016-06-20T08:59:00.000+0300\"}", ReadableDateTimeWithContextTZOverride.class); DateTime expected = new DateTime(2016, 6, 20, 5, 59, DateTimeZone.forID("UTC")); assertEquals(expected, date.time); } public void testDeserReadableDateTimeWithoutContextTZOverride() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.enable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); mapper.setTimeZone(TimeZone.getTimeZone("UTC")); ReadableDateTimeWithoutContextTZOverride date = mapper.readValue("{ \"time\" : \"2016-06-20T08:59:00.000+0300\"}", ReadableDateTimeWithoutContextTZOverride.class); DateTime expected = new DateTime(2016, 6, 20, 8, 59, DateTimeZone.forOffsetHours(3)); assertEquals(expected, date.time); } public void test_enable_ADJUST_DATES_TO_CONTEXT_TIME_ZONE() throws Exception { ObjectMapper mapper = jodaMapper(); mapper.enable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); DateTime result = mapper.readValue("{\"jodaDateTime\":\"2017-01-01 01:01:01[Asia/Shanghai]\"}", Issue93Bean.class).getJodaDateTime(); assertEquals(new DateTime(2016, 12, 31, 17, 1, 1, DateTimeZone.UTC), result); } public void test_disable_ADJUST_DATES_TO_CONTEXT_TIME_ZONE() throws Exception { ObjectMapper mapper = jodaMapper(); mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); DateTime result = mapper.readValue("{\"jodaDateTime\":\"2017-01-01 01:01:01[Asia/Shanghai]\"}", Issue93Bean.class).getJodaDateTime(); DateTimeZone expTZ = DateTimeZone.forID("Asia/Shanghai"); assertEquals(new DateTime(2017, 1, 1, 1, 1, 1, expTZ), result); } } DateTimeZoneDeserTest.java000066400000000000000000000032561323201316200415460ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.util.TimeZone; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; import com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserTest.DateTimeZoneWrapper; public class DateTimeZoneDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Test methods /********************************************************** */ // [datatype-joda#82] public void testSimpleDateTimeZone() throws Exception { TimeZone timeZone = TimeZone.getTimeZone("GMT-6"); DateTimeZone input = DateTimeZone.forTimeZone(timeZone); String json = MAPPER.writeValueAsString(input); assertEquals(quote("-06:00"), json); DateTimeZone result = MAPPER.readValue(json, DateTimeZone.class); assertEquals(result, input); // But then verify polymorphic handling DateTimeZoneWrapper input2 = new DateTimeZoneWrapper(input); json = MAPPER.writeValueAsString(input2); if (json.indexOf("DateTimeZone") < 0) { fail("Should contain type information, json = "+json); } DateTimeZoneWrapper result2 = MAPPER.readValue(json, DateTimeZoneWrapper.class); assertNotNull(result2.tz); assertEquals(input, result2.tz); } } DurationDeserializationTest.java000066400000000000000000000071721323201316200430700ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.Map; import org.joda.time.Duration; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class DurationDeserializationTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) private static interface ObjectConfiguration { } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); public void testDurationDeserFromInt() throws IOException { Duration d = MAPPER.readValue("1234", Duration.class); assertEquals(1234, d.getMillis()); } public void testDurationDeserFromString() throws IOException { Duration d = MAPPER.readValue(quote("PT1.234S"), Duration.class); assertEquals(1234, d.getMillis()); } public void testDurationRoundtrip() throws IOException { Duration d = new Duration(5513); assertEquals(d, MAPPER.readValue(MAPPER.writeValueAsString(d), Duration.class)); } public void testDurationFailsDeserializingUnexpectedType() throws IOException { try { MAPPER.readValue("{\"foo\":1234}", Duration.class); fail(); } catch (JsonMappingException e) { // there's location info involving a string object id on the second line, so just use the first line assertEquals("expected JSON Number or String", e.getMessage().split("\n")[0]); } } public void testDurationDeserFromIntWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(Duration.class, ObjectConfiguration.class); Duration d = mapper.readValue("[\"org.joda.time.Duration\",1234]", Duration.class); assertEquals(1234, d.getMillis()); } /* /********************************************************** /* Test methods, key deserialization /********************************************************** */ public void testDurationKeyDeserialize() throws IOException { final String json = "{" + quote("PT60s") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(Duration.standardMinutes(1L))); } /* /********************************************************** /* Test methods, alternate representations /********************************************************** */ // [datatype-joda#90]: Possibly support wider set of representations public void testDurationAltFromString() throws IOException { Duration d = MAPPER.readValue(quote("PT1H"), Duration.class); assertEquals(60, d.getStandardMinutes()); d = MAPPER.readValue(quote("PT4H30M"), Duration.class); assertEquals(4 * 60 + 30, d.getStandardMinutes()); } public void testDurationAltKeyDeserialize() throws IOException { final String json = "{" + quote("PT4H30M") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(Duration.standardMinutes(4 * 60 + 30))); } } InstantDeserTest.java000066400000000000000000000045711323201316200406370ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.joda.time.DateTime; import org.joda.time.Instant; import org.joda.time.ReadableInstant; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class InstantDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) private static interface ObjectConfiguration { } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); public void testDeserReadableInstant() throws IOException { ReadableInstant date = MAPPER.readValue(quote("1972-12-28T12:00:01.000+0000"), ReadableInstant.class); assertNotNull(date); assertEquals("1972-12-28T12:00:01.000Z", date.toString()); assertNull(MAPPER.readValue(quote(""), ReadableInstant.class)); } public void testDeserDateTimeWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(DateTime.class, ObjectConfiguration.class); DateTime date = mapper.readValue("[\"org.joda.time.DateTime\",\"1972-12-28T12:00:01.000+0000\"]", DateTime.class); assertNotNull(date); assertEquals("1972-12-28T12:00:01.000Z", date.toString()); } public void testDeserInstantFromNumber() throws IOException { Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); cal.set(Calendar.YEAR, 1972); long timepoint = cal.getTime().getTime(); // Ok, first: using JSON number (milliseconds since epoch) Instant instant = MAPPER.readValue(String.valueOf(timepoint), Instant.class); assertEquals(timepoint, instant.getMillis()); } public void testDeserInstant() throws IOException { Instant date = MAPPER.readValue(quote("1972-12-28T12:00:01.000Z"), Instant.class); assertNotNull(date); assertEquals("1972-12-28T12:00:01.000Z", date.toString()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), Instant.class)); } } IntervalDeserTest.java000066400000000000000000000054611323201316200410020ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.TimeZone; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.chrono.ISOChronology; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class IntervalDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Test methods /********************************************************** */ /* /********************************************************** /* Tests for Interval type /********************************************************** */ public void testIntervalDeser() throws IOException { Interval interval = MAPPER.readValue(quote("1396439982-1396440001"), Interval.class); assertEquals(1396439982, interval.getStartMillis()); assertEquals(1396440001, interval.getEndMillis()); interval = MAPPER.readValue(quote("-100-1396440001"), Interval.class); assertEquals(-100, interval.getStartMillis()); assertEquals(1396440001, interval.getEndMillis()); assertEquals(ISOChronology.getInstance(DateTimeZone.UTC), interval.getChronology()); } public void testIntervalDeserWithTimeZone() throws IOException { MAPPER.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); Interval interval = MAPPER.readValue(quote("1396439982-1396440001"), Interval.class); assertEquals(1396439982, interval.getStartMillis()); assertEquals(1396440001, interval.getEndMillis()); assertEquals(ISOChronology.getInstance(DateTimeZone.forID("Europe/Paris")), interval.getChronology()); MAPPER.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); interval = MAPPER.readValue(quote("-100-1396440001"), Interval.class); assertEquals(-100, interval.getStartMillis()); assertEquals(1396440001, interval.getEndMillis()); assertEquals(ISOChronology.getInstance(DateTimeZone.forID("America/Los_Angeles")), interval.getChronology()); } public void testIntervalDeserWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(Interval.class, ObjectConfiguration.class); Interval interval= mapper.readValue("[\"org.joda.time.Interval\",\"1396439982-1396440001\"]", Interval.class); assertEquals(1396439982, interval.getStartMillis()); assertEquals(1396440001, interval.getEndMillis()); } } KeyDeserTest.java000066400000000000000000000044121323201316200377410ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class KeyDeserTest extends JodaTestBase { /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Tests for key deserializers /********************************************************** */ public void testDateTimeKeyDeserialize() throws IOException { final String json = "{" + quote("1970-01-01T00:00:00.000Z") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(DateTime.parse("1970-01-01T00:00:00.000Z"))); } public void testLocalDateKeyDeserialize() throws IOException { final String json = "{" + quote("2014-05-23") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(LocalDate.parse("2014-05-23"))); } public void testLocalTimeKeyDeserialize() throws IOException { final String json = "{" + quote("00:00:00.000") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(LocalTime.parse("00:00:00.000"))); } public void testLocalDateTimeKeyDeserialize() throws IOException { final String json = "{" + quote("2014-05-23T00:00:00.000") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(LocalDateTime.parse("2014-05-23T00:00:00.000"))); } } LocalDateDeserTest.java000066400000000000000000000105021323201316200410360ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.TimeZone; import org.joda.time.LocalDate; import org.joda.time.chrono.ISOChronology; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class LocalDateDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) private static interface ObjectConfiguration { } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Tests for LocalDate type /********************************************************** */ public void testLocalDateDeser() throws IOException { // couple of acceptable formats, so: LocalDate date = MAPPER.readValue("[2001,5,25]", LocalDate.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); LocalDate date2 = MAPPER.readValue(quote("2005-07-13"), LocalDate.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), LocalDate.class)); } public void testLocalDateDeserWithTimeZone() throws IOException { final String trickyInstant = "1238558582001"; // MAPPER is using default TimeZone (GMT) LocalDate date3 = MAPPER.readValue(trickyInstant, LocalDate.class); assertEquals(2009, date3.getYear()); assertEquals(4, date3.getMonthOfYear()); assertEquals(1, date3.getDayOfMonth()); assertEquals(ISOChronology.getInstanceUTC(), date3.getChronology()); MAPPER.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); // couple of acceptable formats, so: LocalDate date = MAPPER.readValue("[2001,5,25]", LocalDate.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); assertEquals(ISOChronology.getInstanceUTC(), date.getChronology()); MAPPER.setTimeZone(TimeZone.getTimeZone("Asia/Taipei")); LocalDate date2 = MAPPER .readValue(quote("2005-07-13"), LocalDate.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); assertEquals(ISOChronology.getInstanceUTC(), date.getChronology()); assertNull(MAPPER.readValue(quote(""), LocalDate.class)); MAPPER.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); LocalDate date4 = MAPPER.readValue(trickyInstant, LocalDate.class); assertEquals(2009, date4.getYear()); assertEquals(3, date4.getMonthOfYear()); assertEquals(31, date4.getDayOfMonth()); assertEquals(ISOChronology.getInstanceUTC(), date4.getChronology()); } public void testLocalDateDeserWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(LocalDate.class, ObjectConfiguration.class); // couple of acceptable formats, so: LocalDate date = mapper.readValue("[\"org.joda.time.LocalDate\",[2001,5,25]]", LocalDate.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); LocalDate date2 = mapper.readValue("[\"org.joda.time.LocalDate\",\"2005-07-13\"]", LocalDate.class); assertEquals(2005, date2.getYear()); assertEquals(7, date2.getMonthOfYear()); assertEquals(13, date2.getDayOfMonth()); } public void testLocalDateDeserWithPartsAsString() throws IOException { // couple of acceptable formats, so: LocalDate date = MAPPER.readValue("[\"2001\",\"5\",\"25\"]", LocalDate.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); } } LocalDateTimeDeserTest.java000066400000000000000000000120401323201316200416540ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.TimeZone; import org.joda.time.LocalDateTime; import org.joda.time.chrono.ISOChronology; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class LocalDateTimeDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Test methods /********************************************************** */ public void testLocalDateTimeDeser() throws IOException { // couple of acceptable formats again: LocalDateTime date = MAPPER.readValue("[2001,5,25,10,15,30,37]", LocalDateTime.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); assertEquals(10, date.getHourOfDay()); assertEquals(15, date.getMinuteOfHour()); assertEquals(30, date.getSecondOfMinute()); assertEquals(37, date.getMillisOfSecond()); LocalDateTime date2 = MAPPER.readValue(quote("2007-06-30T08:34:09.001"), LocalDateTime.class); assertEquals(2007, date2.getYear()); assertEquals(6, date2.getMonthOfYear()); assertEquals(30, date2.getDayOfMonth()); assertEquals(8, date2.getHourOfDay()); assertEquals(34, date2.getMinuteOfHour()); assertEquals(9, date2.getSecondOfMinute()); assertEquals(1, date2.getMillisOfSecond()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), LocalDateTime.class)); // MAPPER is using default TimeZone (GMT) LocalDateTime date3 = MAPPER.readValue("1238558582001", LocalDateTime.class); assertEquals(2009, date3.getYear()); assertEquals(4, date3.getMonthOfYear()); assertEquals(1, date3.getDayOfMonth()); assertEquals(4, date3.getHourOfDay()); assertEquals(3, date3.getMinuteOfHour()); assertEquals(2, date3.getSecondOfMinute()); assertEquals(1, date3.getMillisOfSecond()); assertEquals(ISOChronology.getInstanceUTC(), date3.getChronology()); } public void testLocalDateTimeDeserWithTimeZone() throws IOException { MAPPER.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); // couple of acceptable formats again: LocalDateTime date = MAPPER.readValue("[2001,5,25,10,15,30,37]", LocalDateTime.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); assertEquals(10, date.getHourOfDay()); assertEquals(15, date.getMinuteOfHour()); assertEquals(30, date.getSecondOfMinute()); assertEquals(37, date.getMillisOfSecond()); assertEquals(ISOChronology.getInstanceUTC(), date.getChronology()); MAPPER.setTimeZone(TimeZone.getTimeZone("Asia/Taipei")); LocalDateTime date2 = MAPPER.readValue(quote("2007-06-30T08:34:09.001"), LocalDateTime.class); assertEquals(2007, date2.getYear()); assertEquals(6, date2.getMonthOfYear()); assertEquals(30, date2.getDayOfMonth()); assertEquals(8, date2.getHourOfDay()); assertEquals(34, date2.getMinuteOfHour()); assertEquals(9, date2.getSecondOfMinute()); assertEquals(1, date2.getMillisOfSecond()); assertEquals(ISOChronology.getInstanceUTC(), date.getChronology()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), LocalDateTime.class)); } public void testLocalDateTimeDeserWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(LocalDateTime.class, ObjectConfiguration.class); // couple of acceptable formats again: LocalDateTime date = mapper.readValue("[\"org.joda.time.LocalDateTime\",[2001,5,25,10,15,30,37]]", LocalDateTime.class); assertEquals(2001, date.getYear()); assertEquals(5, date.getMonthOfYear()); assertEquals(25, date.getDayOfMonth()); assertEquals(10, date.getHourOfDay()); assertEquals(15, date.getMinuteOfHour()); assertEquals(30, date.getSecondOfMinute()); assertEquals(37, date.getMillisOfSecond()); LocalDateTime date2 = mapper.readValue("[\"org.joda.time.LocalDateTime\",\"2007-06-30T08:34:09.001\"]", LocalDateTime.class); assertEquals(2007, date2.getYear()); assertEquals(6, date2.getMonthOfYear()); assertEquals(30, date2.getDayOfMonth()); assertEquals(8, date2.getHourOfDay()); assertEquals(34, date2.getMinuteOfHour()); assertEquals(9, date2.getSecondOfMinute()); assertEquals(1, date2.getMillisOfSecond()); } } LocalTimeDeserTest.java000066400000000000000000000047271323201316200410730ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import org.joda.time.LocalTime; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class LocalTimeDeserTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) private static interface ObjectConfiguration { } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Tests for LocalTime type /********************************************************** */ public void testLocalTimeDeser() throws IOException { // couple of acceptable formats, so: LocalTime time = MAPPER.readValue("[23,59,1,222]", LocalTime.class); assertEquals(23, time.getHourOfDay()); assertEquals(59, time.getMinuteOfHour()); assertEquals(1, time.getSecondOfMinute()); assertEquals(222, time.getMillisOfSecond()); LocalTime time2 = MAPPER.readValue(quote("13:45:22"), LocalTime.class); assertEquals(13, time2.getHourOfDay()); assertEquals(45, time2.getMinuteOfHour()); assertEquals(22, time2.getSecondOfMinute()); assertEquals(0, time2.getMillisOfSecond()); // since 1.6.1, for [JACKSON-360] assertNull(MAPPER.readValue(quote(""), LocalTime.class)); } public void testLocalTimeDeserWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(LocalTime.class, ObjectConfiguration.class); // couple of acceptable formats, so: LocalTime time = mapper.readValue("[\"org.joda.time.LocalTime\",[23,59,1,10]]", LocalTime.class); assertEquals(23, time.getHourOfDay()); assertEquals(59, time.getMinuteOfHour()); assertEquals(1, time.getSecondOfMinute()); assertEquals(10, time.getMillisOfSecond()); LocalTime time2 = mapper.readValue("[\"org.joda.time.LocalTime\",\"13:45:22\"]", LocalTime.class); assertEquals(13, time2.getHourOfDay()); assertEquals(45, time2.getMinuteOfHour()); assertEquals(22, time2.getSecondOfMinute()); assertEquals(0, time2.getMillisOfSecond()); } } MonthDayDeserTest.java000066400000000000000000000035001323201316200407310ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.TimeZone; import org.joda.time.MonthDay; import org.joda.time.chrono.ISOChronology; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class MonthDayDeserTest extends JodaTestBase { /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); public void testDeserMonthDay() throws Exception { String monthDayString = new MonthDay(7, 23).toString(); MonthDay monthDay = MAPPER.readValue(quote(monthDayString), MonthDay.class); assertEquals(new MonthDay(7, 23), monthDay); } public void testDeserMonthDayWithTimeZone() throws Exception { MAPPER.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); String monthDayString = new MonthDay(7, 23).toString(); MonthDay monthDay = MAPPER.readValue(quote(monthDayString), MonthDay.class); assertEquals(new MonthDay(7, 23), monthDay); assertEquals(ISOChronology.getInstanceUTC(), monthDay.getChronology()); } public void testDeserMonthDayFromEmptyString() throws Exception { MonthDay monthDay = MAPPER.readValue(quote(""), MonthDay.class); assertNull(monthDay); } public void testDeserMonthDayFailsForUnexpectedType() throws IOException { try { MAPPER.readValue("{\"month\":8}", MonthDay.class); fail(); } catch (JsonMappingException e) { assertTrue(e.getMessage().contains("expected JSON String")); } } } PeriodDeserializationTest.java000066400000000000000000000055501323201316200425230ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.Map; import org.joda.time.Period; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class PeriodDeserializationTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } private final ObjectMapper MAPPER = jodaMapper(); /* /********************************************************** /* Tests for Period type values /********************************************************** */ public void testPeriodDeser() throws IOException { Period out = MAPPER.readValue(quote("PT1H2M3.004S"), Period.class); assertEquals(1, out.getHours()); assertEquals(2, out.getMinutes()); assertEquals(3, out.getSeconds()); assertEquals(4, out.getMillis()); // also, should work as number: String json = String.valueOf(1000 * out.toStandardSeconds().getSeconds()); out = MAPPER.readValue(json, Period.class); assertEquals(1, out.getHours()); assertEquals(2, out.getMinutes()); assertEquals(3, out.getSeconds()); // but millis are actually truncated... assertEquals(0, out.getMillis()); } public void testPeriodDeserWithTypeInfo() throws IOException { ObjectMapper mapper = jodaMapper(); mapper.addMixIn(Period.class, ObjectConfiguration.class); Period out = mapper.readValue("[\"org.joda.time.Period\",\"PT1H2M3.004S\"]", Period.class); assertEquals(1, out.getHours()); assertEquals(2, out.getMinutes()); assertEquals(3, out.getSeconds()); assertEquals(4, out.getMillis()); // also, should work as number: String json = "[\"org.joda.time.Period\"," + String.valueOf(1000 * out.toStandardSeconds().getSeconds()) + "]"; out = mapper.readValue(json, Period.class); assertEquals(1, out.getHours()); assertEquals(2, out.getMinutes()); assertEquals(3, out.getSeconds()); // but millis are actually truncated... assertEquals(0, out.getMillis()); } /* /********************************************************** /* Tests for Period type keys /********************************************************** */ public void testPeriodKeyDeserialize() throws IOException { final String json = "{" + quote("PT1H2M3.004S") + ":0}"; final Map map = MAPPER.readValue(json, new TypeReference>() { }); assertNotNull(map); assertTrue(map.containsKey(new Period(1, 2, 3, 4))); } } ReadablePeriodDeserializerTest.java000066400000000000000000000057171323201316200434440ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; import org.joda.time.Days; import org.joda.time.Hours; import org.joda.time.Minutes; import org.joda.time.Months; import org.joda.time.ReadablePeriod; import org.joda.time.Seconds; import org.joda.time.Weeks; import org.joda.time.Years; public class ReadablePeriodDeserializerTest extends JodaTestBase { public void testDeserializeSeconds() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"seconds\"},\"seconds\":12,\"periodType\":{\"name\":\"Seconds\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Seconds.seconds( 12 ), readablePeriod ); } public void testDeserializeMinutes() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"minutes\"},\"minutes\":1,\"periodType\":{\"name\":\"Minutes\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Minutes.minutes( 1 ), readablePeriod ); } public void testDeserializeHours() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"hours\"},\"hours\":2,\"periodType\":{\"name\":\"Hours\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Hours.hours( 2 ), readablePeriod ); } public void testDeserializeDays() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"days\"},\"days\":2,\"periodType\":{\"name\":\"Days\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Days.days( 2 ), readablePeriod ); } public void testDeserializeWeeks() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"weeks\"},\"weeks\":2,\"periodType\":{\"name\":\"Weeks\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Weeks.weeks( 2 ), readablePeriod ); } public void testDeserializeMonths() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"months\"},\"months\":2,\"periodType\":{\"name\":\"Months\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Months.months( 2 ), readablePeriod ); } public void testDeserializeYears() throws Exception { ObjectMapper objectMapper = jodaMapper(); ReadablePeriod readablePeriod = objectMapper.readValue( "{\"fieldType\":{\"name\":\"years\"},\"years\":2,\"periodType\":{\"name\":\"Years\"}}", ReadablePeriod.class ); assertNotNull( readablePeriod ); assertEquals( Years.years( 2 ), readablePeriod ); } }YearMonthDeserTest.java000066400000000000000000000035101323201316200411150ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/deserpackage com.fasterxml.jackson.datatype.joda.deser; import java.io.IOException; import java.util.TimeZone; import org.joda.time.YearMonth; import org.joda.time.chrono.ISOChronology; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class YearMonthDeserTest extends JodaTestBase { /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = jodaMapper(); public void testDeserYearMonth() throws Exception { String yearMonthString = new YearMonth(2013, 8).toString(); YearMonth yearMonth = MAPPER.readValue(quote(yearMonthString), YearMonth.class); assertEquals(new YearMonth(2013, 8), yearMonth); } public void testDeserYearMonthWithTimeZone() throws Exception { MAPPER.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); String yearMonthString = new YearMonth(2013, 8).toString(); YearMonth yearMonth = MAPPER.readValue(quote(yearMonthString), YearMonth.class); assertEquals(new YearMonth(2013, 8), yearMonth); assertEquals(ISOChronology.getInstanceUTC(), yearMonth.getChronology()); } public void testDeserYearMonthFromEmptyString() throws Exception { YearMonth yearMonth = MAPPER.readValue(quote(""), YearMonth.class); assertNull(yearMonth); } public void testDeserYearMonthFailsForUnexpectedType() throws IOException { try { MAPPER.readValue("{\"year\":2013}", YearMonth.class); fail(); } catch (JsonMappingException e) { verifyException(e, "expected JSON String"); } } } ser/000077500000000000000000000000001323201316200342115ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/jodaJodaSerializationTest.java000066400000000000000000000251551323201316200413370ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import java.io.IOException; import java.text.SimpleDateFormat; import com.fasterxml.jackson.annotation.JsonInclude; import org.joda.time.*; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class JodaSerializationTest extends JodaTestBase { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY, property = "@class") private static interface ObjectConfiguration { } static class Container { T contents; public Container(T contents) { this.contents = contents; } public T getContents() { return contents; } } private final ObjectMapper MAPPER = jodaMapper(); { MAPPER.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); MAPPER.enable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS); } private final ObjectWriter WRITER = MAPPER.writer(); /* /********************************************************** /* Tests for DateMidnight type /********************************************************** */ @SuppressWarnings("deprecation") // since Jackson 2.7 / Joda 2.4 public void testDateMidnightSer() throws IOException { DateMidnight date = new DateMidnight(2001, 5, 25); // default format is that of JSON array... assertEquals("[2001,5,25]", WRITER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) assertEquals(quote("2001-05-25"), WRITER.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(date)); date = new DateMidnight(2001, 5, 25); // default format is that of JSON array... assertEquals("[2001,5,25]", WRITER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) ObjectMapper mapper = jodaMapper(); mapper.addMixIn(DateMidnight.class, ObjectConfiguration.class); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); assertEquals("[\"org.joda.time.DateMidnight\",\"2001-05-25\"]", mapper.writeValueAsString(date)); } /* /********************************************************** /* Tests for LocalDate type /********************************************************** */ public void testLocalDateSer() throws IOException { LocalDate date = new LocalDate(2001, 5, 25); // default format is that of JSON array... assertEquals("[2001,5,25]", MAPPER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) assertEquals(quote("2001-05-25"), WRITER.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).writeValueAsString(date)); // We can also configure beans to not include empty values. In this case, // JodaDateSerializerBase#isEmpty is called to check if the value is empty. ObjectMapper mapper = jodaMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); assertEquals("{\"contents\":[2001,5,25]}", mapper.writeValueAsString(new Container(date))); // also verify pruning by NON_EMPTY assertEquals("{}", mapper.writeValueAsString(new Container(null))); } public void testLocalDateSerWithTypeInfo() throws IOException { LocalDate date = new LocalDate(2001, 5, 25); // default format is that of JSON array... assertEquals("[2001,5,25]", MAPPER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) ObjectMapper mapper = jodaMapper(); mapper.addMixIn(LocalDate.class, ObjectConfiguration.class); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); assertEquals("[\"org.joda.time.LocalDate\",\"2001-05-25\"]", mapper.writeValueAsString(date)); } /* /********************************************************** /* Tests for LocalTime type /********************************************************** */ public void testLocalTimeSer() throws IOException { LocalTime date = new LocalTime(13,20,54); // default format is that of JSON array... assertEquals("[13,20,54,0]", MAPPER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) ObjectMapper mapper = jodaMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); assertEquals(quote("13:20:54.000"), mapper.writeValueAsString(date)); } public void testLocalTimeSerWithTypeInfo() throws IOException { LocalTime date = new LocalTime(13,20,54); // default format is that of JSON array... assertEquals("[13,20,54,0]", MAPPER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) ObjectMapper mapper = jodaMapper(); mapper.addMixIn(LocalTime.class, ObjectConfiguration.class); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); assertEquals("[\"org.joda.time.LocalTime\",\"13:20:54.000\"]", mapper.writeValueAsString(date)); } /* /********************************************************** /* Tests for LocalDateTime type /********************************************************** */ public void testLocalDateTimeSer() throws IOException { LocalDateTime date = new LocalDateTime(2001, 5, 25, 10, 15, 30, 37); // default format is that of JSON array... assertEquals("[2001,5,25,10,15,30,37]", MAPPER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) ObjectMapper mapper = jodaMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); assertEquals(quote("2001-05-25T10:15:30.037"), mapper.writeValueAsString(date)); } public void testLocalDateTimeSerWithTypeInfo() throws IOException { LocalDateTime date = new LocalDateTime(2001, 5, 25, 10, 15, 30, 37); // default format is that of JSON array... assertEquals("[2001,5,25,10,15,30,37]", MAPPER.writeValueAsString(date)); // but we can force it to be a String as well (note: here we assume this is // dynamically changeable) ObjectMapper mapper = jodaMapper(); mapper.addMixIn(LocalDateTime.class, ObjectConfiguration.class); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); assertEquals("[\"org.joda.time.LocalDateTime\",\"2001-05-25T10:15:30.037\"]", mapper.writeValueAsString(date)); } /* /********************************************************** /* Tests for Period type /********************************************************** */ public void testPeriodSer() throws IOException { Period in = new Period(1, 2, 3, 4); assertEquals(quote("PT1H2M3.004S"), MAPPER.writeValueAsString(in)); } public void testPeriodSerWithTypeInfo() throws IOException { Period in = new Period(1, 2, 3, 4); ObjectMapper mapper = jodaMapper(); mapper.addMixIn(Period.class, ObjectConfiguration.class); assertEquals("[\"org.joda.time.Period\",\"PT1H2M3.004S\"]", mapper.writeValueAsString(in)); } /* /********************************************************** /* Tests for Duration type /********************************************************** */ public void testDurationSer() throws IOException { Duration d = new Duration(3123422); String json = MAPPER.writeValueAsString(d); assertEquals("3123422", json); assertEquals(quote("PT3123.422S"), MAPPER.writer() .without(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) .writeValueAsString(d)); } public void testDurationSerWithTypeInfo() throws IOException { Duration d = new Duration(3123422); ObjectMapper mapper = jodaMapper(); mapper.enable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS); mapper.addMixIn(Duration.class, ObjectConfiguration.class); String json = mapper.writeValueAsString(d); assertEquals("[\"org.joda.time.Duration\",3123422]", json); } public void testInstantSer() throws IOException { Instant instant = new Instant(0L); // by default, dates use timestamp, so: assertEquals("0", MAPPER.writeValueAsString(instant)); // but if re-configured, as regular ISO-8601 string assertEquals(quote("1970-01-01T00:00:00.000Z"), MAPPER.writer() .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .writeValueAsString(instant)); } // [datatype-joda#60] public void testInstantConversion() throws Exception { final ObjectMapper mapper = jodaMapper(); // Configure Date Formatting mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")); // Create an instant and serialize and additionally serialize the instant as DateTime to demonstrate the difference org.joda.time.Instant now = new DateTime(1431498572205L).toInstant(); String instantString = mapper.writeValueAsString(now); assertEquals("\"2015-05-13T06:29:32.205Z\"", instantString); } public void testMonthDaySer() throws Exception { MonthDay monthDay = new MonthDay(7, 23); ObjectMapper mapper = jodaMapper(); String json = mapper.writeValueAsString(monthDay); assertEquals(quote("--07-23"), json); } public void testYearMonthSer() throws Exception { YearMonth yearMonth = new YearMonth(2013, 8); ObjectMapper mapper = jodaMapper(); String json = mapper.writeValueAsString(yearMonth); assertEquals(quote("2013-08"), json); } } WriteZoneIdTest.java000066400000000000000000000030031323201316200401130ustar00rootroot00000000000000jackson-datatype-joda-jackson-datatype-joda-2.9.4/src/test/java/com/fasterxml/jackson/datatype/joda/serpackage com.fasterxml.jackson.datatype.joda.ser; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaTestBase; public class WriteZoneIdTest extends JodaTestBase { static class DummyClassWithDate { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss Z", with = JsonFormat.Feature.WRITE_DATES_WITH_ZONE_ID) public DateTime date; DummyClassWithDate() { } public DummyClassWithDate(DateTime date) { this.date = date; } } public void testJacksonAnnotatedPOJOWithDateWithTimezoneToJson() throws Exception { ObjectMapper mapper = jodaMapper(); String ZONE_ID = "Asia/Krasnoyarsk"; DummyClassWithDate input = new DummyClassWithDate(new DateTime(2015, 11, 23, 22, 06, 39, DateTimeZone.forID(ZONE_ID))); // 30-Jun-2016, tatu: Exact time seems to vary a bit based on DST, so let's actually // just verify appending of timezone id itself: String json = mapper.writeValueAsString(input); if (!json.contains("\"23-11-2015")) { fail("Should contain time prefix, did not: "+json); } String match = String.format("[%s]", ZONE_ID); if (!json.contains(match)) { fail("Should contain zone id "+match+", does not: "+json); } } }