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