Skip to content

Instantly share code, notes, and snippets.

@abhirockzz
Created July 27, 2017 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhirockzz/54375cdf0f29fd5281a49caa9ae01539 to your computer and use it in GitHub Desktop.
Save abhirockzz/54375cdf0f29fd5281a49caa9ae01539 to your computer and use it in GitHub Desktop.
JAX-RS 2.1 - Composing asynchronous server-side pipelines
@Path("cabs")
public class CabBookingResource {
@Resource
ManagedExecutorService mes;
@GET
@Path("{id}")
public CompletionStage<String> getCab(@PathParam("id") final String name) {
System.out.println("HTTP request handled by thread " + Thread.currentThread().getName());
final CompletableFuture<Boolean> validateUserTask = new CompletableFuture<>();
CompletableFuture<String> searchDriverTask = validateUserTask.thenComposeAsync(
new Function<Boolean, CompletionStage<String>>() {
@Override
public CompletionStage<String> apply(Boolean t) {
System.out.println("User validated ? " + t);
return CompletableFuture.supplyAsync(() -> searchDriver(), mes);
}
}, mes);
final CompletableFuture<String> notifyUserTask = searchDriverTask.thenApplyAsync(
(driver) -> notifyUser(driver), mes);
mes.execute(new Runnable() {
@Override
public void run() {
try {
validateUserTask.complete(validateUser(name));
} catch (Exception ex) {
Logger.getLogger(CabBookingResource.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
return notifyUserTask;
}
boolean validateUser(String id) {
System.out.println("searchDriverTask handled by thread " + Thread.currentThread().getName());
System.out.println("validating user " + id);
try {
Thread.sleep(1500);
} catch (InterruptedException ex) {
Logger.getLogger(CabBookingResource.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
String searchDriver() {
System.out.println("searchDriverTask handled by thread " + Thread.currentThread().getName());
try {
Thread.sleep(2500);
} catch (InterruptedException ex) {
Logger.getLogger(CabBookingResource.class.getName()).log(Level.SEVERE, null, ex);
}
return "abhishek";
}
String notifyUser(String info) {
System.out.println("searchDriverTask handled by thread " + Thread.currentThread().getName());
return "Your driver is " + info + " and the OTP is " + (new Random().nextInt(999) + 1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment