Search in sources :

Example 56 with JsonMappingException

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());
    }
}
Also used : RequestFailedException(com.cribbstechnologies.clients.mandrill.exception.RequestFailedException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) BaseMandrillRequest(com.cribbstechnologies.clients.mandrill.model.BaseMandrillRequest) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) Test(org.junit.Test)

Example 57 with JsonMappingException

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;
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JsonToken(com.fasterxml.jackson.core.JsonToken) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) InputFormatException(org.neo4j.server.http.cypher.format.api.InputFormatException) ConnectionException(org.neo4j.server.http.cypher.format.api.ConnectionException)

Example 58 with JsonMappingException

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);
}
Also used : Module(com.fasterxml.jackson.databind.Module) Arrays(java.util.Arrays) JacksonAnnotationIntrospector(com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector) AnnotationIntrospector(com.fasterxml.jackson.databind.AnnotationIntrospector) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleBeanPropertyFilter(com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) SimpleModule(com.fasterxml.jackson.databind.module.SimpleModule) Locale(java.util.Locale) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) Map(java.util.Map) JsonSerializer(com.fasterxml.jackson.databind.JsonSerializer) DeserializerFactoryConfig(com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig) XmlFactory(com.fasterxml.jackson.dataformat.xml.XmlFactory) JsonDeserializer(com.fasterxml.jackson.databind.JsonDeserializer) Path(java.nio.file.Path) IntRange(kotlin.ranges.IntRange) NopAnnotationIntrospector(com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector) TimeZone(java.util.TimeZone) Visibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility) Version(com.fasterxml.jackson.core.Version) SerializerFactoryConfig(com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Test(org.junit.jupiter.api.Test) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) BasicDeserializerFactory(com.fasterxml.jackson.databind.deser.BasicDeserializerFactory) BasicSerializerFactory(com.fasterxml.jackson.databind.ser.BasicSerializerFactory) Optional(java.util.Optional) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonDeserialize(com.fasterxml.jackson.databind.annotation.JsonDeserialize) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) Serializers(com.fasterxml.jackson.databind.ser.Serializers) SimpleType(com.fasterxml.jackson.databind.type.SimpleType) CBORFactory(com.fasterxml.jackson.dataformat.cbor.CBORFactory) AnnotationIntrospectorPair(com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair) ArrayList(java.util.ArrayList) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) Deserializers(com.fasterxml.jackson.databind.deser.Deserializers) ClassSerializer(com.fasterxml.jackson.databind.ser.std.ClassSerializer) DateDeserializers(com.fasterxml.jackson.databind.deser.std.DateDeserializers) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) StreamSupport(java.util.stream.StreamSupport) PropertyAccessor(com.fasterxml.jackson.annotation.PropertyAccessor) SerializerProvider(com.fasterxml.jackson.databind.SerializerProvider) PropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy) DeserializationContext(com.fasterxml.jackson.databind.DeserializationContext) JsonParser(com.fasterxml.jackson.core.JsonParser) FatalBeanException(org.springframework.beans.FatalBeanException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SimpleSerializers(com.fasterxml.jackson.databind.module.SimpleSerializers) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SmileFactory(com.fasterxml.jackson.dataformat.smile.SmileFactory) JsonFilter(com.fasterxml.jackson.annotation.JsonFilter) Paths(java.nio.file.Paths) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) Collections(java.util.Collections) NumberSerializer(com.fasterxml.jackson.databind.ser.std.NumberSerializer) StringUtils(org.springframework.util.StringUtils) AnnotationIntrospectorPair(com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair) NopAnnotationIntrospector(com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector) HashMap(java.util.HashMap) JsonDeserializer(com.fasterxml.jackson.databind.JsonDeserializer) Date(java.util.Date) ClassSerializer(com.fasterxml.jackson.databind.ser.std.ClassSerializer) NumberSerializer(com.fasterxml.jackson.databind.ser.std.NumberSerializer) Deserializers(com.fasterxml.jackson.databind.deser.Deserializers) DateDeserializers(com.fasterxml.jackson.databind.deser.std.DateDeserializers) Serializers(com.fasterxml.jackson.databind.ser.Serializers) SimpleSerializers(com.fasterxml.jackson.databind.module.SimpleSerializers) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Example 59 with JsonMappingException

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);
    }
}
Also used : TreeTraversingParser(com.fasterxml.jackson.databind.node.TreeTraversingParser) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) List(java.util.List) Map(java.util.Map) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException)

Example 60 with JsonMappingException

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);
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) HealthStateView(io.dropwizard.health.HealthStateView) Collection(java.util.Collection) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Aggregations

JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)140 IOException (java.io.IOException)68 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)54 JsonParseException (com.fasterxml.jackson.core.JsonParseException)52 Test (org.junit.Test)31 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)19 HashMap (java.util.HashMap)16 ArrayList (java.util.ArrayList)14 Map (java.util.Map)14 JsonNode (com.fasterxml.jackson.databind.JsonNode)12 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)11 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)10 File (java.io.File)9 InputStream (java.io.InputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 List (java.util.List)7 Writer (org.alfresco.rest.framework.jacksonextensions.JacksonHelper.Writer)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 Response (javax.ws.rs.core.Response)6 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)5