c451bfbd5b04591f7b44eca761174fb42797d558
[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         public static final <T> DeferredResult<T> deferredAdapter(CompletableFuture<T> completableFuture) {
18
19         DeferredResult<T> deferredResult = new DeferredResult<>(ASYNC_TIMEOUT);
20
21         completableFuture
22                 .thenAcceptAsync(deferredResult::setResult)
23                 .exceptionally(exception -> {
24                         Throwable realException = launderException(exception);
25
26                                 LOGGER.error("error: ", realException);
27
28                                 deferredResult.setErrorResult(exception);
29                                 return null;
30                         });
31
32         return deferredResult;  
33         }
34         
35         private static final Throwable launderException(Throwable exception) {
36                 return exception.getCause() != null
37                            ? exception.getCause()
38                            : exception;
39         }
40 }