001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.api.jackson;
015
016import org.gbif.api.util.IsoDateInterval;
017
018import java.io.IOException;
019import java.text.ParseException;
020
021import com.fasterxml.jackson.core.JsonGenerator;
022import com.fasterxml.jackson.core.JsonParser;
023import com.fasterxml.jackson.core.JsonToken;
024import com.fasterxml.jackson.databind.DeserializationContext;
025import com.fasterxml.jackson.databind.JsonDeserializer;
026import com.fasterxml.jackson.databind.JsonMappingException;
027import com.fasterxml.jackson.databind.JsonSerializer;
028import com.fasterxml.jackson.databind.SerializerProvider;
029
030/**
031 * Jackson {@link JsonSerializer} classes for {@link IsoDateInterval}s with specified formats.
032 */
033public class IsoDateIntervalSerde {
034
035  /**
036   * Jackson {@link JsonSerializer} for {@link IsoDateInterval}.
037   */
038  public static class IsoDateIntervalSerializer extends JsonSerializer<IsoDateInterval> {
039
040    @Override
041    public void serialize(IsoDateInterval value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
042      // Empty fields aren't included in the JSON.
043      if (value != null) {
044        jgen.writeString(value.toString());
045      }
046    }
047  }
048
049  /**
050   * Jackson {@link JsonDeserializer} for {@link IsoDateInterval}s formatted above, falling back to the Jackson way.
051   */
052  public static class IsoDateIntervalDeserializer extends JsonDeserializer<IsoDateInterval> {
053
054    @Override
055    public IsoDateInterval deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
056      if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
057        String text = jp.getText();
058
059        try {
060          return IsoDateInterval.fromString(text);
061        } catch (ParseException e) {
062          throw JsonMappingException.from(jp, "Unable to parse date interval string");
063        }
064
065      }
066      throw JsonMappingException.from(jp, "Expected String");
067    }
068  }
069}