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.vocabulary.BasisOfRecord;
017
018import java.io.IOException;
019
020import org.apache.commons.lang3.StringUtils;
021
022import com.fasterxml.jackson.core.JsonGenerator;
023import com.fasterxml.jackson.core.JsonParser;
024import com.fasterxml.jackson.core.JsonToken;
025import com.fasterxml.jackson.databind.DeserializationContext;
026import com.fasterxml.jackson.databind.JsonDeserializer;
027import com.fasterxml.jackson.databind.JsonMappingException;
028import com.fasterxml.jackson.databind.JsonSerializer;
029import com.fasterxml.jackson.databind.SerializerProvider;
030
031/**
032 * Serializer for BasisOfRecord. Handles deprecated elements in the enum.
033 */
034public class BasisOfRecordSerde {
035
036  /**
037   * Jackson {@link JsonSerializer} for {@link BasisOfRecord}.
038   */
039  public static class BasisOfRecordJsonSerializer extends JsonSerializer<BasisOfRecord> {
040
041    @Override
042    public void serialize(BasisOfRecord value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
043      if (value == null) {
044        jgen.writeNull();
045        return;
046      }
047      jgen.writeString(getValue(value).name());
048    }
049  }
050
051  /**
052   * Maps deprecated values into their default values.
053   */
054  private static BasisOfRecord getValue(BasisOfRecord basisOfRecord) {
055    return BasisOfRecord.LITERATURE == basisOfRecord || BasisOfRecord.UNKNOWN == basisOfRecord? BasisOfRecord.OCCURRENCE : basisOfRecord;
056  }
057
058  /**
059   * Jackson {@link JsonDeserializer} for {@link BasisOfRecord}.
060   */
061  public static class BasisOfRecordJsonDeserializer extends JsonDeserializer<BasisOfRecord> {
062    @Override
063    public BasisOfRecord deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
064      if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
065        if (StringUtils.isEmpty(jp.getText())) {
066          return null;
067        }
068        // first, try by url
069        BasisOfRecord basisOfRecord = BasisOfRecord.valueOf(jp.getText());
070
071        // then, try by name
072        return getValue(basisOfRecord);
073      }
074      throw JsonMappingException.from(jp, "Expected String");
075    }
076  }
077}