Java Code Examples for com.fasterxml.jackson.databind.JsonMappingException#getCause()

The following examples show how to use com.fasterxml.jackson.databind.JsonMappingException#getCause() . 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: JsonMappingExceptionMapper.java    From heroic with Apache License 2.0 6 votes vote down vote up
private String constructPath(final JsonMappingException e) {
    final StringBuilder builder = new StringBuilder();

    final Consumer<String> field = name -> {
        if (builder.length() > 0) {
            builder.append(".");
        }

        builder.append(name);
    };

    for (final JsonMappingException.Reference reference : e.getPath()) {
        if (reference.getIndex() >= 0) {
            builder.append("[" + reference.getIndex() + "]");
        } else {
            field.accept(reference.getFieldName());
        }
    }

    if (e.getCause() instanceof Validation.MissingField) {
        final Validation.MissingField f = (Validation.MissingField) e.getCause();
        field.accept(f.getName());
    }

    return builder.toString();
}
 
Example 2
Source File: DefaultServiceSpecTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidDuplicatePodName() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("invalid-pod-name.yml").getFile());
    try {
        DefaultServiceSpec.newGenerator(file, SCHEDULER_CONFIG).build();
        Assert.fail("Expected exception");
    } catch (JsonMappingException e) {
        Assert.assertTrue(e.getCause().toString(), e.getCause() instanceof JsonParseException);
        JsonParseException cause = (JsonParseException) e.getCause();
        Assert.assertTrue(cause.getMessage(), cause.getMessage().contains("Duplicate field 'meta-data'"));
    }
}
 
Example 3
Source File: DefaultServiceSpecTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidDuplicateCount() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("invalid-duplicate-count.yml").getFile());
    try {
        DefaultServiceSpec.newGenerator(file, SCHEDULER_CONFIG).build();
        Assert.fail("Expected exception");
    } catch (JsonMappingException e) {
        Assert.assertTrue(e.getCause().toString(), e.getCause() instanceof JsonParseException);
        JsonParseException cause = (JsonParseException) e.getCause();
        Assert.assertTrue(cause.getMessage().contains("Duplicate field 'count'"));
    }
}
 
Example 4
Source File: DefaultServiceSpecTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidTaskName() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("invalid-task-name.yml").getFile());
    try {
        DefaultServiceSpec.newGenerator(file, SCHEDULER_CONFIG).build();
        Assert.fail("Expected exception");
    } catch (JsonMappingException e) {
        Assert.assertTrue(e.getCause().toString(), e.getCause() instanceof JsonParseException);
        JsonParseException cause = (JsonParseException) e.getCause();
        Assert.assertTrue(cause.getMessage(), cause.getMessage().contains("Duplicate field 'meta-data-task'"));
    }
}
 
Example 5
Source File: DefaultServiceSpecTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidDuplicateResourceSetName() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("invalid-resource-set-name.yml").getFile());
    try {
        DefaultServiceSpec.newGenerator(file, SCHEDULER_CONFIG).build();
        Assert.fail("Expected exception");
    } catch (JsonMappingException e) {
        Assert.assertTrue(e.getCause().toString(), e.getCause() instanceof JsonParseException);
        JsonParseException cause = (JsonParseException) e.getCause();
        Assert.assertTrue(cause.getMessage(),
                cause.getMessage().contains("Duplicate field 'data-store-resources'"));
    }
}
 
Example 6
Source File: TestOffsetDateTimeDeserialization.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
private void expectFailure(String json) throws Exception {
    try {
        READER.readValue(aposToQuotes(json));
        fail("expected JsonMappingException");
    } catch (JsonMappingException e) {
        Throwable t = e.getCause();
        if (t == null) {
            fail("Should have `cause` for exception: "+e);
        }
        if (!(t instanceof DateTimeParseException)) {
            fail("Should have DateTimeParseException as root cause, had: "+t);
        }
    }
}
 
Example 7
Source File: MetricsHttpSink.java    From beam with Apache License 2.0 5 votes vote down vote up
private String serializeMetrics(MetricQueryResults metricQueryResults) throws Exception {
  SimpleModule module = new JodaModule();
  module.addSerializer(new MetricNameSerializer(MetricName.class));
  module.addSerializer(new MetricKeySerializer(MetricKey.class));
  module.addSerializer(new MetricResultSerializer(MetricResult.class));
  objectMapper.registerModule(module);
  objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
  // need to register a filter as soon as @JsonFilter annotation is specified.
  // So specify an pass through filter
  SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAll();
  SimpleFilterProvider filterProvider = new SimpleFilterProvider();
  filterProvider.addFilter("committedMetrics", filter);
  objectMapper.setFilterProvider(filterProvider);
  String result;
  try {
    result = objectMapper.writeValueAsString(metricQueryResults);
  } catch (JsonMappingException exception) {
    if ((exception.getCause() instanceof UnsupportedOperationException)
        && exception.getCause().getMessage().contains("committed metrics")) {
      filterProvider.removeFilter("committedMetrics");
      filter = SimpleBeanPropertyFilter.serializeAllExcept("committed");
      filterProvider.addFilter("committedMetrics", filter);
      result = objectMapper.writeValueAsString(metricQueryResults);
    } else {
      throw exception;
    }
  }
  return result;
}
 
Example 8
Source File: PhysicalFlowEndpoint.java    From waltz with Apache License 2.0 5 votes vote down vote up
private List<PhysicalFlowUploadCommandResponse> validateUpload(Request request, Response response) throws IOException {
    requireRole(userRoleService, request, SystemRole.LOGICAL_DATA_FLOW_EDITOR);
    try {
        List<PhysicalFlowUploadCommand> commands = Arrays.asList(readBody(request, PhysicalFlowUploadCommand[].class));
        return physicalFlowUploadService.validate(commands);
    } catch (JsonMappingException ex) {
        Throwable cause = ex.getCause();
        if(cause != null) {

            String message = cause.getMessage();

            Matcher match = ERROR_PATTERN.matcher(message);

            String errorMsg = (match.find())
                    ? String.format("Cannot resolve physical flows as the required attributes are missing [%s]", match.group(1))
                    : message;

            int lineNr = ex.getPath().get(0).getIndex() + 1;

            throw new IOException(String.format("%s in line %d",
                    errorMsg,
                    lineNr),
                    cause);
        }
        throw ex;
    }
}
 
Example 9
Source File: IndexV1UpdaterTest.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testIndexV1WithCorruptAppPackageName() throws Throwable {
    try {
        testBadTestyJar("testy.at.or.at_corrupt_app_package_name_index-v1.jar");
    } catch (JsonMappingException e) {
        throw e.getCause();
    }
    fail();
}
 
Example 10
Source File: IndexV1UpdaterTest.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testIndexV1WithCorruptPackageName() throws Throwable {
    try {
        testBadTestyJar("testy.at.or.at_corrupt_package_name_index-v1.jar");
    } catch (JsonMappingException e) {
        throw e.getCause();
    }
    fail();
}
 
Example 11
Source File: PostValidators.java    From teku with Apache License 2.0 4 votes vote down vote up
@OpenApi(
    path = ROUTE,
    method = HttpMethod.POST,
    summary = "Get validators matching specified public keys.",
    tags = {TAG_BEACON},
    description =
        "Returns information about validators that match the list of validator public keys and optional epoch.\n\n"
            + "If no epoch is specified, the validators are queried from the current state.\n\n"
            + "Public keys that do not match a validator are returned without validator information.",
    requestBody =
        @OpenApiRequestBody(
            content = {@OpenApiContent(from = ValidatorsRequest.class)},
            description =
                "```\n{\n  \"epoch\": (uint64),\n  \"pubkeys\": [(Bytes48 as Hex String)]\n}\n```"),
    responses = {
      @OpenApiResponse(
          status = RES_OK,
          content = @OpenApiContent(from = ValidatorWithIndex.class, isArray = true),
          description = "List of validator objects."),
      @OpenApiResponse(status = RES_NO_CONTENT, description = NO_CONTENT_PRE_GENESIS),
      @OpenApiResponse(status = RES_BAD_REQUEST, description = "Invalid body supplied"),
      @OpenApiResponse(status = RES_INTERNAL_ERROR)
    })
@Override
public void handle(Context ctx) throws Exception {
  try {
    ValidatorsRequest request = jsonProvider.jsonToObject(ctx.body(), ValidatorsRequest.class);
    final SafeFuture<Optional<BeaconValidators>> validatorsFuture =
        chainDataProvider.getValidatorsByValidatorsRequest(request);

    if (request.epoch != null && chainDataProvider.isFinalizedEpoch(request.epoch)) {
      handlePossiblyGoneResult(ctx, validatorsFuture, this::processResult);
    } else {
      handlePossiblyMissingResult(ctx, validatorsFuture, this::processResult);
    }
    ctx.header(Header.CACHE_CONTROL, CACHE_NONE);
  } catch (final IllegalArgumentException e) {
    ctx.result(jsonProvider.objectToJSON(new BadRequest(e.getMessage())));
    ctx.status(SC_BAD_REQUEST);
  } catch (JsonMappingException ex) {
    Throwable cause = ex.getCause();
    if (cause instanceof PublicKeyException) {
      ctx.result(
          jsonProvider.objectToJSON(
              new BadRequest("Public key is not valid: " + ex.getMessage())));
    }
    ctx.status(SC_BAD_REQUEST);
  }
}