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