com.fasterxml.jackson.databind.exc.MismatchedInputException Java Examples

The following examples show how to use com.fasterxml.jackson.databind.exc.MismatchedInputException. 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: ZoneIdDeserTest.java    From jackson-modules-java8 with Apache License 2.0 7 votes vote down vote up
public void testStrictDeserializeFromEmptyString() throws Exception {

        final String key = "zoneId";
        final ObjectMapper mapper = mapperBuilder()
                .withCoercionConfig(LogicalType.DateTime,
                        cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
                .build();
        final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

        String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
        Map<String, ZoneId> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
        assertNull(actualMapFromNullStr.get(key));

        String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
        try {
            objectReader.readValue(valueFromEmptyStr);
            fail("Should not pass");
        } catch (MismatchedInputException e) {
            verifyException(e, "Cannot coerce empty String");
            verifyException(e, ZoneId.class.getName());
        }
    }
 
Example #2
Source File: YearMonthDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "YearMonth";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(YearMonth.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, YearMonth> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #3
Source File: ZoneIdDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public void testZoneIdDeserFromEmpty() throws Exception
{
    // by default, should be fine
    assertNull(MAPPER.readValue(quote("  "), ZoneId.class));
    // but fail if coercion illegal
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    try {
        mapper.readValue(quote(" "), ZoneId.class);
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
        verifyException(e, ZoneId.class.getName());
    }
}
 
Example #4
Source File: PeriodDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "period";
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, Period> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", ""));
    try {
        objectReader.readValue(valueFromEmptyStr);
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
    }
}
 
Example #5
Source File: OffsetTimeDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "OffsetTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(OffsetTime.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, OffsetTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #6
Source File: LocalDateTimeDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "datetime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(LocalDateTime.class,
                    c -> c.setFormat(JsonFormat.Value.forLeniency(false))
            )
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);
    final String dateValAsNullStr = null;

    // even with strict, null value should be deserialized without throwing an exception
    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, LocalDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String dateValAsEmptyStr = "";
    // TODO: nothing stops us from writing an empty string, maybe there should be a check there too?
    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", dateValAsEmptyStr));
    // with strict, deserializing an empty string is not permitted
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #7
Source File: OffsetDateTimeDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "OffsetDateTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(OffsetDateTime.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
        .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, OffsetDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #8
Source File: ZoneOffsetDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public void testZoneOffsetDeserFromEmpty() throws Exception
{
    // by default, should be fine
    assertNull(MAPPER.readValue(quote("  "), ZoneOffset.class));
    // but fail if coercion illegal
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    try {
        mapper.readerFor(ZoneOffset.class)
            .readValue(quote(" "));
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
        verifyException(e, ZoneOffset.class.getName());
    }
}
 
Example #9
Source File: ObjectMapper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method called to ensure that given parser is ready for reading
 * content for data binding.
 *
 * @return First token to be used for data binding after this call:
 *  can never be null as exception will be thrown if parser cannot
 *  provide more tokens.
 *
 * @throws IOException if the underlying input source has problems during
 *   parsing
 * @throws JsonParseException if parser has problems parsing content
 * @throws JsonMappingException if the parser does not have any more
 *   content to map (note: Json "null" value is considered content;
 *   enf-of-stream not)
 */
protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException
{
    _deserializationConfig.initialize(p); // since 2.5

    // First: must point to a token; if not pointing to one, advance.
    // This occurs before first read from JsonParser, as well as
    // after clearing of current token.
    JsonToken t = p.getCurrentToken();
    if (t == null) {
        // and then we must get something...
        t = p.nextToken();
        if (t == null) {
            // Throw mapping exception, since it's failure to map,
            //   not an actual parsing problem
            throw MismatchedInputException.from(p, targetType,
                    "No content to map due to end-of-input");
        }
    }
    return t;
}
 
Example #10
Source File: ZoneOffsetDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "zoneOffset";
    final ObjectMapper mapper = mapperBuilder()
            .withCoercionConfig(LogicalType.DateTime,
                    cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, ZoneOffset> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    try {
        objectReader.readValue(valueFromEmptyStr);
        fail("Should not pass");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
        verifyException(e, ZoneOffset.class.getName());
    }
}
 
Example #11
Source File: InstantDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "instant";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(Instant.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, Instant> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #12
Source File: ZonedDateTimeDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "zonedDateTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(ZonedDateTime.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
        .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, ZonedDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #13
Source File: DurationDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test ( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "duration";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(Duration.class,
                    o -> o.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();

    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);
    final String dateValAsNullStr = null;

    // even with strict, null value should be deserialized without throwing an exception
    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, Duration> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String dateValAsEmptyStr = "";
    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, dateValAsEmptyStr));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #14
Source File: LocalTimeDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "localTime";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(LocalTime.class,
                    c -> c.setFormat(JsonFormat.Value.forLeniency(false)))
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, LocalTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", ""));
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #15
Source File: LocalDateDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test( expected =  MismatchedInputException.class)
public void testStrictDeserializeFromEmptyString() throws Exception {

    final String key = "date";
    final ObjectMapper mapper = mapperBuilder()
            .withConfigOverride(LocalDate.class,
                    c -> c.setFormat(JsonFormat.Value.forLeniency(false))
            )
            .build();
    final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);
    final String dateValAsNullStr = null;

    // even with strict, null value should be deserialized without throwing an exception
    String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr));
    Map<String, LocalDate> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    assertNull(actualMapFromNullStr.get(key));

    String dateValAsEmptyStr = "";
    // TODO: nothing stops us from writing an empty string, maybe there should be a check there too?
    String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", dateValAsEmptyStr));
    // with strict, deserializing an empty string is not permitted
    objectReader.readValue(valueFromEmptyStr);
}
 
Example #16
Source File: CloudEventDeserializer.java    From sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public CloudEvent deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    // In future we could eventually find a better solution avoiding this buffering step, but now this is the best option
    // Other sdk does the same in order to support all versions
    ObjectNode node = ctxt.readValue(p, ObjectNode.class);

    try {
        return new JsonMessage(p, node).read(CloudEventBuilder::fromSpecVersion);
    } catch (RuntimeException e) {
        // Yeah this is bad but it's needed to support checked exceptions...
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        }
        throw MismatchedInputException.wrapWithPath(e, null);
    }
}
 
Example #17
Source File: DdiArtifactTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiArtifact = "{\"filename\": [\"test.file\"],\"hashes\":{\"sha1\":\"123\",\"md5\":\"456\",\"sha256\":\"789\"},\"size\":111,\"links\":[]}";

    // Test
    mapper.readValue(serializedDdiArtifact, DdiArtifact.class);
}
 
Example #18
Source File: DdiConfigTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiConfig = "{\"polling\":{\"sleep\":[\"10\"]}}";

    // Test
    mapper.readValue(serializedDdiConfig, DdiConfig.class);
}
 
Example #19
Source File: TotalDeserializer.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    try {
        return jsonParser.readValueAs(Long.class);
    }  catch (MismatchedInputException e) {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        return node.get("value").longValue();
    }
}
 
Example #20
Source File: DdiArtifactHashTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiArtifact = "{\"sha1\": [123], \"md5\": 456, \"sha256\": \"789\"";

    // Test
    mapper.readValue(serializedDdiArtifact, DdiArtifactHash.class);
}
 
Example #21
Source File: DdiCancelTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiCancel = "{\"id\":[\"1234\"],\"cancelAction\":{\"stopId\":\"1234\"}}";

    // Test
    mapper.readValue(serializedDdiCancel, DdiCancel.class);
}
 
Example #22
Source File: DdiStatusTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiStatus = "{\"execution\":[\"proceeding\"],\"result\":{\"finished\":\"none\","
            + "\"progress\":{\"cnt\":30,\"of\":100}},\"details\":[]}";

    // Test
    mapper.readValue(serializedDdiStatus, DdiStatus.class);
}
 
Example #23
Source File: DdiDeploymentBaseTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiDeploymentBase = "{\"id\":[\"1234\"],\"deployment\":{\"download\":\"forced\","
            + "\"update\":\"attempt\",\"maintenanceWindow\":\"available\",\"chunks\":[]},"
            + "\"actionHistory\":{\"status\":\"TestAction\",\"messages\":[\"Action status message 1\","
            + "\"Action status message 2\"]},\"links\":[]}";

    // Test
    mapper.readValue(serializedDdiDeploymentBase, DdiDeploymentBase.class);
}
 
Example #24
Source File: DdiMetadataTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiMetadata = "{\"key\":[\"testKey\"],\"value\":\"testValue\"}";

    // Test
    mapper.readValue(serializedDdiMetadata, DdiMetadata.class);
}
 
Example #25
Source File: DdiActionFeedbackTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiActionFeedback = "{\"id\": [1],\"time\":\"20190809T121314\",\"status\":{\"execution\":\"closed\",\"result\":null,\"details\":[]}}";

    // Test
    mapper.readValue(serializedDdiActionFeedback, DdiActionFeedback.class);
}
 
Example #26
Source File: ScalarCoercionTest.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private void _verifyNullFail(Class<?> type) throws IOException
{
    try {
        NOT_COERCING_MAPPER.readerFor(type).readValue("\"\"");
        fail("Should have failed for "+type);
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot coerce empty String");
    }
}
 
Example #27
Source File: HbaseSinkConfigTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = MismatchedInputException.class)
public final void invalidListValidateTest() throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("zookeeperQuorum", "localhost");
    map.put("zookeeperClientPort", "2181");
    map.put("zookeeperZnodeParent", "/hbase");
    map.put("tableName", "pulsar_hbase");
    map.put("rowKeyName", "rowKey");
    map.put("familyName", "info");
    map.put("qualifierNames", new ArrayList<>().add("name"));

    HbaseSinkConfig config = HbaseSinkConfig.load(map);
    config.validate();
}
 
Example #28
Source File: DdiDeploymentTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = MismatchedInputException.class)
@Description("Verify that deserialization fails for known properties with a wrong datatype")
public void shouldFailForObjectWithWrongDataTypes() throws IOException {
    // Setup
    String serializedDdiDeployment = "{\"download\":[\"forced\"],\"update\":\"attempt\", "
            + "\"maintenanceWindow\":\"available\",\"chunks\":[]}";

    // Test
    mapper.readValue(serializedDdiDeployment, DdiDeployment.class);
}
 
Example #29
Source File: ZoneOffsetDeserTest.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadDeserializationAsString01() throws Throwable
{
    try {
        READER.readValue("\"notazonedoffset\"");
        fail("expected MismatchedInputException");
    } catch (MismatchedInputException e) {
        verifyException(e, "Invalid ID for ZoneOffset");
    }
}
 
Example #30
Source File: ZoneOffsetDeserTest.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationAsArrayDisabled() throws Throwable
{
    try {
        READER.readValue("[\"+0300\"]");
        fail("expected MismatchedInputException");
    } catch (MismatchedInputException e) {
        verifyException(e, "Cannot deserialize value of type `java.time.ZoneOffset` from Array value");
    }
}