Asynchronous client callbacks

Like the server side, the client API can add asynchronous callbacks too. We can use these callbacks to receive the responses from the server instead of executing the Future.get() method to receive them. Here's a sample of how to register a client-side asynchronous invocation callback:

...
final
AsyncInvoker asyncInvoker = target.request().async();
final MyResult myResponse = new MyResult();
asyncInvoker.get(new InvocationCallback<Response>() {
@Override
public void completed(Response response) {
...
}
@Override
public void failed(Throwable arg0) {
...
}
});

The callback must implement the javax.ws.rs.client.InvocationCallback interface and override two methods:

  • The completed(Response) method is invoked when the operation ends successfully. The resulting response is passed as an attribute of the callback method.
  • The failed(Throwable) method is invoked when the invocation fails, so an exception showing the failure is passed to the method as an attribute.

In this case, we have a generic type for the InvocationCallback, the response. So, the failed method can only be invoked when the invocation has errors because of an internal client-side problem. The failed method cannot be invoked if the server returns an HTTP error code, for example, the 404 error if the requested resource is not found on the server. In such a case, the response can be passed to the complete method of the callback so that it can send the 404 error code. This case happens only using the response directly as generic type. In the next example, an exception is thrown on the invocation callback even if it returns an error not used in HTTP.

Like the synchronous client API, we can directly retrieve the response entity as a Java type without first requesting a response. In an InvocationCallback, we need to set a generic type representing the expected response entity type without declaring the response class. Let's take an example:

asyncInvoker.get(new InvocationCallback<String>() {
@Override
public void completed(String response) {
...
}
@Override
public void failed(Throwable arg0) {
...
}
});

With that, we end the chapter hoping in its usefulness. Java EE 7, along with WildFly, get powerful asynchronous clients and servers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.124.232