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 org.gbif.dwc.terms.Term;
019import org.gbif.dwc.terms.TermFactory;
020
021import java.io.IOException;
022import java.util.ArrayList;
023import java.util.HashMap;
024import java.util.List;
025import java.util.Map;
026import java.util.Map.Entry;
027
028import com.fasterxml.jackson.core.JsonParser;
029import com.fasterxml.jackson.core.JsonToken;
030import com.fasterxml.jackson.core.ObjectCodec;
031import com.fasterxml.jackson.core.type.TypeReference;
032import com.fasterxml.jackson.databind.DeserializationContext;
033import com.fasterxml.jackson.databind.DeserializationFeature;
034import com.fasterxml.jackson.databind.JsonDeserializer;
035import com.fasterxml.jackson.databind.JsonMappingException;
036
037/**
038 * Deserializes list of maps of terms values.
039 */
040@Deprecated
041public class TermMapListDeserializer extends JsonDeserializer<List<Map<Term, String>>> {
042
043  private final TermFactory termFactory = TermFactory.instance();
044
045  @Override
046  public List<Map<Term, String>> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
047    ObjectCodec objectCodec = ctxt.getParser().getCodec();
048    if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
049      List<Map<String, String>> verbatimTerms = objectCodec.readValue(jp, new TypeReference<List<Map<String, String>>>() {
050      });
051      List<Map<Term, String>> interpretedTerms = new ArrayList<>();
052      for (Map<String, String> verbExtension : verbatimTerms) {
053        Map<Term, String> extension = new HashMap<>();
054        for (Entry<String, String> entry : verbExtension.entrySet()) {
055          Term term = termFactory.findTerm(entry.getKey());
056          if (term == null && ctxt.getConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
057            throw JsonMappingException.from(jp, "Term not found " + entry.getKey());
058          }
059          extension.put(term, entry.getValue());
060        }
061        interpretedTerms.add(extension);
062      }
063      return interpretedTerms;
064    }
065    throw JsonMappingException.from(jp, "Expected JSON String");
066  }
067}