I sometimes want to return a large (several MB) binary object as a response from a JAX-RS resource method. I know the size of the object, and I want the Content-Length header to be set on the response, and I don't want chunked transfer encoding to be used.
In Jersey 1.x, I solved this with a custom MessageBodyWriter:
public class Blob {
public InputStream stream;
public long length;
}
@Provider
public class BlobWriter extends MessageBodyWriter<Blob> {
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return Blob.class.isAssignableFrom(type);
}
public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return t.length;
}
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream)
throws java.io.IOException {
org.glassfish.jersey.message.internal.ReaderWriter.writeTo(t.stream, entityStream);
}
}
But this stopped working when I upgraded to Jersey 2.x, since JAX-RS/Jersey 2 does not care about MessageBodyWriter.getSize() anymore. How can I accomplish this with Jersey 2?