Home » Java » java – Pass outputstream to javax.ws.rs.core.ResponseBuilder-Exceptionshub

java – Pass outputstream to javax.ws.rs.core.ResponseBuilder-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

My Question is if/how I can pass an OutputStream to a Response-Object in Jax-rs. Here is my (bit unstructured) description of my current setup:

I have a Java based REST service (based on resteasy implementation of Java Jax-rs). The api is accessed using web browser and there is some service in the backend that emits an OutputStream. The result of this OutputStream is offered as a file download. To transport the data from the OutputStream to the Browser I am storing the output of the OutputStream in the filesystem and then I am using a ResponsBuilder and a StreamingOutput to get the data to the browser/user. The file creation is what i want to avoid (Really for no special reason – I just think it is nicer to avoid file creation…). Here is the code that passes the created file to the responsebuilder and delete it afterwards:

// <SNIP>
StreamingOutput fileStream = new StreamingOutput() {
                @Override
                public void write(OutputStream output) throws IOException, WebApplicationException {
                    try {
                        Files.copy(exportedFile.toPath(), output);
                    } catch (NoSuchFileException e) {
                        logger.error("An exception (NoSuchFile) occured. MESSAGE=" + e.getMessage());
                    }
                    finally {
                        Files.delete(exportedFile.toPath());
                    }
                }
            };

response = Response.ok( fileStream , MediaType.APPLICATION_OCTET_STREAM )
                    .header("content-disposition","attachment; filename = download.dat"))
                    .build();

return response;
// <SNIP>
How to&Answers:

While i was somhow fixed on a solution that sounds like “hey Response here’s your outputstream. please pass it to the user and dont forget to close stream later” there seems to be no problem with doing

StreamingOutput fileStream = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {

                myResult.write(output);
                myResult.close();

            }

        };