a2e99206ed86fadb407fbec6271ea53d853d30dd
[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 io.reactivex.Observable;
8 import io.reactivex.Single;
9 import io.reactivex.schedulers.Schedulers;
10
11 public class RxJavaAdapter {
12         private static final Logger LOGGER = LoggerFactory.getLogger(RxJavaAdapter.class);
13         
14         // With no value, we depend on the Tomcat/Jboss/Jetty/etc timeout value for asynchronous requests.
15         // Spring will answer after 60 secs with an empty response (by default) and HTTP 503 status (by default) when timeout.
16         private static final long ASYNC_TIMEOUT = 60000;  /* milliseconds */
17
18         
19         public static final <T> DeferredResult<T> deferredAdapter(Observable<T> observable) {
20
21         DeferredResult<T> deferredResult = new DeferredResult<>(ASYNC_TIMEOUT);
22         
23         observable
24                 .subscribeOn(Schedulers.io())
25                 .subscribe(deferredResult::setResult, exception -> {
26                         Throwable realException = launderException(exception);
27
28                         LOGGER.error("error: ", realException);
29
30                         deferredResult.setErrorResult(realException);
31                         });
32
33         return deferredResult;  
34         }
35         
36         public static final <T> DeferredResult<T> deferredAdapter(Single<T> single) {
37
38         DeferredResult<T> deferredResult = new DeferredResult<>(ASYNC_TIMEOUT);
39
40         single
41                 .subscribeOn(Schedulers.io())
42                 .subscribe(deferredResult::setResult, exception -> {
43                                 Throwable realException = launderException(exception);
44         
45                                 LOGGER.error("error: ", realException);
46
47                         deferredResult.setErrorResult(realException);
48                 });
49
50         return deferredResult;
51         }
52         
53         private static final Throwable launderException(Throwable exception) {
54                 return exception.getCause() != null
55                            ? exception.getCause()
56                            : exception;
57         }
58 }