package jaxrs.prototype.tomcat7; import java.io.IOException; import java.util.concurrent.CountDownLatch; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.xml.bind.annotation.XmlRootElement; import org.glassfish.jersey.server.ChunkedOutput; @Path("/async") public class AsyncPrototype { // http://localhost:9090/jaxrs.prototype/rest/async/hello @GET @Path("/hello") @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello, this is async prototype"; } // http://localhost:9080/jaxrs.prototype/rest/async/create_person/david/chu // curl -X POST -H "Accept:Application/json" http://localhost:9090/jaxrs.prototype.tomcat7/rest/async/create_person/david/chu @POST @Path("/create_person/{first}/{last}") @Produces(MediaType.APPLICATION_JSON) public Person createPerson( @PathParam("first") String first, @PathParam("last") String last) { Person person = new Person(first, last); return person; } // stdbuf -oL curl -iN http://localhost:9090/jaxrs.prototype.tomcat7/rest/async/asynchronous @GET @Path("/asynchronous") @Consumes(MediaType.APPLICATION_JSON) public ChunkedOutput getAsyncResponse() { final CountDownLatch countDownLatch1 = new CountDownLatch(1); final ChunkedOutput output = new ChunkedOutput(String.class); new Thread() { public void run() { try { Thread.sleep(2000); for (int i = 0; i < 20; i++) { Person person = new Person("David",String.valueOf(i)); output.write(person); Thread.sleep(1000); } } catch (Throwable th) { th.printStackTrace(); } finally { try { output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); return output; } }