Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream an endless InputStream with JAX-RS

I have an endless InputStream with some data, which I want to return in response to a GET HTTP request. I want my web/API client to read from it endlessly. How can I do it with JAX-RS? I'm trying this:

@GET
@Path("/stream")
@Produces(MediaType.TEXT_PLAIN)
public StreamingOutput stream() {
    final InputStream input = // get it
    return new StreamingOutput() {
        @Override
        public void write(OutputStream out) throws IOException {
            while (true) {
                out.write(input.read());
                out.flush();
            }
        }
    };
}

But content doesn't appear for the client. However, if I add OutputStream#close(), the server delivers the content at that very moment. How can I make it truly streamable?

like image 528
yegor256 Avatar asked Apr 18 '13 19:04

yegor256


2 Answers

So, you have flush issues, you could try to get the ServletResponse as the spec says:

The @Context annotation can be used to indicate a dependency on a Servlet-defined resource. A Servlet- based implementation MUST support injection of the following Servlet-defined types: ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse.

An injected HttpServletResponse allows a resource method to commit the HTTP response prior to returning. An implementation MUST check the committed status and only process the return value if the response is not yet committed.

Then flushing everything you can, like this:

@Context
private HttpServletResponse context;

@GET
@Path("/stream")
@Produces(MediaType.TEXT_PLAIN)
public String stream() {
    final InputStream input = // get it
    ServletOutputStream out = context.getOutputStream();
            while (true) {
                out.write(input.read());
                out.flush();
                context.flushBuffer();
            }
    return "";
}
like image 75
Marcos Zolnowski Avatar answered Nov 15 '22 10:11

Marcos Zolnowski


Simply use the StreamingOutput of JAX-RS

@Path("/numbers")
public class NumbersResource {

    @GET
    public Response streamExample(){
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException, WebApplicationException {
                Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                for (int i = 0; i < 10000000 ; i++){
                    writer.write(i + " ");
                }
                writer.flush();
            }
        };
        return Response.ok(stream).build();
    }
}
like image 35
Jeryl Cook Avatar answered Nov 15 '22 11:11

Jeryl Cook