094d5f0aa0d0c1f774df600efcdb567c8cea19cc
[JavaForFun] /
1 package de.spring.webservices.rest.controller.adapters;
2
3 import java.util.concurrent.CompletableFuture;
4
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7 import org.springframework.web.context.request.async.DeferredResult;
8
9 public class CompletableFutureAdapter {
10         private static final Logger LOGGER = LoggerFactory.getLogger(CompletableFutureAdapter.class);
11
12         /**
13          * 
14          * WHEN EXCEPTION IN setErrorResult, Spring WILL TRIGGER THE Spring Exception Handler AS YOU KNOW IT (I HOPE)
15          * SO, YOU COULD HOOK UP THE HANDLER AND RETURN YOUR CUSTOM MESSAGESS (as usual)
16          * 
17          */
18         
19         // With no value, we depend on the Tomcat/Jboss/Jetty/etc timeout value for asynchronous requests.
20         // Spring will answer after 60 secs with an empty response (by default) and HTTP 503 status (by default) when timeout.
21         private static final long ASYNC_TIMEOUT = 60000;  /* milliseconds */
22
23         
24         @FunctionalInterface
25         public interface DeferredCall<T> {
26                 
27                 public T doCall();
28         }
29         
30         
31         public static final <T> DeferredResult<T> callAdapter(DeferredCall<T> deferredCall) {
32                 
33         DeferredResult<T> deferredResult = new DeferredResult<>(ASYNC_TIMEOUT);
34         CompletableFuture
35                 .supplyAsync(deferredCall::doCall)
36                 .thenAcceptAsync(deferredResult::setResult)
37                 .exceptionally(exception -> {
38                         
39                         LOGGER.error("findById error: ", exception);
40                         
41                         deferredResult.setErrorResult(exception);
42                         
43                         return null;
44                 });
45         
46         return deferredResult;  
47         }
48         
49 }