8d7446fbf3235d340b940002ac58b0c8314900cf
[JavaForFun] /
1 package de.spring.webservices.rest.controller.adapters;
2
3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory;
5 import org.springframework.web.context.request.async.DeferredResult;
6
7 import rx.Observable;
8 import rx.schedulers.Schedulers;
9
10 public class RxJavaAdapter {
11         private static final Logger LOGGER = LoggerFactory.getLogger(RxJavaAdapter.class);
12         
13         // With no value, we depend on the Tomcat/Jboss/Jetty/etc timeout value for asynchronous requests.
14         // Spring will answer after 60 secs with an empty response (by default) and HTTP 503 status (by default) when timeout.
15         private static final long ASYNC_TIMEOUT = 60000;  /* milliseconds */
16
17         
18         @FunctionalInterface
19         public interface DeferredCall<T> {
20                 
21                 public T doCall();
22         }
23         
24         public static final <T> DeferredResult<T> deferredAdapter(Observable<T> observable) {
25
26         DeferredResult<T> deferredResult = new DeferredResult<>(ASYNC_TIMEOUT);
27
28         observable
29                 .subscribeOn(Schedulers.io())
30                 .subscribe(deferredResult::setResult, exception -> {
31                         Throwable realException = launderException(exception);
32
33                         LOGGER.error("error: ", realException);
34
35                         deferredResult.setErrorResult(realException);
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 }