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

The following examples show how to use com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException. 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: LambdaWrapper.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
private void validateModel(final JSONObject modelObject) throws ValidationException, IOException {
    JSONObject resourceSchemaJSONObject = provideResourceSchemaJSONObject();
    if (resourceSchemaJSONObject == null) {
        throw new TerminalException("Unable to validate incoming model as no schema was provided.");
    }

    TypeReference<ResourceT> modelTypeReference = getModelTypeReference();

    // deserialize incoming payload to modelled request
    ResourceT deserializedModel;
    try {
        deserializedModel = this.serializer.deserializeStrict(modelObject.toString(), modelTypeReference);
    } catch (UnrecognizedPropertyException e) {
        throw new ValidationException(String.format("#: extraneous key [%s] is not permitted", e.getPropertyName()),
                                      "additionalProperties", "#");
    }

    JSONObject serializedModel = new JSONObject(this.serializer.serialize(deserializedModel));
    this.validator.validateObject(serializedModel, resourceSchemaJSONObject);
}
 
Example #2
Source File: ErrorHandler.java    From Web-API with MIT License 6 votes vote down vote up
@Override
public Response toResponse(Throwable exception) {
    int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();

    if (exception instanceof WebApplicationException) {
        status = ((WebApplicationException)exception).getResponse().getStatus();
    } else if (exception instanceof UnrecognizedPropertyException) {
        status = Response.Status.BAD_REQUEST.getStatusCode();
    } else {
        // Print the stack trace as this is an "unexpected" exception,
        // and we want to make sure we can track it down
        exception.printStackTrace();
    }

    return Response
            .status(status)
            .entity(new ErrorMessage(status, exception.getMessage()))
            .build();
}
 
Example #3
Source File: ConsumerLocalConfigsWrapTest.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@Test(expected = UnrecognizedPropertyException.class)
public void testDser_UnRecognizedField() throws IOException {
    String json = "{\n" +
            "                \"consumerLocalConfigs\": {\n" +
            "                    \"fileDumpTo\": \"target/temp/demo.txt\",\n" +
            "                    \"commitAsync\":true,\n" +
            "                    \"showRecordsConsumed\":false,\n" +
            "                    \"MAX_NO_OF_RETRY_POLLS_OR_TIME_OUTS\": 5\n" +
            "                }\n" +
            "\n" +
            "            }";

    ConsumerLocalConfigsWrap javaPojo = objectMapper.readValue(json, ConsumerLocalConfigsWrap.class);

    assertThat(javaPojo.getConsumerLocalConfigs().getFileDumpTo(), is("target/temp/demo.txt"));
    assertThat(javaPojo.getConsumerLocalConfigs().getShowRecordsConsumed(), is(false));


}
 
Example #4
Source File: UnifiedPushMessageTest.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: DeserializationContext.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method that deserializers should call if they encounter an unrecognized
 * property (and once that is not explicitly designed as ignorable), to
 * inform possibly configured {@link DeserializationProblemHandler}s and
 * let it handle the problem.
 * 
 * @return True if there was a configured problem handler that was able to handle the
 *   problem
 */
public boolean handleUnknownProperty(JsonParser p, JsonDeserializer<?> deser,
        Object instanceOrClass, String propName)
    throws IOException
{
    LinkedNode<DeserializationProblemHandler> h = _config.getProblemHandlers();
    while (h != null) {
        // Can bail out if it's handled
        if (h.value().handleUnknownProperty(this, p, deser, instanceOrClass, propName)) {
            return true;
        }
        h = h.next();
    }
    // Nope, not handled. Potentially that's a problem...
    if (!isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        p.skipChildren();
        return true;
    }
    // Do we know properties that are expected instead?
    Collection<Object> propIds = (deser == null) ? null : deser.getKnownPropertyNames();
    throw UnrecognizedPropertyException.from(_parser,
            instanceOrClass, propName, propIds);
}
 
Example #6
Source File: ExceptionHandlerControllerAdvice.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public MessageResponse handleHttpMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException e) {
    if (e.getCause() instanceof UnrecognizedPropertyException) {
        return handleUnrecognizedPropertyException(request, (UnrecognizedPropertyException)e.getCause());
    } else {
        MessageResponse response;
        if (e.getCause() instanceof JsonProcessingException) {
            JsonProcessingException jpe = (JsonProcessingException)e.getCause();
            response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, jpe.getOriginalMessage());
        } else {
            response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, e.getMessage());
        }
        log(e, response);
        return response;
    }
}
 
Example #7
Source File: SerDesMiddlewareTest.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void raiseException() {
    assertThatThrownBy(() -> {
        SerDesMiddleware<Object> middleware = builder(new SerDesMiddleware<>())
                .set(SerDesMiddleware::setBodyReaders, jsonProvider)
                .set(SerDesMiddleware::setBodyWriters, jsonProvider)
                .build();

        String body = "{\"a\":1, \"b\":\"ccb\", \"c\": \"This is an unknown property.\"}";
        HttpRequest request = builder(new DefaultHttpRequest())
                .set(HttpRequest::setHeaders, Headers.of("Content-Type", "application/json"))
                .set(HttpRequest::setBody, new ByteArrayInputStream(body.getBytes()))
                .build();

        middleware.deserialize(request, TestDto.class, TestDto.class, new MediaType("application", "json"));
    }).isInstanceOf(UnrecognizedPropertyException.class);
}
 
Example #8
Source File: JsonSdlParserTest.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnrecognizedPropertyException.class)
public void testParseUnknownElementStrictly() throws Exception {
  try {
    mapper.setFailOnUnknownProperties(true);
    parser.parse(getSdl("service_unknown_elements.sdl"));
  } finally {
    mapper.setFailOnUnknownProperties(false);
  }
}
 
Example #9
Source File: SchemaMakerTest.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Test
public void failsWhenGenerateID() throws Exception {
  SchemaMaker schemaMaker = new SchemaMaker("harvard", "circ", TenantOperation.CREATE,
    "mod-foo-0.2.1-SNAPSHOT.2", "mod-foo-18.2.1-SNAPSHOT.2");
  assertThat(assertThrows(UnrecognizedPropertyException.class, () -> {
    schemaMaker.setSchema(schema("templates/db_scripts/schemaGenerateId.json"));
  }).getMessage(), containsString("Unrecognized field \"generateId\""));
}
 
Example #10
Source File: SchemaMakerTest.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Test
public void failsWhenPkColumnName() throws Exception {
  SchemaMaker schemaMaker = new SchemaMaker("harvard", "circ", TenantOperation.CREATE,
    "mod-foo-0.2.1-SNAPSHOT.2", "mod-foo-18.2.1-SNAPSHOT.2");
  assertThat(assertThrows(UnrecognizedPropertyException.class, () -> {
    schemaMaker.setSchema(schema("templates/db_scripts/schemaPkColumnName.json"));
  }).getMessage(), containsString("Unrecognized field \"pkColumnName\""));
}
 
Example #11
Source File: NettySourceConfigTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = UnrecognizedPropertyException.class)
public void testNettyTcpConfigLoadWithMapWhenInvalidPropertyIsSet() throws IOException {
    Map<String, Object> map = new HashMap<>();
    map.put("invalidProperty", 1);

    NettySourceConfig.load(map);
}
 
Example #12
Source File: BaseCredentialSetRequestTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnrecognizedPropertyException.class)
public void whenValueHasUnknownField_throwsException() throws IOException {
  final String json = "{\n"
                      + "  \"name\": \"/example/certificate\",\n"
                      + "  \"type\": \"certificate\",\n"
                      + "  \"metadata\": \"hello\",\n"
                      + "  \"value\": {"
                      + "    \"foo\": \"\""
                      + "  }"
                      + "}";
  deserializeChecked(json, BaseCredentialSetRequest.class);
}
 
Example #13
Source File: UnrecognizedPropertyExceptionMapper.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #14
Source File: UnrecognizedPropertyExceptionMapper.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(UnrecognizedPropertyException e) {
    Status status = Response.Status.BAD_REQUEST;
    
    return Response
            .status(status)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .entity(new Error()
                    .status(Integer.toString(HttpStatusCode.BAD_REQUEST_400))
                    .message(String.format("Property [%s] is not recognized as a valid property", e.getPropertyName()))
                    .code("unrecognizedProperty")
                    )
            .build();
}
 
Example #15
Source File: GlobalExceptionHandler.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: RestExceptionHandler.java    From osiam with MIT License 5 votes vote down vote up
@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());
}
 
Example #17
Source File: MonetaryAmountDeserializer.java    From jackson-datatype-money with MIT License 5 votes vote down vote up
@Override
public M deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
    BigDecimal amount = null;
    CurrencyUnit currency = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        final String field = parser.getCurrentName();

        parser.nextToken();

        if (field.equals(names.getAmount())) {
            amount = 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.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);
}
 
Example #18
Source File: MonetaryAmountDeserializerTest.java    From jackson-datatype-money with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
void shouldFailToDeserializeWithAdditionalProperties(final Class<M> type,
        final Configurer configurer) {
    final ObjectMapper unit = unit(configurer);

    final String content = "{\"amount\":29.95,\"currency\":\"EUR\",\"version\":\"1\"}";

    final JsonProcessingException exception = assertThrows(
            UnrecognizedPropertyException.class, () -> unit.readValue(content, type));

    assertThat(exception.getMessage(), startsWith(
            "Unrecognized field \"version\" (class javax.money.MonetaryAmount), " +
                    "not marked as ignorable (3 known properties: \"amount\", \"currency\", \"formatted\"])"));
}
 
Example #19
Source File: BaseAriAction.java    From ari4java with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void setObjectMapperLessStrict() {
    mapper.addHandler(new DeserializationProblemHandler() {
        @Override
        public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
            Collection<Object> propIds = (deserializer == null) ? null : deserializer.getKnownPropertyNames();
            UnrecognizedPropertyException e = UnrecognizedPropertyException.from(p, beanOrClass, propertyName, propIds);
            logger.warn(e.toString());
            return e.toString().length() > 0;
        }
    });
}
 
Example #20
Source File: AvroGenericRecordMapper.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private static UnrecognizedPropertyException unrecognizedPropertyException(final JsonParser parser,
                                                                           final Schema schema,
                                                                           final String fieldName) {
    final List<Object> fieldNames = schema.getFields()
            .stream()
            .map(Schema.Field::name)
            .collect(Collectors.toList());
    return UnrecognizedPropertyException.from(parser, schema, fieldName, fieldNames);
}
 
Example #21
Source File: ValidatedConfiguration.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private static String messageForUnrecognizedPropertyException(final UnrecognizedPropertyException e) {
    return String.format(
            "%s.%n\tLocation: %s.%n\tConfiguration path to error: '%s'%n\tAvailable properties: %s.",
            e.getOriginalMessage(),
            e.getLocation().getSourceRef(),
            e.getPath().stream()
                       .map(Reference::getFieldName)
                       .collect(Collectors.joining(".")),
            e.getKnownPropertyIds().stream()
                                   .map(Object::toString).map(s -> "'" + s + "'")
                                   .collect(Collectors.joining(", ")));
}
 
Example #22
Source File: MrsPyramidMetadataTest.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: UnknownPropertiesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = UnrecognizedPropertyException.class)
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
    final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
    final ObjectMapper mapper = new ObjectMapper();

    final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);

    assertNotNull(readValue);
    assertThat(readValue.getStringValue(), equalTo("a"));
    assertThat(readValue.isBooleanValue(), equalTo(true));
    assertThat(readValue.getIntValue(), equalTo(1));
}
 
Example #24
Source File: JacksonExceptionsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = UnrecognizedPropertyException.class)
public void givenJsonStringWithExtra_whenDeserializing_thenException() throws IOException {
    final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}";

    final ObjectMapper mapper = new ObjectMapper();
    mapper.reader()
        .forType(User.class)
        .readValue(json);
}
 
Example #25
Source File: ServerWebInputExceptionHandler.java    From staccato with Apache License 2.0 5 votes vote down vote up
@Override
protected String getMessage(ServerWebInputException ex) {

    Throwable t = ex.getCause();
    if (t != null && t.getCause() != null && t.getCause() instanceof UnrecognizedPropertyException) {
        String propertyName = ((UnrecognizedPropertyException) t.getCause()).getPropertyName();
        Collection knownFields = ((UnrecognizedPropertyException) t.getCause()).getKnownPropertyIds();
        return InvalidParameterException.buildMessage(propertyName, knownFields);
    }

    return ex.getMessage();
}
 
Example #26
Source File: PetControllerExceptionHandler.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * The handleUnrecognizedProperty method creates a response when the request body does not correspond to the model object
 *
 * @param exception UnrecognizedPropertyException
 * @return 400 and the message 'Unrecognized field '%s''
 */
@ExceptionHandler(UnrecognizedPropertyException.class)
public ResponseEntity<ApiMessageView> handleUnrecognizedProperty(UnrecognizedPropertyException exception) {
    Message message = messageService.createMessage("org.zowe.apiml.sampleservice.api.petUnrecognizedProperty", exception.getPropertyName());

    return ResponseEntity
        .status(HttpStatus.BAD_REQUEST)
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(message.mapToView());
}
 
Example #27
Source File: UnrecognizedPropertyMapper.java    From act-platform with ISC License 5 votes vote down vote up
@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();
}
 
Example #28
Source File: DeserializationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper method for reporting a problem with unhandled unknown property.
 * 
 * @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)
 *
 * @deprecated Since 2.8 call {@link #handleUnknownProperty} instead
 */
@Deprecated
public void reportUnknownProperty(Object instanceOrClass, String fieldName,
        JsonDeserializer<?> deser)
    throws JsonMappingException
{
    if (isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        // Do we know properties that are expected instead?
        Collection<Object> propIds = (deser == null) ? null : deser.getKnownPropertyNames();
        throw UnrecognizedPropertyException.from(_parser,
                instanceOrClass, fieldName, propIds);
    }
}
 
Example #29
Source File: ExceptionHandlerControllerAdvice.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
@ExceptionHandler(UnrecognizedPropertyException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public MessageResponse handleUnrecognizedPropertyException(final HttpServletRequest request, UnrecognizedPropertyException e) {
    String errorMessage = String.format("Unrecognized property: [%s].", e.getPropertyName());
    MessageResponse response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, errorMessage);
    log(e, response);
    return response;
}
 
Example #30
Source File: UnrecognizedPropertyExceptionMapper.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@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();
}