Sending And Receiving Streams With JAX-RS

Streaming:


import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.StreamingOutput;

@Path("XYZ)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public class XYZResource {

    @GET
    public StreamingOutput streamFile() {
        final Random random = new Random();
        return new StreamingOutput() {
            @Override
            public void write(OutputStream output) 
            throws IOException, WebApplicationException {
                    output.write(/* 42 */);
            }
        };
    }

}


Receiving:



import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
//...
public class XYZResourceIT {

    private Client client;
    private WebTarget tut;

    @Before
    public void init() {
        this.client = ClientBuilder.newClient();
        this.tut = this.client.target("http://...");
    }

    @Test
    public void downloadFileWithDefaultSize() throws IOException {
        int defaultSize = 10;
        try (InputStream stream = this.tut.
                request(MediaType.APPLICATION_OCTET_STREAM).
                get(InputStream.class);) {
            assertNotNull(stream);
            //process stream
        }
    }
    
}

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Do you know if this will do "true" streaming in a sense, that it will start sending data as soon as it will be available, or will it try to get all data ito some kind of buffer and only send it afterwards ?

Posted by Adam on October 13, 2015 at 10:39 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License