TechArtandBeer
TechArtandBeer

Reputation: 41

Play framework 2 java view - Header, body, footer style page building using Promise

I would like to build final page in typical header-body-footer pattern where header, body and footer each coming from different sources. Header and body would typically come from content management system and body lets say would come from REST service.

I would need to make WS call for each of these preferably in asynchronous manner.

How can I write a play controller action which essentially wraps three Promises for each of these call?

Upvotes: 0

Views: 330

Answers (1)

Rich Dougherty
Rich Dougherty

Reputation: 3251

First, start the three WS calls. They will run in parallel.

Promise<WS.Response> header = WS.url("http://source1.com/header").get();
Promise<WS.Response> body   = WS.url("http://source2.com/body").get();
Promise<WS.Response> footer = WS.url("http://source3.com/footer").get();

Next make a Promise that combines all three Responses. By using this combined Promise we will be wait for all three Responses to complete before we start producing a Result.

Promise<List<WS.Response>> headerBodyFooter = Promise.sequence(
  Arrays.asList(new Promise<WS.Response>[] {
    header, body, footer
  })
);

Wait on that the Promise of the three Responses. Once we have three responses we can produce a Result.

Promise<Result> result = headerBodyFooter.map(new Function<List<WS.Response>,Result>() {
  public Result apply(List<WS.Response> responses) {
    WS.Response header = responses.get(0);
    WS.Response body   = responses.get(1);
    WS.Response footer = responses.get(2);
    ...
    ... use header, body and footer to produce a result ...
    ...
    return result;
  }
});

Then return the Promise of a Result we just created from your action.

return result;

Upvotes: 1

Related Questions