001/*
002 * Copyright 2020 Global Biodiversity Information Facility (GBIF)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.gbif.api.jackson;
017
018import java.io.IOException;
019import java.time.Instant;
020import java.time.ZoneOffset;
021import java.time.format.DateTimeFormatter;
022import java.util.Date;
023
024import com.fasterxml.jackson.core.JsonGenerator;
025import com.fasterxml.jackson.core.JsonParser;
026import com.fasterxml.jackson.core.JsonToken;
027import com.fasterxml.jackson.databind.DeserializationContext;
028import com.fasterxml.jackson.databind.JsonDeserializer;
029import com.fasterxml.jackson.databind.JsonMappingException;
030import com.fasterxml.jackson.databind.JsonSerializer;
031import com.fasterxml.jackson.databind.SerializerProvider;
032import com.fasterxml.jackson.databind.deser.std.DateDeserializers;
033
034/**
035 * Jackson {@link JsonSerializer} classes for {@link Date}s with specified formats.
036 */
037public class DateSerde {
038
039  // DateTimeFormatter is immutable and thread-safe, unlike SimpleDateFormat which must not be shared between threads.
040  private static final DateTimeFormatter NO_TIMEZONE_FORMAT =
041      DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC);
042
043  /**
044   * Jackson {@link JsonSerializer} for {@link Date}.
045   */
046  public static class NoTimezoneDateJsonSerializer extends JsonSerializer<Date> {
047
048    @Override
049    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
050      // Empty fields aren't included in the JSON.
051      if (value != null) {
052        // Instant.ofEpochMilli rather than Date.toInstant(), which java.sql.Date doesn't support.
053        jgen.writeString(NO_TIMEZONE_FORMAT.format(Instant.ofEpochMilli(value.getTime())));
054      }
055    }
056  }
057
058  /**
059   * Jackson {@link JsonDeserializer} for {@link Date}s formatted above, falling back to the Jackson way.
060   */
061  public static class FlexibleDateJsonDeserializer extends DateDeserializers.DateDeserializer {
062
063    @Override
064    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
065      if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
066        String text = jp.getText();
067        if (text.length() == 19) {
068          return Date.from(Instant.parse(text + "Z"));
069        } else {
070          return super.deserialize(jp, ctxt);
071        }
072      }
073      throw JsonMappingException.from(jp, "Expected String");
074    }
075  }
076}