下面列出了怎么用com.fasterxml.jackson.databind.exc.InvalidFormatException的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
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);
}
/**
* 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();
}
@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\"}")));
}
@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();
}
@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);
}
@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);
}
@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);
}
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);
}
}
@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();
}
@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity<Map<String, String>> handleInvalidFormatException(InvalidFormatException e, HandlerMethod handlerMethod) {
log.warn("Invalid format exception handled in service: {}, message: {}",
handlerMethod.getMethod().getDeclaringClass().getSimpleName(), e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(getHandlerContent("Invalid initial data"));
}
@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;
}
@Override
public StorageLocation deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
final String valueAsString = p.getValueAsString();
if (valueAsString == null) {
return null;
}
try {
return new StorageLocation(valueAsString);
} catch (final Exception ex) {
throw new InvalidFormatException(p, "Invalid StorageLocation.", valueAsString, StorageLocation.class);
}
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
final HttpMessageNotReadableException ex,
final HttpHeaders headers,
final HttpStatus status,
final WebRequest request) {
if (isInvalidFormatException(ex)) {
return parseInvalidFormatException((InvalidFormatException) ex.getCause());
} else if (isJsonParseException(ex)) {
return parseJsonParseException((JsonParseException) ex.getCause());
} else {
return super.handleHttpMessageNotReadable(ex, headers, status, request);
}
}
private String getErrorMessageForInvalidFormatException(final InvalidFormatException ife) {
logger.warn("Handling exception due to bad data ", ife);
String errorMessage = MESSAGE_NOT_READABLE_ERROR_MESSAGE_PATTERN;
try {
return MessageFormat.format(
MESSAGE_NOT_READABLE_ERROR_MESSAGE_PATTERN,
CollectionUtils.isEmpty(ife.getPath())
?
"" :
ife.getPath().get(0).getFieldName());
} catch (Exception e) {
logger.warn("Exception while constructing error message. Ignoring ", e);
return errorMessage;
}
}
@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);
}
}
/**
* {@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);
}
}
@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);
}
}
@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);
}
}
@JsonCreator
static AAID deserialize(String aaid) throws InvalidFormatException {
try {
return new AAID(aaid);
} catch (IllegalArgumentException e) {
throw new InvalidFormatException(null, "invalid aaid", aaid, AAID.class);
}
}
/**
* The handleInvalidFormatException method creates a response when the field is in the wrong format
*
* @param exception InvalidFormatException
* @return 400 and the message 'Field name has wrong format'
*/
@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity<ApiMessageView> handleInvalidFormatException(InvalidFormatException exception) {
String fieldName = exception.getPath().get(0).getFieldName();
Message message = messageService.createMessage("org.zowe.apiml.sampleservice.api.petInvalidFormatException", fieldName);
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(message.mapToView());
}
public static Date convert(String s) {
try {
return DateUtils.fromISODateString(s);
} catch (InvalidFormatException e) {
throw new RuntimeException("Could not parse date: " + s, e);
}
}
/**
* Converts an ISO formatted Date String to a Java Date ISO format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
*
* @param isoFormattedDate
* @return Date
* @throws com.fasterxml.jackson.databind.exc.InvalidFormatException
*/
public static Date fromISODateString(String isoFormattedDate)
throws com.fasterxml.jackson.databind.exc.InvalidFormatException {
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// set UTC time zone - 'Z' indicates it
isoDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return isoDateFormat.parse(isoFormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", isoFormattedDate, Date.class);
}
}
/**
* Converts an ISO 8601 formatted Date String to a Java Date ISO 8601 format:
* yyyy-MM-dd'T'HH:mm:ss
*
* @param iso8601FormattedDate
* @return Date
* @throws com.fasterxml.jackson.databind.exc.InvalidFormatException
*/
public static Date fromISO8601DateString(String iso8601FormattedDate)
throws com.fasterxml.jackson.databind.exc.InvalidFormatException {
SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// set UTC time zone
iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return iso8601Format.parse(iso8601FormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", iso8601FormattedDate, Date.class);
}
}
/**
* Converts an rfc1123 formatted Date String to a Java Date rfc1123 format: EEE, dd MMM yyyy
* HH:mm:ss zzz
*
* @param rfc1123FormattedDate
* @return Date
* @throws com.fasterxml.jackson.databind.exc.InvalidFormatException
*/
public static Date fromRfc1123DateString(String rfc1123FormattedDate, Locale locale)
throws com.fasterxml.jackson.databind.exc.InvalidFormatException {
SimpleDateFormat rfc1123DateFormat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", locale);
try {
return rfc1123DateFormat.parse(rfc1123FormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", rfc1123FormattedDate, Date.class);
}
}
/**
* Converts an RFC3339 formatted Date String to a Java Date RFC3339 format: yyyy-MM-dd HH:mm:ss
*
* @param rfc3339FormattedDate RFC3339 formatted Date
* @return an {@link Date} object
* @throws InvalidFormatException the RFC3339 formatted Date is invalid or cannot be parsed.
* @see <a href="https://tools.ietf.org/html/rfc3339">The Internet Society - RFC 3339</a>
*/
public static Date fromRfc3339DateString(String rfc3339FormattedDate)
throws InvalidFormatException {
SimpleDateFormat rfc3339DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return rfc3339DateFormat.parse(rfc3339FormattedDate);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", rfc3339FormattedDate, Date.class);
}
}
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
String str = jp.getValueAsString();
try {
return dateFormat.parse(str);
} catch (ParseException e) {
throw new InvalidFormatException("Error parsing as date", str, Date.class);
}
}
public static CoinbaseSpotPriceHistory fromRawString(String spotPriceHistoryString) {
final List<CoinbaseHistoricalSpotPrice> historicalPrices = new ArrayList<>();
// Parse in reverse because they are inconsistent with the number of decimals for the rates
// which makes it difficult to differentiate from the following year. Going in reverse
// we can rely on the comma.
final String entireHistoryString =
new StringBuilder(spotPriceHistoryString).reverse().toString();
final Matcher matcher = historicalRateStringPatternInReverse.matcher(entireHistoryString);
while (matcher.find()) {
final String rateString = new StringBuilder(matcher.group(1)).reverse().toString();
final BigDecimal spotRate = new BigDecimal(rateString);
final String timestampString = new StringBuilder(matcher.group(2)).reverse().toString();
Date timestamp = null;
try {
timestamp = DateUtils.fromISO8601DateString(timestampString);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
final CoinbaseHistoricalSpotPrice historicalSpotPrice =
new CoinbaseHistoricalSpotPrice(timestamp, spotRate);
historicalPrices.add(historicalSpotPrice);
}
Collections.sort(historicalPrices, Collections.reverseOrder());
return new CoinbaseSpotPriceHistory(historicalPrices);
}
@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);
}
@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();
}