a9b4337a10caf6fa71f4abb82446f6152b10831c
[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         // With no value, we depend on the Tomcat/Jboss/Jetty/etc timeout value for asynchronous requests.
13         // Spring will answer after 60 secs with an empty response (by default) and HTTP 503 status (by default) when timeout.
14         private static final long ASYNC_TIMEOUT = 60000;  /* milliseconds */
15
16         
17         @FunctionalInterface
18         public interface DeferredCall<T> {
19                 
20                 public T doCall();
21         }
22         
23         public static final <T> DeferredResult<T> deferredAdapter(CompletableFuture<T> completableFuture) {
24
25         DeferredResult<T> deferredResult = new DeferredResult<>(ASYNC_TIMEOUT);
26
27         completableFuture
28                 .thenAcceptAsync(deferredResult::setResult)
29                 .exceptionally(exception -> {
30                         Throwable realException = launderException(exception);
31
32                                 LOGGER.error("error: ", realException);
33
34                                 deferredResult.setErrorResult(exception);
35                                 return null;
36                         });
37
38         return deferredResult;  
39         }
40         
41         private static final Throwable launderException(Throwable exception) {
42                 return exception.getCause() != null
43                            ? exception.getCause()
44                            : exception;
45         }
46 }