Take the following steps to complete this recipe:
- First, we create a User POJO:
public class User implements Serializable{
private Long id;
private String name;
public User(long id, String name){
this.id = id;
this.name = 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;
}
}
- Then, we callĀ UserBean to return a User instance:
@Stateless
public class UserBean {
public User getUser() {
long id = new Date().getTime();
try {
TimeUnit.SECONDS.sleep(5);
return new User(id, "User " + id);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
return new User(id, "Error " + id);
}
}
}
- Finally, we create an async endpoint to call the bean:
@Stateless
@Path("asyncService")
public class AsyncService {
@Inject
private UserBean userBean;
@GET
public void asyncService(@Suspended AsyncResponse response)
{
CompletableFuture
.supplyAsync(() -< userBean.getUser())
.thenAcceptAsync((u) -< {
response.resume(Response.ok(u).build());
}).exceptionally((t) -< {
response.resume(Response.status
(Response.Status.
INTERNAL_SERVER_ERROR).entity(t.getMessage())
.build());
return null;
});
}
}
Now, you can try it out by calling the following URL:
http//localhost:8080/ch10-completable-future/asyncService