001package org.gbif.api.jackson;
002
003import org.gbif.dwc.terms.Term;
004import org.gbif.dwc.terms.TermFactory;
005
006import java.io.IOException;
007import java.util.HashMap;
008import java.util.List;
009import java.util.Map;
010import java.util.Map.Entry;
011
012import com.google.common.collect.Lists;
013import org.codehaus.jackson.JsonParser;
014import org.codehaus.jackson.JsonToken;
015import org.codehaus.jackson.map.DeserializationConfig.Feature;
016import org.codehaus.jackson.map.DeserializationContext;
017import org.codehaus.jackson.map.JsonDeserializer;
018
019/**
020 * Deserializes list of maps of terms values.
021 */
022public class TermMapListDeserializer extends JsonDeserializer<List<Map<Term, String>>> {
023
024  private final TermFactory termFactory = TermFactory.instance();
025
026  @Override
027  public List<Map<Term, String>> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
028    if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
029      JsonDeserializer<Object> deserializer =
030        ctxt.getDeserializerProvider().findTypedValueDeserializer(ctxt.getConfig(),
031                                                                  ctxt.constructType(List.class),null);
032      List<Map<String, String>> verbatimTerms = (List<Map<String, String>>) deserializer.deserialize(jp, ctxt);
033      List<Map<Term, String>> interpretedTerms = Lists.newArrayList();
034      for (Map<String, String> verbExtension : verbatimTerms) {
035        Map<Term, String> extension = new HashMap<Term, String>();
036        for (Entry<String, String> entry : verbExtension.entrySet()) {
037          Term term = termFactory.findTerm(entry.getKey());
038          if (term == null && ctxt.getConfig().isEnabled(Feature.FAIL_ON_UNKNOWN_PROPERTIES)) {
039            throw ctxt.mappingException("Term not found " + entry.getKey());
040          }
041          extension.put(term, entry.getValue());
042        }
043        interpretedTerms.add(extension);
044      }
045      return interpretedTerms;
046    }
047    throw ctxt.mappingException("Expected JSON String");
048  }
049}