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