Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input and Output binary streams using JERSEY?

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.

like image 926
Tauren Avatar asked Aug 16 '10 18:08

Tauren


1 Answers

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.

like image 135
MikeTheReader Avatar answered Sep 22 '22 21:09

MikeTheReader