类com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException源码实例Demo

下面列出了怎么用com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException的API类实例代码及写法,或者点击链接到github查看源代码。

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);
}
 
源代码2 项目: lams   文件: DeserializationContext.java
/**
 * 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);
}
 
@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;
    }
}
 
源代码4 项目: enkan   文件: SerDesMiddlewareTest.java
@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);
}
 
源代码5 项目: zerocode   文件: ConsumerLocalConfigsWrapTest.java
@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));


}
 
源代码6 项目: Web-API   文件: ErrorHandler.java
@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();
}
 
@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);
}
 
源代码8 项目: staccato   文件: ServerWebInputExceptionHandler.java
@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();
}
 
源代码9 项目: api-layer   文件: PetControllerExceptionHandler.java
/**
 * 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());
}
 
源代码10 项目: act-platform   文件: UnrecognizedPropertyMapper.java
@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();
}
 
源代码11 项目: lams   文件: DeserializationContext.java
/**
 * 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);
    }
}
 
源代码12 项目: OpenLRW   文件: ExceptionHandlerControllerAdvice.java
@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;
}
 
@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();
}
 
源代码14 项目: FROST-Server   文件: CustomEntityDeserializer.java
@Override
public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
    T result;
    try {
        result = clazz.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
        throw new IOException("Error deserializing JSON!", ex);
    }
    // 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 = 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)) {
        while (i.hasNext()) {
            Map.Entry<String, JsonNode> next = i.next();
            String fieldName = next.getKey();
            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) {
        deserialiseProperty(obj, classProperty, properties, mapper, result);
    }
    return result;
}
 
源代码15 项目: halyard   文件: ParseConfigException.java
public ParseConfigException(UnrecognizedPropertyException e) {
  Problem problem =
      new ConfigProblemBuilder(
              Problem.Severity.FATAL,
              "Unrecognized property in your halconfig: " + e.getMessage())
          .build();
  getProblems().add(problem);
}
 
源代码16 项目: raml-module-builder   文件: SchemaMakerTest.java
@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\""));
}
 
源代码17 项目: raml-module-builder   文件: SchemaMakerTest.java
@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\""));
}
 
源代码18 项目: pulsar   文件: NettySourceConfigTest.java
@Test(expectedExceptions = UnrecognizedPropertyException.class)
public void testNettyTcpConfigLoadWithMapWhenInvalidPropertyIsSet() throws IOException {
    Map<String, Object> map = new HashMap<>();
    map.put("invalidProperty", 1);

    NettySourceConfig.load(map);
}
 
源代码19 项目: credhub   文件: BaseCredentialSetRequestTest.java
@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);
}
 
@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();
}
 
@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();
}
 
源代码22 项目: NFVO   文件: GlobalExceptionHandler.java
@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);
}
 
源代码23 项目: osiam   文件: RestExceptionHandler.java
@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());
}
 
@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);
}
 
@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\"])"));
}
 
源代码26 项目: cm_ext   文件: JsonSdlParserTest.java
@Test(expected = UnrecognizedPropertyException.class)
public void testParseUnknownElementStrictly() throws Exception {
  try {
    mapper.setFailOnUnknownProperties(true);
    parser.parse(getSdl("service_unknown_elements.sdl"));
  } finally {
    mapper.setFailOnUnknownProperties(false);
  }
}
 
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);
}
 
源代码28 项目: divolte-collector   文件: ValidatedConfiguration.java
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(", ")));
}
 
源代码29 项目: mrgeo   文件: MrsPyramidMetadataTest.java
@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);
}
 
源代码30 项目: tutorials   文件: UnknownPropertiesUnitTest.java
@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));
}
 
 类方法
 同包方法