Input and Output binary streams using JERSEY?

Tauren picture Tauren · Aug 16, 2010 · Viewed 144.3k times · Source

I'm using Jersey to implement a RESTful API that is primarily retrieve and serve JSON encoded data. But I have some situations where I need to accomplish the following:

  • Export downloadable documents, such as PDF, XLS, ZIP, or other binary files.
  • Retrieve multipart data, such some JSON plus an uploaded XLS file

I have a single-page JQuery-based web client that creates AJAX calls to this web service. At the moment, it doesn't do form submits, and uses GET and POST (with a JSON object). Should I utilize a form post to send data and an attached binary file, or can I create a multipart request with JSON plus binary file?

My application's service layer currently creates a ByteArrayOutputStream when it generates a PDF file. What is the best way to output this stream to the client via Jersey? I've created a MessageBodyWriter, but I don't know how to use it from a Jersey resource. Is that the right approach?

I've been looking through the samples included with Jersey, but haven't found anything yet that illustrates how to do either of these things. If it matters, I'm using Jersey with Jackson to do Object->JSON without the XML step and am not really utilizing JAX-RS.

Answer

MikeTheReader picture MikeTheReader · Aug 17, 2010

I managed to get a ZIP file or a PDF file by extending the StreamingOutput object. Here is some sample code:

@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                PDFGenerator generator = new PDFGenerator(getEntity());
                generator.generatePDF(output);
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}

The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.

Don't know if it's the best way to do it, but it works.