@ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public XAPIErrorInfo handleHttpMessageNotReadableException(final HttpServletRequest request, HttpMessageNotReadableException e) { if (e.getCause() instanceof UnrecognizedPropertyException) { return this.handleUnrecognizedPropertyException(request, (UnrecognizedPropertyException)e.getCause()); } else { XAPIErrorInfo result; if (e.getCause() instanceof JsonProcessingException) { final JsonProcessingException jpe = (JsonProcessingException)e.getCause(); result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, jpe.getOriginalMessage()); } else { result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, e); } this.logException(e); this.logError(result); return result; } }
@ExceptionHandler({HttpMessageNotReadableException.class, InvalidJsonException.class, InvalidFormatException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) public ResponseError handleInputNotReadableException(Exception exception) { final Throwable cause = exception.getCause() == null ? exception : exception.getCause(); if (cause instanceof UnrecognizedPropertyException) { return constructError("error.invalid_json_key", ((UnrecognizedPropertyException) cause).getPropertyName()); } else if (cause instanceof InvalidTypeIdException || (cause instanceof JsonMappingException && cause.getMessage() .contains("missing property 'type'"))) { return constructError("error.invalid_type_with_set_prompt"); } else if (cause instanceof InvalidFormatException) { for (InvalidFormatException.Reference reference : ((InvalidFormatException) cause) .getPath()) { if ("operations".equals(reference.getFieldName())) { return constructError("error.permission.invalid_operation"); } } } return badRequestResponse(); }
@ExceptionHandler(value = { HttpMessageNotReadableException.class, UnrecognizedPropertyException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody @Override public MessageResource handle(final Exception e) throws Exception { LOGGER.error("Handling message not readable exception", e); MessageResource messageResource = new MessageResource(MessageType.ERROR, e.getMessage()); BaseExceptionHandler exceptionHandler = handlers.get(e.getCause() != null ? e.getCause().getClass().getName() : ""); if (exceptionHandler != null) { messageResource = exceptionHandler.handle(e.getCause()); } return messageResource; }
@Test public void testHandleWithHanglersExceptionHandler() throws Exception { // Given String msg = "msg"; HttpMessageNotReadableException e = new HttpMessageNotReadableException(msg, new UnrecognizedPropertyException(null, null, null, null, null)); MessageResource expected = new MessageResource(MessageType.ERROR, e.getMessage()); // When when(handlers.get(anyString())).thenReturn(exceptionHandler); when(exceptionHandler.handle(Matchers.<Throwable>any())).thenReturn(expected); MessageResource actual = unit.handle(e); // Then verify(handlers).get(e.getCause().getClass().getName()); verify(exceptionHandler).handle(e.getCause()); assertEquals(expected, actual); }
@Test public void testHandle() throws Exception { // Given JsonLocation loc = new JsonLocation(null, 1L, 1, 1, 1); Class<?> clz = UnrecognizedPropertyException.class; Collection<Object> fields = Arrays.asList("field1", "field2"); String propName = "propName"; String message = "message"; UnrecognizedPropertyException e = new UnrecognizedPropertyException(message, loc, clz, propName, fields); MessageResource expected = new UnrecognizedPropertyMessageResource(MessageType.ERROR, "Unrecognized Property sent", propName, fields.stream().map(field -> field.toString()).collect(Collectors.toList())); // When MessageResource actual = unit.handle(e); // Then assertEquals(expected, actual); }
@ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity<ErrorResponse> resolveHttpMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException ex) { StringBuilder description = new StringBuilder(); List<ClientError> clientErrors = Lists.newArrayList(); description.append("Could not read document."); if (ex.getRootCause() instanceof JsonParseException) { description.append(" Json parse not possible.").append(ex.getRootCause().getMessage()); } else if (ex.getMessage().startsWith("Required request body is missing")) { description.append(" Missing request body."); } else if (ex.getRootCause() instanceof UnrecognizedPropertyException) { description.append(" Unrecognized property"); clientErrors.add(ClientError.fromUnrecognizedPropertyException((UnrecognizedPropertyException) ex.getCause())); } return LoggableErrorResponseCreator.create(HttpStatus.BAD_REQUEST) .withDescription(description.toString()) .withClientErrors(clientErrors) .log() .createErrorResponse(); }
@Test public void ignoreWriteonly() throws Exception { WriteMany writeMany = new WriteMany(); writeMany.readWrite = 6; String serialized = Jackson.defaultMapper().writeValueAsString(writeMany); log.debug("serial writeMany {}", serialized); // should silently ignore "someInt" Config passingOverride = ConfigValueFactory.fromAnyRef(true).atPath("addthis.codec.jackson.ignore.write-only"); Jackson.defaultCodec() .withOverrides(passingOverride) .getObjectMapper() .readValue(serialized, WriteMany.class); // should error on "someInt" thrown.expect(UnrecognizedPropertyException.class); Config erroringOverride = ConfigValueFactory.fromAnyRef(false).atPath("addthis.codec.jackson.ignore.write-only"); Jackson.defaultCodec() .withOverrides(erroringOverride) .getObjectMapper() .readValue(serialized, WriteMany.class); }
@Test(expected = UnrecognizedPropertyException.class) public void createBroadcastMessageWithIncorrectSimplePush() throws IOException { final Map<String, Object> container = new LinkedHashMap<>(); final Map<String, Object> messageObject = new LinkedHashMap<>(); messageObject.put("alert", "Howdy"); messageObject.put("sound", "default"); messageObject.put("badge", 2); Map<String, String> data = new HashMap<>(); data.put("someKey", "someValue"); messageObject.put("user-data", data); container.put("message", messageObject); messageObject.put("simplePush", "version=123"); // parse it: parsePushMessage(container); }
public static Error from(JsonMappingException e) { String path = e.getPath().stream().map(x -> x.getFieldName()).collect(Collectors.joining(" -> ")); if (e instanceof InvalidFormatException) { InvalidFormatException ex = (InvalidFormatException) e; return new Error( String.format("Invalid value for %s. Expected value of type %s but got: '%s'", path, ex.getTargetType().getSimpleName(), ex.getValue()), e ); } else if (e instanceof IgnoredPropertyException) { return new Error(String.format("Missing value for %s", path), e); } else if (e instanceof UnrecognizedPropertyException) { return new Error(String.format("Unknown property: %s", path), e); } else { return new Error(String.format("Cannot parse JSON data for property %s", path), e); } }
@ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public XApiErrorInfo handleHttpMessageNotReadableException(final HttpServletRequest request, HttpMessageNotReadableException e) { if (e.getCause() instanceof UnrecognizedPropertyException) { return this.handleUnrecognizedPropertyException(request, (UnrecognizedPropertyException)e.getCause()); } else { XApiErrorInfo result; if (e.getCause() instanceof JsonProcessingException) { final JsonProcessingException jpe = (JsonProcessingException)e.getCause(); result = new XApiErrorInfo(HttpStatus.BAD_REQUEST, request, jpe.getOriginalMessage()); } else { result = new XApiErrorInfo(HttpStatus.BAD_REQUEST, request, e); } this.logException(e); this.logError(result); return result; } }
@Override public Response toResponse(UnrecognizedPropertyException ex) { return ResultStash.builder() .setStatus(Response.Status.PRECONDITION_FAILED) .addFieldError("Unknown JSON field detected.", "unknown.json.field", MapperUtils.printPropertyPath(ex), "") .buildResponse(); }
/** * Handles exception during loading. * Most exceptions are logged and re-thrown as {@link ConfigurationException} * @param e */ private void handleExceptionDuringLoading(IOException e) { if (e instanceof UnrecognizedPropertyException) { LOGGER.warn("Read an unexpected property. Ignoring it.", e); } else if (e instanceof JsonParseException) { throw LOGGER.throwing(Level.ERROR, new ConfigurationException("The config file could not be parsed", e)); } else if (e instanceof JsonMappingException) { throw LOGGER.throwing(Level.ERROR, new ConfigurationException("The config object is corrupt.", e)); } else { throw LOGGER.throwing(Level.ERROR, new ConfigurationException("An error occurred while reading the configuration.", e)); } }
@Override public Response toResponse(JsonMappingException exception) { if(exception instanceof UnrecognizedPropertyException) { return buildResponse(BAD_REQUEST, "Unrecognized property.", Collections.singletonMap("property_name", ((UnrecognizedPropertyException) exception).getPropertyName())); } return buildResponse(BAD_REQUEST, "Mapping error - Some fields are missing."); }
@ExceptionHandler(UnrecognizedPropertyException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public XAPIErrorInfo handleUnrecognizedPropertyException(final HttpServletRequest request, UnrecognizedPropertyException e) { final String errorMessage = String.format("Unrecognized property: [%s].", e.getPropertyName()); final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessage); this.logException(e); this.logError(result); return result; }
@Test public void testUnrecognizedPropertyException() { final UnrecognizedPropertyException format = new UnrecognizedPropertyException(null, "", null, String.class, "property", Collections.emptyList()); format.prependPath(null, "property"); format.prependPath("property", "property2"); final ValidationJsonException validationJsonException = new ValidationJsonException(format); Assert.assertFalse(validationJsonException.getErrors().isEmpty()); Assert.assertEquals("{property2.property=[{rule=Mapping}]}", validationJsonException.getErrors().toString()); }
@Test public void toResponse() { final UnrecognizedPropertyException exception = new UnrecognizedPropertyException(null, "", null, String.class, "property", Collections.emptyList()); exception.prependPath(null, "property"); exception.prependPath("property", "property2"); check(mock(new UnrecognizedPropertyExceptionMapper()).toResponse(exception), 400, "{\"errors\":{\"property2.property\":[{\"rule\":\"Mapping\"}]}}"); }
@Override public Response toResponse(UnrecognizedPropertyException e) { return Response .status(Response.Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON_TYPE) .entity(new ErrorEntity(String.format("Property [%s] is not recognized as a valid property", e.getPropertyName()), HttpStatusCode.BAD_REQUEST_400)) .build(); }
@ExceptionHandler(UnrecognizedPropertyException.class) public void handleError(HttpServletResponse res, UnrecognizedPropertyException e) throws IOException { ObjectMapper mapper = new ObjectMapper(); String error = "Request JSON body contains an unknown property: " + e; res.sendError(HttpStatus.BAD_REQUEST.value(), error); res.getWriter().write(mapper.writeValueAsString(ErrorResult.error(error))); }
@Override public Response toResponse(UnrecognizedPropertyException exception) { return Response .status(Response.Status.BAD_REQUEST) .build(); }
@ExceptionHandler({UnrecognizedPropertyException.class, MissingPathVariableException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public JSONError unrecognizedProperty(Exception e) { log.warn(e.getMessage(), e); return JSONError.badRequest(); }
@Test(expected = UnrecognizedPropertyException.class) public void whenValueHasUnknownField_throwsException() throws IOException { String json = "{\n" + " \"name\": \"/example/certificate\",\n" + " \"type\": \"certificate\",\n" + " \"value\": {" + " \"foo\": \"\"" + " }" + "}"; deserializeChecked(json, BaseCredentialSetRequest.class); }
@ExceptionHandler({ BadRequestException.class, BadFormatException.class, NetworkServiceIntegrityException.class, WrongStatusException.class, UnrecognizedPropertyException.class, VimException.class, CyclicDependenciesException.class, WrongAction.class, PasswordWeakException.class, AlreadyExistingException.class, IncompatibleVNFPackage.class, EntityInUseException.class, org.openbaton.exceptions.EntityUnreachableException.class, org.openbaton.exceptions.MissingParameterException.class, org.openbaton.exceptions.MonitoringException.class, org.openbaton.exceptions.NetworkServiceIntegrityException.class, org.openbaton.exceptions.PluginException.class, org.openbaton.exceptions.VnfmException.class, org.openbaton.exceptions.VimException.class, org.openbaton.exceptions.VimDriverException.class, org.openbaton.exceptions.QuotaExceededException.class, }) @ResponseStatus(value = HttpStatus.BAD_REQUEST) protected @ResponseBody ResponseEntity<Object> handleInvalidRequest( Exception e, WebRequest request) { if (log.isDebugEnabled()) { log.error("Exception was thrown -> Return message: " + e.getMessage(), e); } else { log.error("Exception was thrown -> Return message: " + e.getMessage()); } ExceptionResource exc = new ExceptionResource("Bad Request", e.getMessage()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(e, exc, headers, HttpStatus.UNPROCESSABLE_ENTITY, request); }
/** * TODO - Figure out why this method is not being called */ @ExceptionHandler(UnrecognizedPropertyException.class) public ResponseEntity<?> handleUnrecognizedProperty(UnrecognizedPropertyException ex, HttpServletRequest request) { ErrorResponse response = new ErrorResponse(); response.addFieldError(ex.getPropertyName(), ex.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); }
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) @ExceptionHandler(value = { UnrecognizedPropertyException.class }) @ResponseBody @Override public MessageResource handle(final UnrecognizedPropertyException e) throws Exception { LOG.error("Handling unrecognized exception", e); List<String> fields = e.getKnownPropertyIds().stream().map(property -> property.toString()).collect(Collectors.toList()); return new UnrecognizedPropertyMessageResource(MessageType.ERROR, UNRECOGNIZED_PROPERTY_SENT, e.getPropertyName(), fields); }
@ExceptionHandler(UnrecognizedPropertyException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ErrorResponse handleUnrecognizedProperty(UnrecognizedPropertyException e) { logger.error("Unknown property", e); return produceErrorResponse(e.getMessage(), HttpStatus.CONFLICT, new JsonPropertyMessageTransformer()); }
/** * Test case for {@link SPQRWebSocketServer#run(java.io.InputStream)} being provided a * stream holding a JSON string which does not comply with expected format */ @Test public void testRun_withStreamHoldingInvalidJSONFormat() throws Exception { try { new SPQRWebSocketServer().run(new ByteArrayInputStream("{\"field\":\"value\"}".getBytes())); Assert.fail("Invalid input"); } catch(UnrecognizedPropertyException e) { // expected } }
public static ClientError fromUnrecognizedPropertyException(UnrecognizedPropertyException exception) { ClientError clientError = new ClientError(); clientError.code = "field.unrecognized"; clientError.path = exception.getPropertyName(); return clientError; }
@Override public M deserialize(final JsonParser parser, final DeserializationContext context) throws IOException { NumberValue amount = null; CurrencyUnit currency = null; while (parser.nextToken() != JsonToken.END_OBJECT) { final String field = parser.getCurrentName(); parser.nextToken(); if (field.equals(names.getAmount())) { amount = DefaultNumberValue.of(context.readValue(parser, BigDecimal.class)); } else if (field.equals(names.getCurrency())) { currency = context.readValue(parser, CurrencyUnit.class); } else if (field.equals(names.getFormatted())) { //noinspection UnnecessaryContinue continue; } else if (context.isEnabled(FAIL_ON_UNKNOWN_PROPERTIES)) { throw UnrecognizedPropertyException.from(parser, MonetaryAmount.class, field, Arrays.<Object>asList(names.getAmount(), names.getCurrency(), names.getFormatted())); } else { parser.skipChildren(); } } checkPresent(parser, amount, names.getAmount()); checkPresent(parser, currency, names.getCurrency()); return factory.create(amount, currency); }
@Test public void shouldFailToDeserializeWithAdditionalProperties() throws IOException { final ObjectMapper unit = unit(); final String content = "{\"amount\":29.95,\"currency\":\"EUR\",\"version\":\"1\"}"; exception.expect(UnrecognizedPropertyException.class); exception.expectMessage(startsWith( "Unrecognized field \"version\" (class javax.money.MonetaryAmount), " + "not marked as ignorable (3 known properties: \"amount\", \"currency\", \"formatted\"])")); unit.readValue(content, type); }
@ExceptionHandler(UnrecognizedPropertyException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ErrorResponse handleUnrecognizedProperty(UnrecognizedPropertyException e) { LOGGER.error("Unknown property", e); return produceErrorResponse(e.getMessage(), HttpStatus.CONFLICT, new JsonPropertyMessageTransformer()); }
public void reportUnknownProperty(Object paramObject, String paramString, JsonDeserializer<?> paramJsonDeserializer) { if (!isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) return; Collection localCollection; if (paramJsonDeserializer == null) localCollection = null; else localCollection = paramJsonDeserializer.getKnownPropertyNames(); throw UnrecognizedPropertyException.from(this._parser, paramObject, paramString, localCollection); }
@Test(expected = UnrecognizedPropertyException.class) public void testParseUnknownElementStrictly() throws Exception { try { mapper.setFailOnUnknownProperties(true); parser.parse(getSdl("service_unknown_elements.sdl")); } finally { mapper.setFailOnUnknownProperties(false); } }
@Test(expected = UnrecognizedPropertyException.class) @Category(UnitTest.class) public void testDeserializeUnknownProperty() throws IOException { final String json = "{\"missing\":null,\"bounds\":{\"n\":41.5,\"e\":25,\"w\":24,\"s\":40.5},\"imageMetadata\":[{\"pixelBounds\":{\"maxY\":728,\"maxX\":728,\"minX\":0,\"minY\":0},\"tileBounds\":{\"maxY\":187,\"maxX\":291,\"minX\":290,\"minY\":185},\"name\":\"9\"}],\"bands\":1,\"defaultValues\":[-32768],\"maxZoomLevel\":3}"; final InputStream is = new ByteArrayInputStream(json.getBytes()); MrsPyramidMetadata.load(is); }
/** * Helper method for reporting a problem with unhandled unknown exception * * @param instanceOrClass Either value being populated (if one has been * instantiated), or Class that indicates type that would be (or * have been) instantiated * @param deser Deserializer that had the problem, if called by deserializer * (or on behalf of one) */ public void reportUnknownProperty(Object instanceOrClass, String fieldName, JsonDeserializer<?> deser) throws JsonMappingException { if (!isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) { return; } // Do we know properties that are expected instead? Collection<Object> propIds = (deser == null) ? null : deser.getKnownPropertyNames(); throw UnrecognizedPropertyException.from(_parser, instanceOrClass, fieldName, propIds); }
@ExceptionHandler(UnrecognizedPropertyException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public XApiErrorInfo handleUnrecognizedPropertyException(final HttpServletRequest request, UnrecognizedPropertyException e) { final String errorMessage = String.format("Unrecognized property: [%s].", e.getPropertyName()); final XApiErrorInfo result = new XApiErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessage); this.logException(e); this.logError(result); return result; }
@Test void strictMapper() throws IOException { Throwable exception = assertThrows(UnrecognizedPropertyException.class, ()-> dataHandler.fromJson(getStringHashMap(), BaseMessageResponse.class)); }
@Override public Response toResponse(final UnrecognizedPropertyException ex) { // Set the JSR-303 error into JSON format. return toResponse(Status.BAD_REQUEST, new ValidationJsonException(ex)); }
@Override public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { Entity result; try { result = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new IOException("Error deserializing JSON!"); } // need to make subclass of this class for every Entity subclass with custom field to get expected class!!! BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz)); ObjectMapper mapper = (ObjectMapper) parser.getCodec(); JsonNode obj = (JsonNode) mapper.readTree(parser); List<BeanPropertyDefinition> properties = beanDescription.findProperties(); Iterator<Map.Entry<String, JsonNode>> i = obj.fields(); // First check if we know all properties that are present. if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) { for (; i.hasNext();) { Map.Entry<String, JsonNode> next = i.next(); String fieldName = next.getKey(); JsonNode field = next.getValue(); Optional<BeanPropertyDefinition> findFirst = properties.stream().filter(p -> p.getName().equals(fieldName)).findFirst(); if (!findFirst.isPresent()) { throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName, parser.getCurrentLocation(), clazz, fieldName, null); } } } for (BeanPropertyDefinition classProperty : properties) { if (obj.has(classProperty.getName())) { // property is present in class and json Annotation annotation = classProperty.getAccessor().getAnnotation(CustomSerialization.class); if (annotation != null) { // property has custom annotation // check if encoding property is also present in json (and also in class itself for sanity reasons) CustomSerialization customAnnotation = (CustomSerialization) annotation; Optional<BeanPropertyDefinition> encodingClassProperty = properties.stream().filter(p -> p.getName().equals(customAnnotation.encoding())).findFirst(); if (!encodingClassProperty.isPresent()) { throw new IOException("Error deserializing JSON as class '" + clazz.toString() + "' \n" + "Reason: field '" + customAnnotation.encoding() + "' specified by annotation as encoding field is not defined in class!"); } String customEncoding = null; if (obj.has(customAnnotation.encoding())) { customEncoding = obj.get(customAnnotation.encoding()).asText(); } Object customDeserializedValue = CustomDeserializationManager.getInstance() .getDeserializer(customEncoding) .deserialize(mapper.writeValueAsString(obj.get(classProperty.getName()))); classProperty.getMutator().setValue(result, customDeserializedValue); } else { // TODO type identificatin is not safe beacuase may ne be backed by field. Rather do multiple checks Object value = mapper.readValue(mapper.writeValueAsString(obj.get(classProperty.getName())), classProperty.getField().getType()); classProperty.getMutator().setValue(result, value); } } } return (T) result; }