- First, we create a User POJO:
package com.eldermoraes.ch09.async.result;
/**
*
* @author eldermoraes
*/
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name="
+ name + '}';
}
}
- Then we create UserService to emulate a remote slow endpoint:
@Stateless
@Path("userService")
public class UserService {
@GET
public Response userService(){
try {
TimeUnit.SECONDS.sleep(5);
long id = new Date().getTime();
return Response.ok(new User(id, "User " + id)).build();
} catch (InterruptedException ex) {
return
Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(ex).build();
}
}
}
- Now we create an asynchronous client that will reach that endpoint and get the result:
@Stateless
public class AsyncResultClient {
private Client client;
private WebTarget target;
@PostConstruct
public void init() {
client = ClientBuilder.newBuilder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build();
target = client.target("http://localhost:8080/
ch09-async-result/userService");
}
@PreDestroy
public void destroy(){
client.close();
}
public CompletionStage<Response> getResult(){
return
target.request(MediaType.APPLICATION_JSON).rx().get();
}
}
- And finally, we create a service (endpoint) that will use the client to write the result in the response:
@Stateless
@Path("asyncService")
public class AsyncService {
@Inject
private AsyncResultClient client;
@GET
public void asyncService(@Suspended AsyncResponse response)
{
try{
client.getResult().thenApply(this::readResponse)
.thenAccept(response::resume);
} catch(Exception e){
response.resume(Response.status(Response.Status.
INTERNAL_SERVER_ERROR).entity(e).build());
}
}
private String readResponse(Response response) {
return response.readEntity(String.class);
}
}
To run this example, just deploy it in GlassFish 5 and open this URL in your browser:
http://localhost:8080/ch09-async-result/asyncService