下面列出了com.fasterxml.jackson.databind.JsonMappingException#getCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
@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'"));
}
}
@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'"));
}
}
@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'"));
}
}
@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'"));
}
}
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);
}
}
}
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;
}
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;
}
}
@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();
}
@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();
}
@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);
}
}