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

The following examples show how to use com.fasterxml.jackson.databind.exc.InvalidFormatException. 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: JsonAdapterUtils.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Override
public LocalDate deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
        final String str = p.getValueAsString();
        try {
            // try ISO first
            return ZonedDateTime.parse(str).toLocalDateTime().toLocalDate();
        } catch (Exception zdt) {
            final LocalDate ld = DateUtils.ldParseSDT(p.getValueAsString());
            if (ld == null) {
                LOG.error("Unable to process date " + p.getValueAsString(), zdt);
            } else {
                return ld;
            }
        }
    } else if (p.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
        return DateUtils.ldFrom(p.getLongValue());
    }
    throw new InvalidFormatException(p, "Unable to format date: " + p.getValueAsString(), p.getCurrentValue(), LocalDate.class);
}
 
Example #2
Source File: TextNode.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
     * Method for accessing textual contents assuming they were
     * base64 encoded; if so, they are decoded and resulting binary
     * data is returned.
     */
    @SuppressWarnings("resource")
    public byte[] getBinaryValue(Base64Variant b64variant) throws IOException
    {
        final String str = _value.trim();
        ByteArrayBuilder builder = new ByteArrayBuilder(4 + ((str.length() * 3) << 2));
        try {
            b64variant.decode(str, builder);
        } catch (IllegalArgumentException e) {
            throw InvalidFormatException.from(null,
                    String.format(
"Cannot access contents of TextNode as binary due to broken Base64 encoding: %s",
e.getMessage()),
                    str, byte[].class);
        }
        return builder.toByteArray();
    }
 
Example #3
Source File: ErrorResponsesTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildOfJacksonWithInvalidType() throws Exception {
    String badDocument = "{\"value\":\"notANumber\"}";

    List<ErrorResponses.StackTraceRepresentation> mappedError = null;
    try {
        mapper.readValue(badDocument, MyService.class);
        fail("Expected parsing exception");
    } catch (InvalidFormatException e) {
        mappedError = ErrorResponses.buildExceptionContext(e);
    }

    Map<String, Object> details = mappedError.get(0).getDetails();
    assertThat(details, is(notNullValue()));

    assertThat(details.get("pathReference"), is(equalTo(this.getClass().getName() + "$MyService[\"value\"]")));
    assertThat(details.get("targetType"), is(equalTo("int")));
    assertThat((String) details.get("errorLocation"), containsString("line: 1"));
    assertThat(details.get("document"), is(equalTo("{\"value\":\"notANumber\"}")));
}
 
Example #4
Source File: GenericExceptionMapper.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(Throwable exception) {
	LOGGER.error(String.format("Error %s url: '%s'", exception.getClass().getSimpleName(), uriInfo.getPath()), exception);

	Monitors.error("error", "error");

	ApplicationException applicationException = null;

       if (exception instanceof IllegalArgumentException || exception instanceof InvalidFormatException) {
           applicationException = new ApplicationException(Code.INVALID_INPUT, exception.getMessage(), exception);
       } else {
           applicationException = new ApplicationException(Code.INTERNAL_ERROR, exception.getMessage(), exception);
       }
	
	Map<String, Object> entityMap = applicationException.toMap();
	entityMap.put("instance", host);
	
	return Response.status(applicationException.getHttpStatusCode()).entity(entityMap).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example #5
Source File: TestResponse.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testDecodeResponseError() {
  InvocationException exception = null;
  try {
    intf.testDecodeResponseError();
  } catch (InvocationException e) {
    // 1. InvocationException: wrapper exception
    exception = e;
  }
  Objects.requireNonNull(exception);
  // 2. CseException: bizKeeper exception
  Throwable cause = exception.getCause();
  TestMgr.check(InvalidFormatException.class, cause.getClass());
  TestMgr.check(
      ((InvalidFormatException) cause).getMessage().contains("Cannot deserialize value of type `java.util.Date`"),
      true);
}
 
Example #6
Source File: JsonAdapterUtils.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Override
public Instant deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
        final String str = p.getValueAsString();
        try {
            // try ISO first
            return ZonedDateTime.parse(str).toInstant();
        } catch (Exception zdt) {
            final Instant instant = DateUtils.iParseSDT(p.getValueAsString());
            if (instant == null) {
                LOG.error("Unable to process instant " + p.getValueAsString(), zdt);
            } else {
                return instant;
            }
        }
    } else if (p.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
        return DateUtils.iFrom(p.getLongValue());
    }
    throw new InvalidFormatException(p, "Unable to format instant: " + p.getValueAsString(), p.getCurrentValue(), Instant.class);
}
 
Example #7
Source File: TPMSAttestDeserializer.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@Override
public TPMSAttest deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    byte[] value = p.getBinaryValue();
    ByteBuffer buffer = ByteBuffer.wrap(value);
    byte[] magicBytes = new byte[4];
    buffer.get(magicBytes);
    TPMGenerated magic = TPMGenerated.create(magicBytes);
    byte[] typeBytes = new byte[2];
    buffer.get(typeBytes);
    TPMISTAttest type = TPMISTAttest.create(typeBytes);
    int qualifiedSignerSize = UnsignedNumberUtil.getUnsignedShort(buffer);
    byte[] qualifiedSigner = new byte[qualifiedSignerSize];
    buffer.get(qualifiedSigner);
    int extraDataSize = UnsignedNumberUtil.getUnsignedShort(buffer);
    byte[] extraData = new byte[extraDataSize];
    buffer.get(extraData);
    TPMSClockInfo clock = extractClockInfo(buffer);
    BigInteger firmwareVersion = UnsignedNumberUtil.getUnsignedLong(buffer);
    TPMUAttest attested = extractTPMUAttest(type, buffer);
    if (buffer.remaining() > 0) {
        throw new InvalidFormatException(p, "input byte array contains surplus data", value, TPMTPublic.class);
    }

    return new TPMSAttest(magic, type, qualifiedSigner, extraData, clock, firmwareVersion, attested);
}
 
Example #8
Source File: JsonAdapterUtils.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
@Override
public LocalDateTime deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
        final String str = p.getValueAsString();
        try {
            // try ISO first
            return ZonedDateTime.parse(str).toLocalDateTime();
        } catch (Exception zdt) {
            final LocalDateTime ldt = DateUtils.ldtParseSDT(p.getValueAsString());
            if (ldt == null) {
                LOG.error("Unable to process datetime " + p.getValueAsString(), zdt);
            } else {
                return ldt;
            }
        }
    } else if (p.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
        return DateUtils.ldtFrom(p.getLongValue());
    }
    throw new InvalidFormatException(p, "Unable to format datetime: " + p.getValueAsString(), p.getCurrentValue(), LocalDateTime.class);
}
 
Example #9
Source File: ExcelHandle.java    From danyuan-application with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void readXLSX(String path, int num) throws InvalidFormatException, IOException {
	File file = new File(path);
	@SuppressWarnings("resource")
	XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(file));
	XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(num);

	int rowstart = xssfSheet.getFirstRowNum();
	int rowEnd = xssfSheet.getLastRowNum();
	for (int i = rowstart; i <= rowEnd; i++) {
		XSSFRow row = xssfSheet.getRow(i);
		if (null == row) {
			continue;
		}
		int cellStart = row.getFirstCellNum();
		int cellEnd = row.getLastCellNum();

		for (int k = cellStart; k <= cellEnd; k++) {
			XSSFCell cell = row.getCell(k);
			if (null == cell) {
				continue;
			}

			switch (cell.getCellTypeEnum()) {
				case NUMERIC: // 数字
					System.out.print(cell.getNumericCellValue() + "   ");
					break;
				case STRING: // 字符串
					System.out.print(cell.getStringCellValue() + "   ");
					break;
				case BOOLEAN: // Boolean
					System.out.println(cell.getBooleanCellValue() + "   ");
					break;
				case FORMULA: // 公式
					System.out.print(cell.getCellFormula() + "   ");
					break;
				case BLANK: // 空值
					System.out.println(" ");
					break;
				case ERROR: // 故障
					System.out.println(" ");
					break;
				default:
					System.out.print("未知类型   ");
					break;
			}

		}
		System.out.print("\n");
	}

}
 
Example #10
Source File: KafkaExceptionMapper.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
private Response handleException(final Throwable exception) {
  if (exception instanceof AuthenticationException) {
    return getResponse(exception, Status.UNAUTHORIZED,
        KAFKA_AUTHENTICATION_ERROR_CODE);
  } else if (exception instanceof AuthorizationException) {
    return getResponse(exception, Status.FORBIDDEN,
        KAFKA_AUTHORIZATION_ERROR_CODE);
  } else if (HANDLED.containsKey(exception.getClass())) {
    return getResponse(exception);
  } else if (exception instanceof RetriableException) {
    log.debug("Kafka retriable exception", exception);
    return getResponse(exception, Status.INTERNAL_SERVER_ERROR,
        KAFKA_RETRIABLE_ERROR_ERROR_CODE);
  } else if (exception instanceof KafkaException) {
    log.error("Kafka exception", exception);
    return getResponse(exception, Status.INTERNAL_SERVER_ERROR,
        KAFKA_ERROR_ERROR_CODE);
  } else if (exception instanceof InvalidFormatException) {
    return getResponse(exception, Status.BAD_REQUEST,
        KAFKA_BAD_REQUEST_ERROR_CODE);
  } else {
    log.error("Unhandled exception", exception);
    return super.toResponse(exception);
  }
}
 
Example #11
Source File: JsonContentConversionExceptionMapper.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(InvalidFormatException ex) {
    // log the error
    logger.info(String.format("%s. Returning %s response.", ex, Response.Status.BAD_REQUEST));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, ex);
    }

    String value = ex.getValue().toString();
    String propName = "field";

    if (ex.getPath() != null && !ex.getPath().isEmpty()) {
        JsonMappingException.Reference path = ex.getPath().get(ex.getPath().size() - 1);
        if (path != null) {
            propName = path.getFieldName();
        }
    }

    String errorMessage = "The provided " + propName + " value '" + sanitizeMessage(value) + "' is not of required type " + ex.getTargetType();

    logger.error(errorMessage);

    return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).type("text/plain").build();
}
 
Example #12
Source File: Origin.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@JsonCreator
private static Origin deserialize(String value) throws InvalidFormatException {
    try {
        return create(value);
    } catch (IllegalArgumentException e) {
        throw new InvalidFormatException(null, "value is out of range", value, Origin.class);
    }
}
 
Example #13
Source File: TPMTPublicDeserializer.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Override
public TPMTPublic deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    byte[] value = p.getBinaryValue();
    try {
        return deserialize(value);
    } catch (IllegalArgumentException e) {
        throw new InvalidFormatException(p, "input byte array contains surplus data", value, TPMTPublic.class);
    }
}
 
Example #14
Source File: ChallengeDeserializer.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Challenge deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    String str = p.getValueAsString();
    try {
        return new DefaultChallenge(str);
    } catch (IllegalArgumentException e) {
        throw new InvalidFormatException(null, "value is out of range", str, DefaultChallenge.class);
    }
}
 
Example #15
Source File: TimestampDeserializerTest.java    From act-platform with ISC License 5 votes vote down vote up
@Test(expected = InvalidFormatException.class)
public void testDeserializeStringInvalidFormat() throws IOException {
  when(context.handleWeirdStringValue(eq(Long.class), eq("invalid"), anyString())).thenThrow(InvalidFormatException.class);
  when(parser.hasToken(eq(JsonToken.VALUE_STRING))).thenReturn(true);
  when(parser.getText()).thenReturn("invalid");
  deserializer.deserialize(parser, context);
}
 
Example #16
Source File: InvalidFormatMapper.java    From act-platform with ISC License 5 votes vote down vote up
@Override
public Response toResponse(InvalidFormatException ex) {
  String value = ObjectUtils.ifNotNull(ex.getValue(), Object::toString, "NULL");

  return ResultStash.builder()
          .setStatus(Response.Status.PRECONDITION_FAILED)
          .addFieldError("JSON field has an invalid value.", "invalid.json.field.value", MapperUtils.printPropertyPath(ex), value)
          .buildResponse();
}
 
Example #17
Source File: JWSDeserializer.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Override
public JWS<? extends Serializable> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {

    byte[] value = p.getBinaryValue();
    String str = new String(value, StandardCharsets.UTF_8);
    try {
        return jwsFactory.parse(str, Response.class);
    } catch (IllegalArgumentException e) {
        throw new InvalidFormatException(p, "value is not valid as JWS", value, JWS.class);
    }
}
 
Example #18
Source File: UUIDDeserializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private UUID _fromBytes(byte[] bytes, DeserializationContext ctxt) throws JsonMappingException {
    if (bytes.length != 16) {
        throw InvalidFormatException.from(ctxt.getParser(),
                "Can only construct UUIDs from byte[16]; got "+bytes.length+" bytes",
                bytes, handledType());
    }
    return new UUID(_long(bytes, 0), _long(bytes, 8));
}
 
Example #19
Source File: StateOptions.java    From java-sdk with MIT License 5 votes vote down vote up
@Override
public Duration deserialize(
    JsonParser jsonParser,
    DeserializationContext deserializationContext) throws IOException {
  String durationStr = jsonParser.readValueAs(String.class);
  Duration duration = null;
  if (durationStr != null && !durationStr.trim().isEmpty()) {
    try {
      duration = DurationUtils.convertDurationFromDaprFormat(durationStr);
    } catch (Exception ex) {
      throw InvalidFormatException.from(jsonParser, "Unable to parse duration.", ex);
    }
  }
  return duration;
}
 
Example #20
Source File: DeserializationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper method for constructing exception to indicate that input JSON
 * Number was not suitable for deserializing into given target type.
 * Note that most of the time this method should NOT be called; instead,
 * {@link #handleWeirdNumberValue} should be called which will call this method
 * if necessary.
 */
public JsonMappingException weirdNumberException(Number value, Class<?> instClass,
        String msg) {
    return InvalidFormatException.from(_parser,
            String.format("Cannot deserialize value of type %s from number %s: %s",
                    ClassUtil.nameOf(instClass), String.valueOf(value), msg),
            value, instClass);
}
 
Example #21
Source File: ErrorResponses.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> appendJacksonErrorDetails(JsonProcessingException cause) {
    Map<String, Object> out = new TreeMap<>();

    JsonLocation location = cause.getLocation();
    if (location != null) {
        out.put("errorLocation", "line: " + location.getLineNr() + ", column: " + location.getColumnNr());
        if (location.getSourceRef() != null && location.getSourceRef() instanceof String) {
            out.put("document", location.getSourceRef());
        }
    }

    if (cause instanceof JsonMappingException) {
        JsonMappingException mappingEx = (JsonMappingException) cause;
        if (mappingEx.getPathReference() != null) {
            out.put("pathReference", mappingEx.getPathReference());
        }

        if (cause instanceof InvalidFormatException) {
            InvalidFormatException formEx = (InvalidFormatException) cause;
            if (formEx.getTargetType() != null) {
                out.put("targetType", formEx.getTargetType().getName());
            }
        } else if (cause instanceof PropertyBindingException) {
            PropertyBindingException bindingEx = (PropertyBindingException) cause;
            if (bindingEx.getPropertyName() != null) {
                out.put("property", bindingEx.getPropertyName());
                out.put("knownProperties", bindingEx.getKnownPropertyIds());
            }
        }
    }

    return out;
}
 
Example #22
Source File: LocalDateTimeDeserTest.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(quote("notalocaldatetime"));
        fail("expected fail");
    } catch (InvalidFormatException e) {
        verifyException(e, "Cannot deserialize value of type");
        verifyException(e, "from String \"");
    }
}
 
Example #23
Source File: YearMonthDeserTest.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadDeserializationAsString01() throws Throwable
{
    try {
        read(quote("notayearmonth"));
        fail("expected DateTimeParseException");
    } catch (InvalidFormatException e) {
        verifyException(e, "could not be parsed");
    }
}
 
Example #24
Source File: HdfsSinkConfigTests.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = InvalidFormatException.class)
public final void invalidCodecValidateTest() throws IOException {
	Map<String, Object> map = new HashMap<String, Object> ();
	map.put("hdfsConfigResources", "core-site.xml");
	map.put("directory", "/foo/bar");
	map.put("filenamePrefix", "prefix");
	map.put("fileExtension", ".txt");
	map.put("compression", "bad value");
	
	HdfsSinkConfig config = HdfsSinkConfig.load(map);
	config.validate();
}
 
Example #25
Source File: HdfsSinkConfigTests.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = InvalidFormatException.class)
public final void invalidCodecValidateTest() throws IOException {
	Map<String, Object> map = new HashMap<String, Object> ();
	map.put("hdfsConfigResources", "core-site.xml");
	map.put("directory", "/foo/bar");
	map.put("filenamePrefix", "prefix");
	map.put("fileExtension", ".txt");
	map.put("compression", "bad value");
	
	HdfsSinkConfig config = HdfsSinkConfig.load(map);
	config.validate();
}
 
Example #26
Source File: ECKeyDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public ECKey deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                return DumpedPrivateKey.fromBase58(null, p.getValueAsString()).getKey();
            } catch (AddressFormatException e) {
                throw new InvalidFormatException(p, "Invalid Key", p.getValueAsString(), ECKey.class);
            }
        default:
            return (ECKey) ctxt.handleUnexpectedToken(ECKey.class, p);
    }
}
 
Example #27
Source File: BlockHexDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Block deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                byte[] payload = HexUtil.hexStringToByteArray(p.getValueAsString()); // convert  to hex
                return context.getParams().getDefaultSerializer().makeBlock(payload);
            } catch (ProtocolException e) {
                throw new InvalidFormatException(p, "Invalid Block", p.getValueAsString(), Block.class);
            }
        default:
            return (Block) ctxt.handleUnexpectedToken(Block.class, p);
    }
}
 
Example #28
Source File: AddressDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Address deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                return Address.fromString(netParams, p.getValueAsString());
            } catch (AddressFormatException e) {
                throw new InvalidFormatException(p, "Invalid Address", p.getValueAsString(), Address.class);
            }
        default:
            return (Address) ctxt.handleUnexpectedToken(Address.class, p);
    }
}
 
Example #29
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private static InvalidFormatException unknownEnumValueException(final JsonParser parser,
                                                                final Schema targetSchema,
                                                                final String symbol) {
    return InvalidFormatException.from(parser,
                                       "Symbol " + symbol + " is not valid for enumeration " + targetSchema.getName(),
                                       symbol,
                                       null);
}
 
Example #30
Source File: DurationDeserializer.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
@Override
public Duration deserialize(final JsonParser p,
                            final DeserializationContext ctx) throws IOException {
    if (VALUE_STRING != p.getCurrentToken()) {
        ctx.reportWrongTokenException(this, VALUE_STRING, "Expected string value for Duration mapping.");
    }
    long result;
    try {
        result = parse(p.getText());
    } catch(final DurationFormatException e) {
        throw InvalidFormatException.from(p, e.getMessage(), e);
    }
    return Duration.ofNanos(result);
}