001package systems.dmx.webservice.provider;
002
003import systems.dmx.core.JSONEnabled;
004
005import java.io.BufferedWriter;
006import java.io.IOException;
007import java.io.OutputStream;
008import java.io.OutputStreamWriter;
009import java.lang.annotation.Annotation;
010import java.lang.reflect.Type;
011import java.util.logging.Logger;
012
013import javax.ws.rs.WebApplicationException;
014import javax.ws.rs.core.MediaType;
015import javax.ws.rs.core.MultivaluedMap;
016import javax.ws.rs.ext.MessageBodyWriter;
017import javax.ws.rs.ext.Provider;
018
019
020
021@Provider
022public class JSONEnabledProvider implements MessageBodyWriter<JSONEnabled> {
023
024    // ---------------------------------------------------------------------------------------------- Instance Variables
025
026    private Logger logger = Logger.getLogger(getClass().getName());
027
028    // -------------------------------------------------------------------------------------------------- Public Methods
029
030    // *** MessageBodyWriter Implementation ***
031
032    @Override
033    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
034        // Note: unlike equals() isCompatible() ignores parameters like "charset" in "application/json;charset=UTF-8"
035        return JSONEnabled.class.isAssignableFrom(type) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
036    }
037
038    @Override
039    public long getSize(JSONEnabled jsonEnabled, Class<?> type, Type genericType, Annotation[] annotations,
040                        MediaType mediaType) {
041        return -1;
042    }
043
044    @Override
045    public void writeTo(JSONEnabled jsonEnabled, Class<?> type, Type genericType, Annotation[] annotations,
046                        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
047                        throws IOException, WebApplicationException {
048        try {
049            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(entityStream));
050            jsonEnabled.toJSON().write(writer);
051            writer.flush();
052        } catch (Exception e) {
053            throw new RuntimeException("Writing message body failed", e);
054        }
055    }
056}