A complete reactive REST service

Here's a complete method in the ForecastResource.java file:

@GET
@Produces(MediaType.APPLICATION_JSON)
public void getLocationsWithTemperature(@Suspended AsyncResponse asyncResponse) {
asyncResponse.setTimeout(5, TimeUnit.MINUTES);

// initial completed stage to reduce all stages into one
CompletionStage<List<Forecast>> initialStage
= CompletableFuture.completedFuture(new ArrayList<>());
CompletionStage<List<Forecast>> finalStage = locations.stream()
// for each location, call a service and return a CompletionStage
.map(location -> {
return temperatureTarget
.resolveTemplate("city", location.getName())
.request()
.rx()
.get(Temperature.class)
.thenApply(temperature -> new Forecast(location, temperature));
})
// reduce stages using thenCombine, which joins 2 stages into 1
.reduce(initialStage,
(combinedStage, forecastStage) -> {
return combinedStage.thenCombine(forecastStage,
(forecasts, forecast) -> {
forecasts.add(forecast);
return forecasts;
});
}, (stage1, stage2) -> null); // a combiner is not needed

// complete the response with forecasts
finalStage.thenAccept(forecasts -> {
asyncResponse.resume(Response.ok(forecasts).build());
})
// handle an exception and complete the response with it
.exceptionally(e -> {
// unwrap the real exception if wrapped in CompletionException)
Throwable cause = (e instanceof CompletionException) ? e.getCause() : e;
asyncResponse.resume(cause);
return null;
});
}
..................Content has been hidden....................

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