Adam Bien's Weblog

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


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

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
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License