下面列出了怎么用com.fasterxml.jackson.databind.exc.InvalidDefinitionException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Helper method called to indicate problem in POJO (serialization) definitions or settings
* regarding specific property (of a type), unrelated to actual JSON content to map.
* Default behavior is to construct and throw a {@link JsonMappingException}.
*
* @since 2.9
*/
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop,
String message, Object... msgArgs) throws JsonMappingException {
message = _format(message, msgArgs);
String propName = "N/A";
if (prop != null) {
propName = _quotedString(prop.getName());
}
String beanDesc = "N/A";
if (bean != null) {
beanDesc = ClassUtil.nameOf(bean.getBeanClass());
}
message = String.format("Invalid definition for property %s (of type %s): %s",
propName, beanDesc, message);
throw InvalidDefinitionException.from(getGenerator(), message, bean, prop);
}
@Test
public void loadConfigWithGroupDots() throws IOException {
Map<String, String> dotReplacement = new HashMap<>();
dotReplacement.put("key map", "key.map");
dotReplacement.put("LG (large group)", "LG (large.group)");
dotReplacement.put("placeholder param group", "placeholder param.group");
String serialized = ConnectionInformationSerializer.INSTANCE.createJsonFromObject(getLargeConfiguration(), EncryptionProvider.DEFAULT_CONTEXT);
for (Map.Entry<String, String> entry : dotReplacement.entrySet()) {
String replaced = serialized.replace(entry.getKey(), entry.getValue());
//stream version
try {
ConnectionInformationSerializer.INSTANCE.loadConfiguration(new ByteArrayInputStream(replaced.getBytes(StandardCharsets.UTF_8)), EncryptionProvider.DEFAULT_CONTEXT);
fail("Groups with dots should not be allowed");
} catch (InvalidDefinitionException e) {
assertEquals(IllegalArgumentException.class, e.getCause().getClass());
}
}
}
private CodecException processException(IOException ex) {
if (ex instanceof InvalidDefinitionException) {
JavaType type = ((InvalidDefinitionException) ex).getType();
return new CodecException("Type definition error: " + type, ex);
}
if (ex instanceof JsonProcessingException) {
String originalMessage = ((JsonProcessingException) ex).getOriginalMessage();
return new DecodingException("JSON decoding error: " + originalMessage, ex);
}
return new DecodingException("I/O error while parsing input stream", ex);
}
@Test
public void testSetterWithoutAnnotationIsInvalid() throws Exception {
assertThatThrownBy(() -> mapper.readValue("{\"fooBar\": \"baz\"}", NoAnnotationInvalidTarget.class))
.isInstanceOf(InvalidDefinitionException.class)
.hasMessageContaining("All setter ({@code set*}) deserialization targets require "
+ "@JsonProperty annotations: setFooBar");
}
private void _reportMissingSetter(JsonParser p, DeserializationContext ctxt) throws IOException
{
final String msg = "No fallback setter/field defined for creator property '"+getName()+"'";
// Hmmmh. Should we return quietly (NOP), or error?
// Perhaps better to throw an exception, since it's generally an error.
if (ctxt != null ) {
ctxt.reportBadDefinition(getType(), msg);
} else {
throw InvalidDefinitionException.from(p, msg, getType());
}
}
/**
* Helper method called to indicate problem in POJO (serialization) definitions or settings
* regarding specific Java type, unrelated to actual JSON content to map.
* Default behavior is to construct and throw a {@link JsonMappingException}.
*
* @since 2.9
*/
public <T> T reportBadTypeDefinition(BeanDescription bean,
String msg, Object... msgArgs) throws JsonMappingException {
String beanDesc = "N/A";
if (bean != null) {
beanDesc = ClassUtil.nameOf(bean.getBeanClass());
}
msg = String.format("Invalid type definition for type %s: %s",
beanDesc, _format(msg, msgArgs));
throw InvalidDefinitionException.from(getGenerator(), msg, bean, null);
}
/**
* @since 2.9
*/
public <T> T reportBadDefinition(JavaType type, String msg, Throwable cause)
throws JsonMappingException {
InvalidDefinitionException e = InvalidDefinitionException.from(getGenerator(), msg, type);
e.initCause(cause);
throw e;
}
/**
* @since 2.9
*/
public <T> T reportBadDefinition(Class<?> raw, String msg, Throwable cause)
throws JsonMappingException {
InvalidDefinitionException e = InvalidDefinitionException.from(getGenerator(), msg, constructType(raw));
e.initCause(cause);
throw e;
}
/**
* Helper method called to indicate problem in POJO (serialization) definitions or settings
* regarding specific Java type, unrelated to actual JSON content to map.
* Default behavior is to construct and throw a {@link JsonMappingException}.
*
* @since 2.9
*/
public <T> T reportBadTypeDefinition(BeanDescription bean,
String msg, Object... msgArgs) throws JsonMappingException {
msg = _format(msg, msgArgs);
String beanDesc = ClassUtil.nameOf(bean.getBeanClass());
msg = String.format("Invalid type definition for type %s: %s", beanDesc, msg);
throw InvalidDefinitionException.from(_parser, msg, bean, null);
}
/**
* Helper method called to indicate problem in POJO (serialization) definitions or settings
* regarding specific property (of a type), unrelated to actual JSON content to map.
* Default behavior is to construct and throw a {@link JsonMappingException}.
*
* @since 2.9
*/
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop,
String msg, Object... msgArgs) throws JsonMappingException {
msg = _format(msg, msgArgs);
String propName = ClassUtil.nameOf(prop);
String beanDesc = ClassUtil.nameOf(bean.getBeanClass());
msg = String.format("Invalid definition for property %s (of type %s): %s",
propName, beanDesc, msg);
throw InvalidDefinitionException.from(_parser, msg, bean, prop);
}
/**
* Helper method for constructing instantiation exception for specified type,
* to indicate problem with physically constructing instance of
* specified class (missing constructor, exception from constructor)
*<p>
* Note that most of the time this method should NOT be called; instead,
* {@link #handleInstantiationProblem} should be called which will call this method
* if necessary.
*/
public JsonMappingException instantiationException(Class<?> instClass, Throwable cause) {
// Most likely problem with Creator definition, right?
JavaType type = constructType(instClass);
String msg = String.format("Cannot construct instance of %s, problem: %s",
ClassUtil.nameOf(instClass), cause.getMessage());
InvalidDefinitionException e = InvalidDefinitionException.from(_parser, msg, type);
e.initCause(cause);
return e;
}
@Test
public void shouldNotSerializeAndDeserialize() throws IOException {
ObjectMapper objectMapperWithoutModule = new ObjectMapper(); // No Module!
final SharedSecretContainer expectedContainer = ImmutableSharedSecretContainer.builder()
.sharedSecret(SHARED_SECRET)
.build();
expectedException.expect(InvalidDefinitionException.class);
final String actualJson = objectMapperWithoutModule.writeValueAsString(expectedContainer);
objectMapperWithoutModule.readValue(actualJson, SharedSecretContainer.class);
}
public void testInvalidPropertyMerge() throws Exception
{
ObjectMapper mapper = afterburnerMapperBuilder()
.disable(MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE)
.build();
try {
mapper.readValue("{\"value\":3}", CantMergeInts.class);
fail("Should not pass");
} catch (InvalidDefinitionException e) {
verifyException(e, "cannot be merged");
}
}
@Test
void jacksonShouldThrowWhenDeserializeMatchAllConditionWithMatchingValue() {
String json = "{\"operator\":\"matchAll\", \"matchingValue\":\"matchme\"}";
assertThatThrownBy(() -> OBJECT_MAPPER.readValue(json, Condition.class))
.isInstanceOf(InvalidDefinitionException.class)
.hasMessageContaining("You should not specify a matchingValue with the matchAll operator");
}
@Test
void jacksonShouldThrowWhenDeserializeContainsConditionWithoutMatchingValue() {
String json = "{\"operator\":\"contains\"}";
assertThatThrownBy(() -> OBJECT_MAPPER.readValue(json, Condition.class))
.isInstanceOf(InvalidDefinitionException.class)
.hasMessageContaining("You need to specify a matchingValue with the contains operator");
}
@Test
void deserializeShouldNotBeSupported() {
assertThatThrownBy(() -> JsonGenericSerializer.forModules(WebAdminUserReindexingTaskAdditionalInformationDTO
.serializationModule(new TestId.Factory()))
.withoutNestedType()
.deserialize(serializedAdditionalInformation))
.isInstanceOf(InvalidDefinitionException.class);
}
@Test
void deserializeShouldNotBeSupported() {
assertThatThrownBy(() -> JsonGenericSerializer.forModules(WebAdminSingleMailboxReindexingTaskAdditionalInformationDTO
.serializationModule(new TestId.Factory()))
.withoutNestedType()
.deserialize(serializedAdditionalInformation))
.isInstanceOf(InvalidDefinitionException.class);
}
@Test
void deserializeErrorRecoveryShouldNotBeSupported() {
assertThatThrownBy(() -> JsonGenericSerializer.forModules(WebAdminReprocessingContextInformationDTO.WebAdminErrorRecoveryIndexationDTO
.serializationModule(new TestId.Factory()))
.withoutNestedType()
.deserialize(serializedErrorRecoveryAdditionalInformation))
.isInstanceOf(InvalidDefinitionException.class);
}
@Test
void deserializeFullShouldNotBeSupported() {
assertThatThrownBy(() -> JsonGenericSerializer.forModules(WebAdminReprocessingContextInformationDTO.WebAdminFullIndexationDTO
.serializationModule(new TestId.Factory()))
.withoutNestedType()
.deserialize(serializedFullAdditionalInformation))
.isInstanceOf(InvalidDefinitionException.class);
}
/** check that we throw an error for duplicate address groups */
@Test
public void testBookDeserializationDupAddressGroup() throws IOException {
_thrown.expect(InvalidDefinitionException.class);
_thrown.expectMessage("Duplicate");
BatfishObjectMapper.mapper()
.readValue(
readResource("org/batfish/referencelibrary/bookDupAddressGroup.json", UTF_8),
ReferenceBook.class);
}
/** check that we throw an error for a non-existent child address group name */
@Test
public void testBookUndefChildAddressGroup() throws IOException {
_thrown.expect(InvalidDefinitionException.class);
_thrown.expectMessage("Following child address group names are not defined: [ag3]");
BatfishObjectMapper.mapper()
.readValue(
readResource("org/batfish/referencelibrary/bookUndefChildAddressGroup.json", UTF_8),
ReferenceBook.class);
}
/** check that we throw an error when the same name is used in a service object and group */
@Test
public void testBookDeserializationDupServiceName() throws IOException {
_thrown.expect(InvalidDefinitionException.class);
_thrown.expectMessage("Duplicate");
BatfishObjectMapper.mapper()
.readValue(
readResource("org/batfish/referencelibrary/bookDupServiceName.json", UTF_8),
ReferenceBook.class);
}
/** check that we throw an error for undefined address groups */
@Test
public void testBookDeserializationUndefAddressGroup() throws IOException {
_thrown.expect(InvalidDefinitionException.class);
_thrown.expectMessage("Undefined");
BatfishObjectMapper.mapper()
.readValue(
readResource("org/batfish/referencelibrary/bookUndefAddressGroup.json", UTF_8),
ReferenceBook.class);
}
/** check that we throw an error for undefined service name */
@Test
public void testBookDeserializationUndefServiceName() throws IOException {
_thrown.expect(InvalidDefinitionException.class);
_thrown.expectMessage("Undefined");
BatfishObjectMapper.mapper()
.readValue(
readResource("org/batfish/referencelibrary/bookUndefServiceName.json", UTF_8),
ReferenceBook.class);
}
/** check that we barf on duplicate book names */
@Test
public void testLibraryDeserializationDuplicateBooks() throws IOException {
_thrown.expect(InvalidDefinitionException.class);
_thrown.expectMessage("Duplicate");
BatfishObjectMapper.mapper()
.readValue(
readResource("org/batfish/referencelibrary/libraryDuplicateBooks.json", UTF_8),
ReferenceLibrary.class);
}
@Test
public void testSetterWithNonKebabCaseAnnotationIsInvalid() throws Exception {
assertThatThrownBy(() -> mapper.readValue("{\"fooBar\": \"baz\"}", NonKebabCaseAnnotationInvalidTarget.class))
.isInstanceOf(InvalidDefinitionException.class)
.hasMessageContaining("Conjure grammar requires kebab-case field names: fooBar");
}
@Override
public <T> T reportBadDefinition(JavaType type, String msg) throws JsonMappingException {
throw InvalidDefinitionException.from(getGenerator(), msg, type);
}
@Override
public <T> T reportBadDefinition(JavaType type, String msg) throws JsonMappingException {
throw InvalidDefinitionException.from(_parser, msg, type);
}
@ExceptionHandler(InvalidDefinitionException.class)
public ResponseEntity<String> exceptionHandler(final InvalidDefinitionException exception) {
return new ResponseEntity<>(exception.getCause().getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
/**
* Method that deserializer may call if it is called to do an update ("merge")
* but deserializer operates on a non-mergeable type. Although this should
* usually be caught earlier, sometimes it may only be caught during operation
* and if so this is the method to call.
* Note that if {@link MapperFeature#IGNORE_MERGE_FOR_UNMERGEABLE} is enabled,
* this method will simply return null; otherwise {@link InvalidDefinitionException}
* will be thrown.
*
* @since 2.9
*/
public <T> T reportBadMerge(JsonDeserializer<?> deser) throws JsonMappingException
{
if (isEnabled(MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE)) {
return null;
}
JavaType type = constructType(deser.handledType());
String msg = String.format("Invalid configuration: values of type %s cannot be merged", type);
throw InvalidDefinitionException.from(getParser(), msg, type);
}