Java Reference
In-Depth Information
import
import javax.ws.rs.container.AsyncResponse
javax.ws.rs.container.AsyncResponse ;
import
import javax.ws.rs.container.Suspended
javax.ws.rs.container.Suspended ;
@Path ( "/orders" )
public
public class
class OrderResource
OrderResource {
@POST
@Consumes ( "application/json" )
@Produces ( "application/json" )
public
public void
void submit ( final
final Order order ,
final
final @Suspended AsyncResponse response ) {
new
new Thread () {
public
public void
void run () {
OrderConfirmation confirmation = orderProcessor . process ( order );
response . resume ( order );
}
}. start ();
}
}
In the previous example, the client would just time out. Now, the OrderResource.submit()
method spawns a new thread to handle order submission. This background thread processes
the Order to obtain an OrderConfirmation . It then sends a response back to the client by
calling the AsyncResponse.resume() method, passing in the OrderConfirmation instance.
Invoking resume() in this manner means that it is a successful response. So, a status code of
200 is sent back to the client. Also, because we're passing a Java object, the resume() meth-
od will marshal this object and send it within the HTTP response body. The media type used
is determined by the @Produces annotation placed on the original JAX-RS method. If the
@Produces annotation has more than one value, then the request's Accept header is ex-
amined to pick the returned media type. Basically, this is the same algorithm a regular JAX-
RS method uses to determine the media type.
Alternatively, you can pass resume() a Response object to send the client a more specific
response:
import
import javax.ws.rs.container.AsyncResponse
javax.ws.rs.container.AsyncResponse ;
import
import javax.ws.rs.container.Suspended
javax.ws.rs.container.Suspended ;
@Path ( "/orders" )
public
public class
class OrderResource
OrderResource {
@POST
@Consumes ( "application/json" )
public
public void
void submit ( final
final Order order ,
Search WWH ::




Custom Search