Java EE 7 SDK |
This sample application uses JAX-RS asynchronous features to implement a simple producer/consumer chat.
This sample demonstrates how to use javax.ws.rs.container.AsyncResponse
.
The deployed resource (ChatResource
) contains two asynchronous methods.
These methods have a response annotated with @AsyncResponse
and run
in the suspended mode. In this mode, the response is not returned from the resource method
as a return value but must be resumed by calling the AsyncResponse.resume()
method.
Before the response is resumed, the execution thread is returned back to container.
The resource method that receives messages (ChatResource.getMesssage()
) stores
the asynchronous response in a blocking queue. After the message is sent to server
(ChatResource.posMesssage()
), the asynchronous response of the request that is waiting
for message is taken from the queue and resumed with the message. Instead of keeping messages in
the queue, the queue stores the responses waiting for these messages, and the messages are directly
delivered to these response when they are available.
The front page shows the text input field for a message. Enter a message and click on
POST MESSAGE
. The POST request is sent to the server where it is blocked in the
queue until a message is requested.
After sending a message, click on GET MESSAGE
, which sends a
background asynchronous GET request to the server. This request will be suspended and
resumed later with the message from the POST request that is stored in the blocking queue.
The message is sent back to the browser and displayed in the box below the
GET MESSAGE
button.
If you click the buttons in the opposite order, the GET request is suspended waiting to be resumed by an incoming POST request.
The page also contains the field with the status of an asynchronous queue
that is stored in ChatResource
. This
field is automatically refreshed in short intervals by calling the GET method on
/chat/queue
from ChatResource
.
You can only send one GET and one POST request to the server from the page (the buttons are then disabled). To submit more GET and POST requests, open new browser windows. The screen also contains a log of the asynchronous requests submitted by the browser.
This sample application demonstrates the following key features:
@AsyncResponse
@Path
@Singleton
Perform the following steps to build, deploy, and run the application:
samples_install_dir
is the sample application base directory. Go to: samples_install_dir/javaee7/rest/async-chat
.run
outcome.
mvn clean verify cargo:run
http://localhost:8080/async-chat
.clean
outcome to undeploy the sample application and to remove the temporary directories such as build
and dist
.
mvn clean
If you have problems when running the application, refer to the troubleshooting document.
Copyright © 1997-2013 Oracle and/or its affiliates. All rights reserved.