use of com.fasterxml.jackson.databind.JsonMappingException in project Java-Mandrill-Wrapper by cribbstechnologies.
the class MandrillRESTRequestTest method testPostRequestMapperExceptions.
@Test
public void testPostRequestMapperExceptions() throws ClientProtocolException, IOException {
this.request = new MandrillRESTRequest();
this.request.setHttpClient(this.client);
this.request.setConfig(this.config);
this.request.setObjectMapper(this.mapper);
doThrow(new JsonGenerationException("Mockito!")).when(this.mapper).writeValueAsString(isA(BaseMandrillRequest.class));
try {
this.request.postRequest(this.emptyBaseRequest, "test", null);
fail("Exception not thrown");
} catch (RequestFailedException e) {
assertEquals("Json Generation Exception", e.getMessage());
}
doThrow(new JsonMappingException("Mockito!")).when(this.mapper).writeValueAsString(isA(BaseMandrillRequest.class));
try {
this.request.postRequest(this.emptyBaseRequest, "test", null);
fail("Exception not thrown");
} catch (RequestFailedException e) {
assertEquals("Json Mapping Exception", e.getMessage());
}
}
use of com.fasterxml.jackson.databind.JsonMappingException in project neo4j by neo4j.
the class StatementDeserializer method read.
InputStatement read() {
switch(state) {
case BEFORE_OUTER_ARRAY:
if (!beginsWithCorrectTokens()) {
return null;
}
state = State.IN_BODY;
case IN_BODY:
String statement = null;
Map<String, Object> parameters = null;
List<Object> resultsDataContents = null;
boolean includeStats = false;
JsonToken tok;
try {
while ((tok = parser.nextToken()) != null && tok != END_OBJECT) {
if (tok == END_ARRAY) {
// No more statements
state = State.FINISHED;
return null;
}
parser.nextValue();
String currentName = parser.getCurrentName();
switch(currentName) {
case "statement":
statement = parser.readValueAs(String.class);
break;
case "parameters":
parameters = readMap();
break;
case "resultDataContents":
resultsDataContents = readArray();
break;
case "includeStats":
includeStats = parser.getBooleanValue();
break;
default:
discardValue();
}
}
if (statement == null) {
throw new InputFormatException("No statement provided.");
}
return new InputStatement(statement, parameters == null ? NO_PARAMETERS : parameters, includeStats, ResultDataContent.fromNames(resultsDataContents));
} catch (JsonParseException e) {
throw new InputFormatException("Could not parse the incoming JSON", e);
} catch (JsonMappingException e) {
throw new InputFormatException("Could not map the incoming JSON", e);
} catch (IOException e) {
throw new ConnectionException("An error encountered while reading the inbound entity", e);
}
case FINISHED:
return null;
default:
break;
}
return null;
}
use of com.fasterxml.jackson.databind.JsonMappingException in project spring-framework by spring-projects.
the class Jackson2ObjectMapperBuilderTests method completeSetup.
@Test
void completeSetup() throws JsonMappingException {
NopAnnotationIntrospector introspector = NopAnnotationIntrospector.instance;
Map<Class<?>, JsonDeserializer<?>> deserializerMap = new HashMap<>();
JsonDeserializer<Date> deserializer = new DateDeserializers.DateDeserializer();
deserializerMap.put(Date.class, deserializer);
JsonSerializer<Class<?>> serializer1 = new ClassSerializer();
JsonSerializer<Number> serializer2 = new NumberSerializer(Integer.class);
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json().modules(// Disable well-known modules detection
new ArrayList<>()).serializers(serializer1).serializersByType(Collections.singletonMap(Boolean.class, serializer2)).deserializersByType(deserializerMap).annotationIntrospector(introspector).annotationIntrospector(current -> AnnotationIntrospector.pair(current, introspector)).featuresToEnable(SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.UNWRAP_ROOT_VALUE, JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS).featuresToDisable(MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_FIELDS, JsonParser.Feature.AUTO_CLOSE_SOURCE, JsonGenerator.Feature.QUOTE_FIELD_NAMES).serializationInclusion(JsonInclude.Include.NON_NULL);
ObjectMapper mapper = new ObjectMapper();
builder.configure(mapper);
assertThat(getSerializerFactoryConfig(mapper).hasSerializers()).isTrue();
assertThat(getDeserializerFactoryConfig(mapper).hasDeserializers()).isTrue();
Serializers serializers = getSerializerFactoryConfig(mapper).serializers().iterator().next();
assertThat(serializers.findSerializer(null, SimpleType.construct(Class.class), null)).isSameAs(serializer1);
assertThat(serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)).isSameAs(serializer2);
assertThat(serializers.findSerializer(null, SimpleType.construct(Number.class), null)).isNull();
Deserializers deserializers = getDeserializerFactoryConfig(mapper).deserializers().iterator().next();
assertThat(deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null)).isSameAs(deserializer);
AnnotationIntrospectorPair pair1 = (AnnotationIntrospectorPair) mapper.getSerializationConfig().getAnnotationIntrospector();
AnnotationIntrospectorPair pair2 = (AnnotationIntrospectorPair) mapper.getDeserializationConfig().getAnnotationIntrospector();
assertThat(pair1.allIntrospectors()).containsExactly(introspector, introspector);
assertThat(pair2.allIntrospectors()).containsExactly(introspector, introspector);
assertThat(mapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isTrue();
assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)).isTrue();
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)).isTrue();
assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue();
assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isFalse();
assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse();
assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse();
assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse();
assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)).isFalse();
assertThat(mapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.NON_NULL);
}
use of com.fasterxml.jackson.databind.JsonMappingException in project dropwizard by dropwizard.
the class BaseConfigurationFactory method build.
protected T build(JsonNode node, String path) throws IOException, ConfigurationException {
for (Map.Entry<Object, Object> pref : System.getProperties().entrySet()) {
final String prefName = (String) pref.getKey();
if (prefName.startsWith(propertyPrefix)) {
final String configName = prefName.substring(propertyPrefix.length());
addOverride(node, configName, System.getProperty(prefName));
}
}
try {
final T config = mapper.readValue(new TreeTraversingParser(node, mapper), klass);
validate(path, config);
return config;
} catch (UnrecognizedPropertyException e) {
final List<String> properties = e.getKnownPropertyIds().stream().map(Object::toString).collect(Collectors.toList());
throw ConfigurationParsingException.builder("Unrecognized field").setFieldPath(e.getPath()).setLocation(e.getLocation()).addSuggestions(properties).setSuggestionBase(e.getPropertyName()).setCause(e).build(path);
} catch (InvalidFormatException e) {
final String sourceType = e.getValue().getClass().getSimpleName();
final String targetType = e.getTargetType().getSimpleName();
throw ConfigurationParsingException.builder("Incorrect type of value").setDetail("is of type: " + sourceType + ", expected: " + targetType).setLocation(e.getLocation()).setFieldPath(e.getPath()).setCause(e).build(path);
} catch (JsonMappingException e) {
throw ConfigurationParsingException.builder("Failed to parse configuration").setDetail(e.getMessage()).setFieldPath(e.getPath()).setLocation(e.getLocation()).setCause(e).build(path);
}
}
use of com.fasterxml.jackson.databind.JsonMappingException in project dropwizard by dropwizard.
the class JsonHealthResponseProviderTest method shouldThrowExceptionWhenJsonProcessorExceptionOccurs.
@Test
void shouldThrowExceptionWhenJsonProcessorExceptionOccurs() throws IOException {
// given
final ObjectMapper mapperMock = mock(ObjectMapper.class);
this.jsonHealthResponseProvider = new JsonHealthResponseProvider(healthStatusChecker, healthStateAggregator, mapperMock);
final HealthStateView view = new HealthStateView("foo", true, HealthCheckType.READY, true);
final Map<String, Collection<String>> queryParams = Collections.singletonMap(JsonHealthResponseProvider.NAME_QUERY_PARAM, Collections.singleton(view.getName()));
final JsonMappingException exception = JsonMappingException.fromUnexpectedIOE(new IOException("uh oh"));
// when
when(healthStateAggregator.healthStateView(view.getName())).thenReturn(Optional.of(view));
when(mapperMock.writeValueAsString(any())).thenThrow(exception);
// then
assertThatThrownBy(() -> jsonHealthResponseProvider.healthResponse(queryParams)).isInstanceOf(RuntimeException.class).hasCauseReference(exception);
verifyNoInteractions(healthStatusChecker);
}
Aggregations