4191239f4a3ed1a455bdc3e2f8f6dea82e05765a
[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
24         // You'd rather better rely on the server values. IMHO this is something to be controlled
25         // by the server administrator no the developer.
26         // private static final long ASYNC_TIMEOUT = 60000;  /* milliseconds */
27
28         private RxJavaAdapter() {
29                 
30         }
31         
32         public static final <T> DeferredResult<T> deferredAdapter(Observable<T> observable) {
33
34         DeferredResult<T> deferredResult = new DeferredResult<>(/** ASYNC_TIMEOUT **/);
35         
36         observable
37                 .subscribeOn(Schedulers.io())
38                 .subscribe(deferredResult::setResult, exception -> {
39                         Throwable realException = launderException(exception);
40
41                         LOGGER.error("error: ", realException);
42
43                         deferredResult.setErrorResult(realException);
44                         });
45
46         return deferredResult;  
47         }
48         
49         public static final <T> DeferredResult<T> deferredAdapter(Single<T> single) {
50
51         DeferredResult<T> deferredResult = new DeferredResult<>(/** ASYNC_TIMEOUT **/);
52
53         single
54                 .subscribeOn(Schedulers.io())
55                 .subscribe(deferredResult::setResult, exception -> {
56                                 Throwable realException = launderException(exception);
57         
58                                 LOGGER.error("error: ", realException);
59
60                         deferredResult.setErrorResult(realException);
61                 });
62
63         return deferredResult;
64         }
65         
66         private static final Throwable launderException(Throwable exception) {
67                 return exception.getCause() != null
68                            ? exception.getCause()
69                            : exception;
70         }
71 }