Async Client

Run
How to run the sample
The source code for this sample can be found in the javaee7-samples GitHub repository. The first thing we need to do is to get the source by downloading the repository and then go into the samples folder:
git clone git://github.com/javaee-samples/javaee7-samples.git
cd javaee7-samples/jaxrs/async-client/
Now we are ready to start testing. You can run all the tests in this sample by executing:
mvn test
Or you can run individual tests by executing one of the following:
mvn test -Dtest=MyResourceTest

Invoke a JAX-RS service via an asynchronous client

  • Specifications in use:
    • JAXRS

    MyResourceTest

    In this sample we’re going to explore how to communicate with a JAX-RS service via an asynchronous invocation from the client.

    First step; we need a service to invoke.

    Let’s create a simple GET method.

    @GET
    public String getList() {
        return response[0];
    }

    For JAX-RS to expose our service we need to provide an implementation of the JAX-RS Application class to define our root path.

    @ApplicationPath("webresources")
    public class MyApplication extends Application {
    
        public MyApplication();
    }

    Since JAX-RS webservices are, well, web related and require a web context, they are required to be deployed within a web archive. By default, JAX-RS will perform autodiscovery of our services. That means there is no need to add a web.xml in this scenario.

    Based on the definition of our @Deployment method, we will be creating and deploying the following archive structure.

    /WEB-INF/
    /WEB-INF/classes/
    /WEB-INF/classes/org/
    /WEB-INF/classes/org/javaee7/jaxrs/
    /WEB-INF/classes/org/javaee7/jaxrs/asyncclient/
    /WEB-INF/classes/org/javaee7/jaxrs/asyncclient/MyResource.class
    /WEB-INF/classes/org/javaee7/jaxrs/asyncclient/MyApplication.class
    @Deployment(testable = false)
    public static WebArchive createDeployment() {
       return ShrinkWrap.create(WebArchive.class)
             .addClasses(MyApplication.class, MyResource.class);
    }

    Before we can invoke our service we need to setup the client.

    @Before
    public void setUpClass() throws MalformedURLException {
        Client client = ClientBuilder.newClient();
        target = client.target(URI.create(new URL(base, "webresources/fruits").toExternalForm()));
    }

    Now we are free to invoke our deployed service by using the JAX-RS client library.

    The asynchronous client library comes with multiple option on how to invoke the methods. First let’s look at using the Future option with access to the complete Response.

    @Test
    public void testPollingResponse() throws InterruptedException, ExecutionException {
        Future<Response> r1 = target.request().async().get(); (1)
        String response = r1.get().readEntity(String.class);  (2)
        assertEquals("apple", response);                      (3)
    }
    1. Build an asynchronous request handler for the Response object

    2. Read the entity from the body of the Response

    3. Validate we got the expected value

    Another possibility is to use the Future option with access to only the Response body.

    @Test
    public void testPollingString() throws InterruptedException, ExecutionException {
        Future<String> r1 = target.request().async().get(String.class); (1)
        String response = r1.get();                                     (2)
        assertEquals("apple", response);                                (3)
    }
    1. Build an asynchronous request handler for the body of the Response

    2. Read the entity directly from the Future

    3. Validate we got the expected value

    You can also register a InvocationCallback and get a callback when the Request is done.

    @Test
    public void testInvocationCallback() throws InterruptedException, ExecutionException {
            target.request().async().get(new InvocationCallback<String>() { (1)
    
                @Override
                public void completed(String r) {                           (2)
                    assertEquals("apple", r);
                }
    
                @Override
                public void failed(Throwable t) {                           (3)
                    fail(t.getMessage());
                }
    
            });
    }
    1. Build an asynchronous request callback for the body of the Response

    2. Called when the Request is completed and our entiy parsed

    3. Called if the Request failed to complete

    Share the Knowledge

    Find this sample useful? Share on

    There's a lot more about JavaEE to cover. If you're ready to learn more, check out the other available samples.

    Help Improve

    Find a bug in the sample? Something missing? You can fix it by editing the source, making the correction and sending a pull request. Or report the problem to the issue tracker

    Recent Changelog

    • Sep 10, 2014: Fix typo and remove not very helpful ' ;) by Max Rydahl Andersen
    • Jul 15, 2014: Removed default header by Roberto Cortez
    • Jul 15, 2014: Removed header license. the licensing is now referenced in the license file in the root of the project by Roberto Cortez
    • Jan 13, 2014: Fix typo in jax-rs::async-client description by Aslak Knutsen
    • Jan 10, 2014: Add description to jax-rs:async-client sample by Aslak Knutsen
    • Dec 03, 2013: Change to use client.target(uri) to be compatible with jax-rs 1.0 by Aslak Knutsen
    • Nov 12, 2013: Convert jax-rs samples to arquillian: async client by Aslak Knutsen
    • Nov 08, 2013: Initializing the client before each test by Arun Gupta
    • Nov 07, 2013: Converting servlet into tests by Arun Gupta
    • Oct 27, 2013: Removing redundant dependencies by Arun Gupta
    How to help improve this sample
    The source code for this sample can be found in the javaee7-samples GitHub repository. The first thing you need to do is to get the source by downloading the repository and then go into the samples folder:
    git clone git://github.com/javaee-samples/javaee7-samples.git
    cd javaee7-samples/jaxrs/async-client/

    Do the changes as you see fit and send a pull request!

    Good Luck!