Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close InputStream which fed into Response(jax.rs)

@GET
@Path("/{id}/content")
@Produces({ "application/octet-stream" })
public Response getDocumentContentById(@PathParam("id") String docId) {

    InputStream is = getDocumentStream(); // some method which gives stream
    ResponseBuilder responseBuilder = Response.ok(is);
    responseBuilder.header("Content-Disposition", "attachment; filename=" + fileName);
    return responseBuilder.build();

}

Here how can I close the InputStream is ? If something(jax.rs) closes automatically. Please give me some information. Thank you.

like image 420
Siva R Avatar asked Oct 30 '22 13:10

Siva R


1 Answers

When you're wanting to stream a custom response, the most reliable way I've found is to return an object that contains the InputStream (or which can obtain the stream in some other way at some point), and to define a MessageBodyWriter provider that will do the actual streaming at the right time.

For example, this code is part of Apache Taverna, and it streams back the zipped contents of a directory. All that the main code needs to do to use it is to return a ZipStream as the response (which can be packaged in a Response or not) and to ensure that it is dealing with returning the application/zip content type. The final point to note is that since this is dealing with CXF, you need to manually register the provider; unlike with Glassfish, they are not automatically picked up. This is a good thing in sophisticated scenarios, but it does mean that you need to do the registration.

like image 138
Donal Fellows Avatar answered Nov 15 '22 08:11

Donal Fellows