Java Code Examples for com.fasterxml.jackson.databind.JsonMappingException#from()

The following examples show how to use com.fasterxml.jackson.databind.JsonMappingException#from() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UriDeserializer.java    From Partner-Center-Java with MIT License 6 votes vote down vote up
@Override
public URI deserialize(JsonParser parser, DeserializationContext context)
		throws IOException, JsonProcessingException
{
	JsonToken currentToken = parser.getCurrentToken();
	if (currentToken.equals(JsonToken.VALUE_STRING))
	{
		String linkUri = parser.getText().trim();

        try
        {
			return new URI (linkUri);
		}
        catch (URISyntaxException e)
        {
			PartnerLog.getInstance().logError(e.toString());
		}
	}
	else if(currentToken.equals(JsonToken.VALUE_NULL))
	{
		return null;
	}
	
	context.handleUnexpectedToken(URI.class, parser); 
	throw JsonMappingException.from(parser, null);
}
 
Example 2
Source File: RefStdDeserializer.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
@Override
public Ref<?> deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException {
    if ( valueType == null ) {
        throw JsonMappingException.from( ctxt, "valueType can't be null." );
    }

    JsonNode jsonNode = jp.readValueAsTree();

    JsonParser keyJsonParser = jsonNode.get( RefConstant.KEY ).traverse();
    keyJsonParser.setCodec( jp.getCodec() );
    Key key = keyJsonParser.readValueAs( Key.class );

    Object value = null;
    if ( jsonNode.has( RefConstant.VALUE ) ) {
        JsonParser valueJsonParser = jsonNode.get( RefConstant.VALUE ).traverse();
        valueJsonParser.setCodec( jp.getCodec() );
        value = valueJsonParser.readValueAs( valueType.getRawClass() );
    }

    return value != null ? new DeadRef( key, value ) : new DeadRef( key );
}
 
Example 3
Source File: ClassUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
public static <T> T throwAsMappingException(DeserializationContext ctxt,
        IOException e0) throws JsonMappingException {
    if (e0 instanceof JsonMappingException) {
        throw (JsonMappingException) e0;
    }
    JsonMappingException e = JsonMappingException.from(ctxt, e0.getMessage());
    e.initCause(e0);
    throw e;
}
 
Example 4
Source File: DnDeserializer.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
@Override
public DistinguishedName deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
  if (p.getCurrentToken() == JsonToken.START_OBJECT) {

    DnBuilder dnBuilder = dn();
    for (JsonToken t = p.nextToken(); t != JsonToken.END_OBJECT; t = p.nextToken()) {
      if (t != JsonToken.FIELD_NAME)
        throw JsonMappingException.from(p, "Expecting " + JsonToken.FIELD_NAME);

      final String fieldName = p.getCurrentName();

      switch (fieldName) {
      case "cn":
        dnBuilder = dnBuilder.setCn(p.nextTextValue());
        break;
      case "ou":
        dnBuilder = dnBuilder.setOu(p.nextTextValue());
        break;
      case "c":
        dnBuilder = dnBuilder.setC(p.nextTextValue());
        break;
      case "l":
        dnBuilder = dnBuilder.setL(p.nextTextValue());
        break;
      case "o":
        dnBuilder = dnBuilder.setO(p.nextTextValue());
        break;
      case "st":
        dnBuilder = dnBuilder.setSt(p.nextTextValue());
        break;
      default:
        p.nextToken();
      }

    }
    return dnBuilder.build();
  } else
    return dn(p.getValueAsString());
}
 
Example 5
Source File: KubernetesDeserializer.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static KubernetesResource fromObjectNode(JsonParser jp, JsonNode node) throws IOException {
    String key = getKey(node);
    if (key != null) {
        Class<? extends KubernetesResource> resourceType = mapping.getForKey(key);
        if (resourceType == null) {
            throw JsonMappingException.from(jp,"No resource type found for:" + key);
        } else if (KubernetesResource.class.isAssignableFrom(resourceType)){
            return jp.getCodec().treeToValue(node, resourceType);
        }
    }
    return null;
}
 
Example 6
Source File: RefStdDeserializer.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException {
    if ( ctxt.getContextualType() == null || ctxt.getContextualType().containedType( 0 ) == null ) {
        throw JsonMappingException.from( ctxt, "Cannot deserialize Ref<T>. Cannot find the Generic Type T." );
    }
    return new RefStdDeserializer( ctxt.getContextualType().containedType( 0 ) );
}
 
Example 7
Source File: RefStdKeyDeserializer.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
@Override
public KeyDeserializer createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException {
    if ( ctxt.getContextualType() == null || ctxt.getContextualType().containedType( 0 ) == null || ctxt.getContextualType().containedType( 0 ).containedType( 0 ) == null ) {
        throw JsonMappingException.from( ctxt, "Cannot deserialize Ref<T>. Cannot find the Generic Type T." );
    }
    return new RefStdKeyDeserializer( ctxt.getContextualType().containedType( 0 ).containedType( 0 ) );
}
 
Example 8
Source File: Log4jStackTraceElementDeserializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
    JsonToken t = jp.getCurrentToken();
    // Must get an Object
    if (t == JsonToken.START_OBJECT) {
        String className = null, methodName = null, fileName = null;
        int lineNumber = -1;

        while ((t = jp.nextValue()) != JsonToken.END_OBJECT) {
            final String propName = jp.getCurrentName();
            if ("class".equals(propName)) {
                className = jp.getText();
            } else if ("file".equals(propName)) {
                fileName = jp.getText();
            } else if ("line".equals(propName)) {
                if (t.isNumeric()) {
                    lineNumber = jp.getIntValue();
                } else {
                    // An XML number always comes in a string since there is no syntax help as with JSON.
                    try {
                        lineNumber = Integer.parseInt(jp.getText().trim());
                    } catch (final NumberFormatException e) {
                        throw JsonMappingException.from(jp, "Non-numeric token (" + t + ") for property 'line'", e);
                    }
                }
            } else if ("method".equals(propName)) {
                methodName = jp.getText();
            } else if ("nativeMethod".equals(propName)) {
                // no setter, not passed via constructor: ignore
            } else {
                this.handleUnknownProperty(jp, ctxt, this._valueClass, propName);
            }
        }
        return new StackTraceElement(className, methodName, fileName, lineNumber);
    }
    throw ctxt.mappingException(this._valueClass, t);
}
 
Example 9
Source File: JacksonIssue429MyNamesTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
    JsonToken t = jp.getCurrentToken();
    // Must get an Object
    if (t == JsonToken.START_OBJECT) {
        String className = Strings.EMPTY, methodName = Strings.EMPTY, fileName = Strings.EMPTY;
        int lineNumber = -1;

        while ((t = jp.nextValue()) != JsonToken.END_OBJECT) {
            final String propName = jp.getCurrentName();
            if ("class".equals(propName)) {
                className = jp.getText();
            } else if ("file".equals(propName)) {
                fileName = jp.getText();
            } else if ("line".equals(propName)) {
                if (t.isNumeric()) {
                    lineNumber = jp.getIntValue();
                } else {
                    throw JsonMappingException.from(jp, "Non-numeric token (" + t
                            + ") for property 'lineNumber'");
                }
            } else if ("method".equals(propName)) {
                methodName = jp.getText();
            } else if ("nativeMethod".equals(propName)) {
                // no setter, not passed via constructor: ignore
            } else {
                handleUnknownProperty(jp, ctxt, _valueClass, propName);
            }
        }
        return new StackTraceElement(className, methodName, fileName, lineNumber);
    }
    throw ctxt.mappingException(_valueClass, t);
}
 
Example 10
Source File: CustomCollectionDeserializer.java    From caravan with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt,
    Object result)
    throws IOException {
  // Ok: must point to START_ARRAY (or equivalent)
  if (!p.isExpectedStartArrayToken()) {
    return handleNonArray(p, ctxt, (Collection<Object>) result);
  }
  // [databind#631]: Assign current value, to be accessible by custom serializers
  p.setCurrentValue(result);

  JsonDeserializer<Object> valueDes = _valueDeserializer;
  final TypeDeserializer typeDeser = _valueTypeDeserializer;
  CollectionReferringAccumulator referringAccumulator =
      (valueDes.getObjectIdReader() == null) ? null :
          new CollectionReferringAccumulator(_containerType.getContentType().getRawClass(), (Collection<Object>) result);

  JsonToken t;
  while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
    try {
      Object value;
      if (t == JsonToken.VALUE_NULL) {
        if (_skipNullValues) {
          continue;
        }
        value = _nullProvider.getNullValue(ctxt);
      } else if (typeDeser == null) {
        value = valueDes.deserialize(p, ctxt);
      } else {
        value = valueDes.deserializeWithType(p, ctxt, typeDeser);
      }
      if (referringAccumulator != null) {
        referringAccumulator.add(value);
      } else {
        ((Collection<Object>) result).add(value);
      }
    } catch (UnresolvedForwardReference reference) {
      if (referringAccumulator == null) {
        throw JsonMappingException
            .from(p, "Unresolved forward reference but no identity info", reference);
      }
      Referring ref = referringAccumulator.handleUnresolvedReference(reference);
      reference.getRoid().appendReferring(ref);
    } catch (Exception e) {
      boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS);
      if (!wrap) {
        ClassUtil.throwIfRTE(e);
      }
      throw JsonMappingException.wrapWithPath(e, result, ((Collection<Object>) result).size());
    }
  }
  return result;
}
 
Example 11
Source File: ListDeserializer.java    From allure2 with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<Object> deserialize(JsonParser p, DeserializationContext ctxt,
                                      Collection<Object> result)
        throws IOException {
    // Ok: must point to START_ARRAY (or equivalent)
    if (!p.isExpectedStartArrayToken()) {
        return result;
    }
    // [databind#631]: Assign current value, to be accessible by custom serializers
    p.setCurrentValue(result);

    JsonDeserializer<Object> valueDes = _valueDeserializer;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;
    CollectionReferringAccumulator referringAccumulator =
            (valueDes.getObjectIdReader() == null) ? null :
                    new CollectionReferringAccumulator(_containerType.getContentType().getRawClass(), result);

    JsonToken t;
    while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
        try {
            Object value;
            if (t == JsonToken.VALUE_NULL) {
                if (_skipNullValues) {
                    continue;
                }
                value = _nullProvider.getNullValue(ctxt);
            } else if (typeDeser == null) {
                value = valueDes.deserialize(p, ctxt);
            } else {
                value = valueDes.deserializeWithType(p, ctxt, typeDeser);
            }
            if (referringAccumulator != null) {
                referringAccumulator.add(value);
            } else {
                result.add(value);
            }
        } catch (UnresolvedForwardReference reference) {
            if (referringAccumulator == null) {
                throw JsonMappingException
                        .from(p, "Unresolved forward reference but no identity info", reference);
            }
            ReadableObjectId.Referring ref = referringAccumulator.handleUnresolvedReference(reference);
            reference.getRoid().appendReferring(ref);
        } catch (Exception e) {
            boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS);
            if (!wrap) {
                ClassUtil.throwIfRTE(e);
            }
            throw JsonMappingException.wrapWithPath(e, result, result.size());
        }
    }
    return result;
}
 
Example 12
Source File: ValueDeserializer.java    From vavr-jackson with Apache License 2.0 4 votes vote down vote up
static JsonMappingException mappingException(DeserializationContext ctxt, Class<?> targetClass, JsonToken token) {
    String tokenDesc = (token == null) ? "<end of input>" : String.format("%s token", token);
    return JsonMappingException.from(ctxt.getParser(),
            String.format("Can not deserialize instance of %s out of %s",
                    _calcName(targetClass), tokenDesc));
}
 
Example 13
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
/**
 * Produce an Avro datum using the supplied JSON event stream.
 * The event stream must already be positioned on the first token
 * to read, and will be consumed only as far as necessary to
 * produce the datum that conforms to the supplied Avro schema.
 *
 * @param parser the JSON parser which will produce the event stream
 *               for the datum.
 * @param targetSchema the schema of the Avro datum to produce.
 * @return an Avro datum that conforms to the supplied schema.
 * @throws IOException if an error occurs while producing the Avro datum.
 */
@Nullable
public Object read(final JsonParser parser,
                   final Schema targetSchema) throws IOException {
    final Object result;
    switch (targetSchema.getType()) {
        case RECORD:
            result = readRecord(parser, targetSchema);
            break;
        case ENUM:
            result = readEnum(parser, targetSchema);
            break;
        case ARRAY:
            result = readArray(parser, targetSchema);
            break;
        case MAP:
            result = readMap(parser, targetSchema);
            break;
        case UNION:
            result = readUnion(parser, targetSchema);
            break;
        case FIXED:
            result = readFixed(parser, targetSchema);
            break;
        case STRING:
            result = reader.readValue(parser, String.class);
            break;
        case BYTES:
            result = reader.readValue(parser, ByteBuffer.class);
            break;
        case INT:
            result = reader.readValue(parser, Integer.class);
            break;
        case LONG:
            result = reader.readValue(parser, Long.class);
            break;
        case FLOAT:
            result = reader.readValue(parser, Float.class);
            break;
        case DOUBLE:
            result = reader.readValue(parser, Double.class);
            break;
        case BOOLEAN:
            result = reader.readValue(parser, Boolean.class);
            break;
        case NULL:
            result = readNull(parser, targetSchema);
            break;
        default:
            throw JsonMappingException.from(parser, "Unknown schema type: " + targetSchema);
    }
    return result;
}
 
Example 14
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
private static JsonMappingException mappingException(final JsonParser parser,
                                                     final Schema targetSchema,
                                                     final JsonToken token) {
    return JsonMappingException.from(parser, "Cannot read " + token + " as " + targetSchema);
}
 
Example 15
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
private static JsonMappingException unsupportedUnionException(final JsonParser parser,
                                                              final Schema targetSchema) {
    return JsonMappingException.from(parser,
                                     "Unsupported union encountered; unions are only supported with null: " + targetSchema);
}