How it works...

Here, our remote endpoint creates User and converts it into a response entity:

return Response.ok(new User(id, "User " + id)).build();

So, with no effort at all, User is now a JSON object.

Now, let's take a look at the key method in AsyncResultClient:

public CompletionStage<Response> getResult(){
return target.request(MediaType.APPLICATION_JSON).rx().get();
}

The rx() method is part of the Reactive Client API introduced to Jakarta EE 8. We'll discuss Reactive in more detail in Chapter 10, Using Event-Driven Programming to Build Reactive Applications. It basically returns CompletionStageInvoker, which allows you to get CompletionStage<Response> (the returning value for this method).

In other words, this is an asynchronous/non-blocking code that gets results from the remote endpoint.

It should be noted that we use the @Stateless annotation with this client so that we can inject it into our main endpoint:

Inject
private AsyncResultClient client;

Here's our asynchronous method for writing a response:

GET
public void asyncService(@Suspended AsyncResponse response) {
client.getResult().thenApply(this::readResponse)
.thenAccept(response::resume);
}

Note that this is a void method; it doesn't return anything because it returns the result to a callback.

The @Suspended annotation, combined with AsyncResponse, resumes the response once the processing is complete as we use the following beautiful, one-line, Java 8-style code:

client.getResult().thenApply(this::readResponse)
.thenAccept(response::resume);

Before looking into the details, let's just clarify our local readResponse method:

 private String readResponse(Response response) {
return response.readEntity(String.class);
}

It just reads the User entity embedded in Response and transforms it into a String object (a JSON string).

Another way that this one-line code can be written is as follows:

 client.getResult()
.thenApply(r -> readResponse(r))
.thenAccept(s -> response.resume(s));

However, the first way is more concise, less verbose, and more fun!

The key is the resume method from the AsyncReponse object. It writes the response to the callback and returns it to whoever asked for it.

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

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