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 java.io.IOException;
017import java.net.URI;
018import java.net.URISyntaxException;
019
020import org.apache.commons.lang3.StringUtils;
021
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;
027
028public class EmptyToNullUriDeserializer extends JsonDeserializer<URI> {
029
030  @Override
031  public URI deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
032    if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
033      if (StringUtils.isEmpty(jp.getText())) {
034        return null;
035      }
036
037      try {
038        return new URI(jp.getText());
039      } catch (URISyntaxException e) {
040        throw JsonMappingException.from(jp, "Invalid URI");
041      }
042    }
043    throw JsonMappingException.from(jp, "Expected String");
044  }
045}