Java Code Examples for com.fasterxml.jackson.databind.DeserializationContext#reportInputMismatch()

The following examples show how to use com.fasterxml.jackson.databind.DeserializationContext#reportInputMismatch() . 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: RevisionJsonDeserializer.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static void validateRevisionNumber(DeserializationContext ctx, @Nullable JsonNode node,
                                           String type, boolean zeroAllowed) throws JsonMappingException {
    if (node == null) {
        ctx.reportInputMismatch(Revision.class, "missing %s revision number", type);
        // Should never reach here.
        throw new Error();
    }

    if (!node.canConvertToInt() || !zeroAllowed && node.intValue() == 0) {
        ctx.reportInputMismatch(Revision.class,
                                "A %s revision number must be %s integer.",
                                type, zeroAllowed ? "an" : "a non-zero");
        // Should never reach here.
        throw new Error();
    }
}
 
Example 2
Source File: TypeDeserializerBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Helper method called when {@link JsonParser} indicates that it can use
 * so-called native type ids, and such type id has been found.
 * 
 * @since 2.4
 */
protected Object _deserializeWithNativeTypeId(JsonParser jp, DeserializationContext ctxt, Object typeId)
    throws IOException
{
    JsonDeserializer<Object> deser;
    if (typeId == null) {
        /* 04-May-2014, tatu: Should error be obligatory, or should there be another method
         *   for "try to deserialize with native tpye id"?
         */
        deser = _findDefaultImplDeserializer(ctxt);
        if (deser == null) {
            return ctxt.reportInputMismatch(baseType(),
                    "No (native) type id found when one was expected for polymorphic type handling");
        }
    } else {
        String typeIdStr = (typeId instanceof String) ? (String) typeId : String.valueOf(typeId);
        deser = _findDeserializer(ctxt, typeIdStr);
    }
    return deser.deserialize(jp, ctxt);
}
 
Example 3
Source File: MediaTypeJsonDeserializer.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public MediaType deserialize(JsonParser p, DeserializationContext ctx)
        throws IOException {
    final JsonNode tree = p.getCodec().readTree(p);
    if (!tree.isTextual()) {
        ctx.reportInputMismatch(MediaType.class, "media type must be a string.");
        return null;
    }

    final String textValue = tree.textValue();
    try {
        return MediaType.parse(textValue);
    } catch (IllegalArgumentException unused) {
        // Failed to parse.
        ctx.reportInputMismatch(MediaType.class, "malformed media type: " + textValue);
        return null;
    }
}
 
Example 4
Source File: RawSessionJsonDeserializer.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public Serializable deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    try (ByteArrayInputStream bais =
                 new ByteArrayInputStream(Base64.getDecoder().decode(p.readValueAs(String.class)));
         ObjectInputStream ois = new ObjectInputStream(bais)) {
        return (Serializable) ois.readObject();
    } catch (ClassNotFoundException e) {
        ctxt.reportInputMismatch(Serializable.class, "failed to deserialize a raw session: " + e);
        throw new Error(); // Should never reach here
    }
}
 
Example 5
Source File: CommitMessageDtoDeserializer.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public CommitMessageDto deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    final JsonNode jsonNode = p.readValueAsTree();
    final JsonNode summary = jsonNode.get("summary");
    if (summary == null || summary.textValue() == null) {
        ctxt.reportInputMismatch(CommitMessageDto.class, "commit message should have a summary.");
        // should never reach here
        throw new Error();
    }

    final String detail = jsonNode.get("detail") == null ? "" : jsonNode.get("detail").textValue();
    final JsonNode markupNode = jsonNode.get("markup");
    final Markup markup = Markup.parse(markupNode == null ? "unknown" : markupNode.textValue());
    return new CommitMessageDto(summary.textValue(), detail, markup);
}
 
Example 6
Source File: PrimitiveKVHandler.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
public char value(DeserializationContext ctx, JsonParser parser) throws IOException {
    String valueAsString = parser.getValueAsString();
    if (valueAsString.length() != 1) {
        ctx.reportInputMismatch(char.class,
                                "Cannot convert a JSON String of length %d into a char element of map",
                                valueAsString.length());
    }
    return valueAsString.charAt(0);
}
 
Example 7
Source File: BaseCharCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    Intermediate intermediate = createIntermediate();

    if (p.isExpectedStartArrayToken()) {
        JsonToken t;
        while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
            String str;
            if (t == JsonToken.VALUE_STRING) {
                str = p.getText();
            } else {
                CharSequence cs =
                        (CharSequence) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
                str = cs.toString();
            }
            if (str.length() != 1) {
                ctxt.reportInputMismatch(this,
                        "Cannot convert a JSON String of length %d into a char element of " +
                                "char array",
                        str.length());
            }
            add(intermediate, str.charAt(0));
        }
        return finish(intermediate);
    }

    char[] chars = p.getTextCharacters();
    addAll(intermediate, chars, p.getTextOffset(), p.getTextLength());
    return finish(intermediate);
}
 
Example 8
Source File: AbstractHttpHeadersJsonDeserializer.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void addHeader(DeserializationContext ctx, HttpHeadersBuilder builder,
                       AsciiString name, JsonNode valueNode) throws JsonMappingException {
    if (valueNode.isTextual()) {
        builder.add(name, valueNode.asText());
    } else {
        ctx.reportInputMismatch(handledType(),
                                "HTTP header '%s' contains %s (%s); only strings are allowed.",
                                name, valueNode.getNodeType(), valueNode);
    }
}
 
Example 9
Source File: ProtobufDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
private AssertionError reportInputMismatch(
        DeserializationContext context,
        String message
) throws JsonMappingException {
  context.reportInputMismatch(this, message);
  // the previous method should have thrown
  throw new AssertionError();
}
 
Example 10
Source File: ValueDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
protected void populate(
        Value.Builder builder,
        JsonParser parser,
        DeserializationContext context
) throws IOException {
  switch (parser.getCurrentToken()) {
    case START_OBJECT:
      Object structValue = readValue(builder, STRUCT_FIELD, null, parser, context);
      builder.setField(STRUCT_FIELD, structValue);
      return;
    case START_ARRAY:
      Object listValue = readValue(builder, LIST_FIELD, null, parser, context);
      builder.setField(LIST_FIELD, listValue);
      return;
    case VALUE_STRING:
      builder.setStringValue(parser.getText());
      return;
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
      builder.setNumberValue(parser.getValueAsDouble());
      return;
    case VALUE_TRUE:
      builder.setBoolValue(true);
      return;
    case VALUE_FALSE:
      builder.setBoolValue(false);
      return;
    case VALUE_NULL:
      builder.setNullValue(NullValue.NULL_VALUE);
      return;
    default:
      String message = "Can not deserialize instance of com.google.protobuf.Value out of " + parser.currentToken() + " token";
      context.reportInputMismatch(Value.class, message);
      // the previous method should have thrown
      throw new AssertionError();
  }
}
 
Example 11
Source File: CentralDogmaConfig.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private static ServerPort fail(DeserializationContext ctx, JsonNode root) throws JsonMappingException {
    ctx.reportInputMismatch(ServerPort.class, "invalid server port information: %s", root);
    throw new Error(); // Should never reach here.
}
 
Example 12
Source File: RevisionJsonDeserializer.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
public Revision deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    final JsonNode node = p.readValueAsTree();
    if (node.isNumber()) {
        validateRevisionNumber(ctx, node, "major", false);
        return new Revision(node.intValue());
    }

    if (node.isTextual()) {
        try {
            return new Revision(node.textValue());
        } catch (IllegalArgumentException e) {
            ctx.reportInputMismatch(Revision.class, e.getMessage());
            // Should never reach here.
            throw new Error();
        }
    }

    if (!node.isObject()) {
        ctx.reportInputMismatch(Revision.class,
                                "A revision must be a non-zero integer or " +
                                "an object that contains \"major\" and \"minor\" properties.");
        // Should never reach here.
        throw new Error();
    }

    final JsonNode majorNode = node.get("major");
    final JsonNode minorNode = node.get("minor");
    final int major;

    validateRevisionNumber(ctx, majorNode, "major", false);
    major = majorNode.intValue();
    if (minorNode != null) {
        validateRevisionNumber(ctx, minorNode, "minor", true);
        if (minorNode.intValue() != 0) {
            ctx.reportInputMismatch(Revision.class,
                                    "A revision must not have a non-zero \"minor\" property.");
        }
    }

    return new Revision(major);
}
 
Example 13
Source File: FailingDeserializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    ctxt.reportInputMismatch(this, _message);
    return null;
}
 
Example 14
Source File: BaseCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException {
    Intermediate intermediate = createIntermediate();

    if (p.isExpectedStartArrayToken()) {
        JsonToken t;
        while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
            String str;
            if (t == JsonToken.VALUE_STRING) {
                str = p.getText();
            } else {
                CharSequence cs = (CharSequence) ctxt.handleUnexpectedToken(getValueType(ctxt), p);
                str = cs.toString();
            }
            if (str.length() != 1) {
                ctxt.reportInputMismatch(this,
                                         "Cannot convert a JSON String of length %d into a char element of " +
                                         "char array",
                                         str.length());
            }
            intermediate.add(str.charAt(0));
        }
        return finish(intermediate);
    }

    char[] chars = p.getTextCharacters();
    if (p.getTextOffset() == 0 && p.getTextLength() == chars.length) {
        intermediate.addAll(chars);
    } else {
        int i = 0;
        // first, copy in batches of BATCH_COPY_SIZE
        if ((p.getTextLength() - i) >= BATCH_COPY_SIZE) {
            char[] buf = new char[BATCH_COPY_SIZE];
            do {
                System.arraycopy(chars, p.getTextOffset() + i, buf, 0, BATCH_COPY_SIZE);
                intermediate.addAll(buf);
                i += BATCH_COPY_SIZE;
            } while ((p.getTextLength() - i) >= BATCH_COPY_SIZE);
        }
        // and finally, copy the remainder.
        if (p.getTextLength() > i) {
            char[] tail = Arrays.copyOfRange(
                    chars, p.getTextOffset() + i, p.getTextOffset() + p.getTextLength());
            intermediate.addAll(tail);
        }
    }
    return finish(intermediate);
}
 
Example 15
Source File: LocalDateDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            if (!isLenient()) {
                return _failForNotLenient(parser, context, JsonToken.VALUE_STRING);
            }
            return null;
        }
        // as per [datatype-jsr310#37], only check for optional (and, incorrect...) time marker 'T'
        // if we are using default formatter
        DateTimeFormatter format = _formatter;
        try {
            if (format == DEFAULT_FORMATTER) {
                // JavaScript by default includes time in JSON serialized Dates (UTC/ISO instant format).
                if (string.length() > 10 && string.charAt(10) == 'T') {
                   if (string.endsWith("Z")) {
                       return LocalDateTime.ofInstant(Instant.parse(string), ZoneOffset.UTC).toLocalDate();
                   } else {
                       return LocalDate.parse(string, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                   }
                }
            }
            return LocalDate.parse(string, format);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, format, string);
        }
    }
    if (parser.isExpectedStartArrayToken()) {
        JsonToken t = parser.nextToken();
        if (t == JsonToken.END_ARRAY) {
            return null;
        }
        if (context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
                && (t == JsonToken.VALUE_STRING || t==JsonToken.VALUE_EMBEDDED_OBJECT)) {
            final LocalDate parsed = deserialize(parser, context);
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(parser, context);
            }
            return parsed;            
        }
        if (t == JsonToken.VALUE_NUMBER_INT) {
            int year = parser.getIntValue();
            int month = parser.nextIntValue(-1);
            int day = parser.nextIntValue(-1);
            
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                        "Expected array to end");
            }
            return LocalDate.of(year, month, day);
        }
        context.reportInputMismatch(handledType(),
                "Unexpected token (%s) within Array, expected VALUE_NUMBER_INT",
                t);
    }
    if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        return (LocalDate) parser.getEmbeddedObject();
    }
    // 06-Jan-2018, tatu: Is this actually safe? Do users expect such coercion?
    if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
        // issue 58 - also check for NUMBER_INT, which needs to be specified when serializing.
        if (_shape == JsonFormat.Shape.NUMBER_INT || isLenient()) {
            return LocalDate.ofEpochDay(parser.getLongValue());
        }
        return _failForNotLenient(parser, context, JsonToken.VALUE_STRING);
    }
    return _handleUnexpectedToken(context, parser, "Expected array or string.");
}
 
Example 16
Source File: JSR310StringParsableDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
    if (p.hasToken(JsonToken.VALUE_STRING)) {
        final String text = p.getText().trim();
        if (text.length() == 0) {
            CoercionAction act = ctxt.findCoercionAction(logicalType(), _valueClass,
                    CoercionInputShape.EmptyString);
            if (act == CoercionAction.Fail) {
                ctxt.reportInputMismatch(this,
    "Cannot coerce empty String (\"\") to %s (but could if enabling coercion using `CoercionConfig`)",
    _coercedTypeDesc());
            }
            if (act == CoercionAction.AsEmpty) {
                return getEmptyValue(ctxt);
            }
            // None of the types has specific null value
            return null;
        }
        try {
            switch (_typeSelector) {
            case TYPE_PERIOD:
                return Period.parse(text);
            case TYPE_ZONE_ID:
                return ZoneId.of(text);
            case TYPE_ZONE_OFFSET:
                return ZoneOffset.of(text);
            }
        } catch (DateTimeException e) {
            return _handleDateTimeException(ctxt, e, text);
        }
    }
    if (p.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        // 20-Apr-2016, tatu: Related to [databind#1208], can try supporting embedded
        //    values quite easily
        return p.getEmbeddedObject();
    }
    if (p.hasToken(JsonToken.START_ARRAY)){
        return _deserializeFromArray(p, ctxt);
    }
    
    throw ctxt.wrongTokenException(p, handledType(), JsonToken.VALUE_STRING, null);
}