001package systems.dmx.topicmaps.provider;
002
003import systems.dmx.topicmaps.ClusterCoords;
004import systems.dmx.core.util.JavaUtils;
005
006import org.codehaus.jettison.json.JSONArray;
007
008import java.io.InputStream;
009import java.io.IOException;
010import java.lang.annotation.Annotation;
011import java.lang.reflect.Type;
012
013import javax.ws.rs.WebApplicationException;
014import javax.ws.rs.core.MediaType;
015import javax.ws.rs.core.MultivaluedMap;
016import javax.ws.rs.ext.MessageBodyReader;
017import javax.ws.rs.ext.Provider;
018
019
020
021// Note: we can't rely on the generic ObjectProvider (Webservice module) as it
022// intantiates a JSONObject but cluster coordinates are serialzed as JSON array.
023// ### TODO: we could serialze cluster coordinates as a JSON object.
024@Provider
025public class ClusterCoordsProvider implements MessageBodyReader<ClusterCoords> {
026
027    // *** MessageBodyReader Implementation ***
028
029    @Override
030    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
031        // Note: unlike equals() isCompatible() ignores parameters like "charset" in "application/json;charset=UTF-8"
032        return type == ClusterCoords.class && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
033    }
034
035    @Override
036    public ClusterCoords readFrom(Class<ClusterCoords> type, Type genericType, Annotation[] annotations,
037            MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
038                                                                throws IOException, WebApplicationException {
039        try {
040            String json = JavaUtils.readText(entityStream);
041            return new ClusterCoords(new JSONArray(json));
042        } catch (Exception e) {
043            throw new RuntimeException("Deserializing a ClusterCoords object failed", e);
044        }
045    }
046}