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

com.jslsolucoes.jax.rs.server.ee.JsonMessageBodyWriter Maven / Gradle / Ivy

There is a newer version: 1.0.32
Show newest version
package com.jslsolucoes.jax.rs.server.ee;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.inject.Inject;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jslsolucoes.jax.rs.provider.se.ObjectMapper;
import com.jslsolucoes.jax.rs.server.ee.annotation.JsonExcludes;

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonMessageBodyWriter implements MessageBodyWriter {

    private ObjectMapper objectMapper;
    private static final Logger logger = LoggerFactory.getLogger(JsonMessageBodyWriter.class);

    @Context
    private ResourceInfo resourceInfo;

    @Deprecated
    public JsonMessageBodyWriter() {
	
    }

    @Inject
    public JsonMessageBodyWriter(ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
    }

    @Override
    public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
	return true;
    }

    @Override
    public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
	    MultivaluedMap httpHeaders, OutputStream entityStream)
	    throws IOException, WebApplicationException {
	Map, Set> exclusions = exclusions();
	logger.debug("writing object {} with exclusions {}",object,exclusions);
	objectMapper.serialize(entityStream, object,exclusions);
    }

    private Map, Set> exclusions() {
	JsonExcludes jsonResponse = searchForAnnotation(JsonExcludes.class);
	if (jsonResponse != null) {
	    return Arrays.asList(jsonResponse.value()).stream().collect(Collectors.toMap(keyMapper -> keyMapper.forClass(),
		    valueMapper -> new HashSet(Arrays.asList(valueMapper.fields()))));
	} else {
	    return null;
	}
    }

    @SuppressWarnings("unchecked")
    private  T searchForAnnotation(Class annotationClazz) {
	Method method = resourceInfo.getResourceMethod();
	if (method != null) {
	    return (T) Arrays.asList(method.getAnnotations()).stream()
		    .filter(annotation -> annotation.annotationType().equals(annotationClazz)).findFirst().orElse(null);
	}
	return null;
    }
}