All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.minijax.json.MinijaxJsonReader Maven / Gradle / Ivy

There is a newer version: 0.5.10
Show newest version
package org.minijax.json;

import static javax.ws.rs.core.MediaType.*;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Singleton
@Consumes(APPLICATION_JSON)
public class MinijaxJsonReader implements MessageBodyReader {

    @Inject
    private ObjectMapper objectMapper;


    @Override
    public boolean isReadable(
            final Class type,
            final Type genericType,
            final Annotation[] annotations,
            final MediaType mediaType) {

        return mediaType != null && mediaType.isCompatible(APPLICATION_JSON_TYPE);
    }


    @Override
    public Object readFrom(
            final Class type,
            final Type genericType,
            final Annotation[] annotations,
            final MediaType mediaType,
            final MultivaluedMap httpHeaders,
            final InputStream entityStream)
                    throws IOException {

        try {
            if (genericType != null) {
                return objectMapper.readValue(entityStream, objectMapper.getTypeFactory().constructType(genericType));
            } else {
                return objectMapper.readValue(entityStream, type);
            }
        } catch (final JsonProcessingException ex) {
            throw new BadRequestException(ex.getMessage(), ex);
        }
    }
}