├── .coveralls.yml ├── .gitignore ├── .java-version ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── codequality └── HEADER ├── gradle.properties ├── gradle ├── license.gradle ├── release.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── libraries.gradle └── src ├── main ├── java │ └── io │ │ └── jmnarloch │ │ └── spring │ │ └── boot │ │ └── rxjava │ │ ├── async │ │ ├── DeferredResultObserver.java │ │ ├── ObservableDeferredResult.java │ │ ├── ObservableSseEmitter.java │ │ ├── ResponseBodyEmitterObserver.java │ │ └── SingleDeferredResult.java │ │ ├── config │ │ ├── RxJava.java │ │ └── RxJavaMvcAutoConfiguration.java │ │ └── mvc │ │ ├── ObservableReturnValueHandler.java │ │ └── SingleReturnValueHandler.java └── resources │ └── META-INF │ └── spring.factories └── test └── java └── io └── jmnarloch └── spring └── boot └── rxjava ├── Demo.java ├── async ├── ObservableDeferredResultTest.java ├── ObservableSseEmitterTest.java └── SingleDeferredResultTest.java ├── dto └── EventDto.java └── mvc ├── ObservableReturnValueHandlerTest.java └── SingleReturnValueHandlerTest.java /.coveralls.yml: -------------------------------------------------------------------------------- 1 | repo_token: fuQ2qrzX3quJeykVRIbU3sqRdgyJge6hD -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Gradle template 3 | .gradle 4 | build/ 5 | 6 | # Ignore Gradle GUI config 7 | gradle-app.setting 8 | 9 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 10 | !gradle-wrapper.jar 11 | 12 | 13 | ### NetBeans template 14 | nbproject/private/ 15 | build/ 16 | nbbuild/ 17 | dist/ 18 | nbdist/ 19 | nbactions.xml 20 | nb-configuration.xml 21 | .nb-gradle/ 22 | 23 | 24 | ### JetBrains template 25 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 26 | 27 | *.iml 28 | 29 | ## Directory-based project format: 30 | .idea/ 31 | # if you remove the above rule, at least ignore the following: 32 | 33 | # User-specific stuff: 34 | # .idea/workspace.xml 35 | # .idea/tasks.xml 36 | # .idea/dictionaries 37 | 38 | # Sensitive or high-churn files: 39 | # .idea/dataSources.ids 40 | # .idea/dataSources.xml 41 | # .idea/sqlDataSources.xml 42 | # .idea/dynamic.xml 43 | # .idea/uiDesigner.xml 44 | 45 | # Gradle: 46 | # .idea/gradle.xml 47 | # .idea/libraries 48 | 49 | # Mongo Explorer plugin: 50 | # .idea/mongoSettings.xml 51 | 52 | ## File-based project format: 53 | *.ipr 54 | *.iws 55 | 56 | ## Plugin-specific files: 57 | 58 | # IntelliJ 59 | /out/ 60 | 61 | # mpeltonen/sbt-idea plugin 62 | .idea_modules/ 63 | 64 | # JIRA plugin 65 | atlassian-ide-plugin.xml 66 | 67 | # Crashlytics plugin (for Android Studio and IntelliJ) 68 | com_crashlytics_export_strings.xml 69 | crashlytics.properties 70 | crashlytics-build.properties 71 | 72 | 73 | ### Eclipse template 74 | *.pydevproject 75 | .metadata 76 | .gradle 77 | bin/ 78 | tmp/ 79 | *.tmp 80 | *.bak 81 | *.swp 82 | *~.nib 83 | local.properties 84 | .settings/ 85 | .loadpath 86 | 87 | # Eclipse Core 88 | .project 89 | 90 | # External tool builders 91 | .externalToolBuilders/ 92 | 93 | # Locally stored "Eclipse launch configurations" 94 | *.launch 95 | 96 | # CDT-specific 97 | .cproject 98 | 99 | # JDT-specific (Eclipse Java Development Tools) 100 | .classpath 101 | 102 | # PDT-specific 103 | .buildpath 104 | 105 | # sbteclipse plugin 106 | .target 107 | 108 | # TeXlipse plugin 109 | .texlipse 110 | 111 | 112 | -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 1.8 -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk7 4 | install: 5 | - ./gradlew assemble -PossrhUsername="${ossrhUsername}" -PossrhPassword="${ossrhPassword}" 6 | script: 7 | - ./gradlew check -PossrhUsername="${ossrhUsername}" -PossrhPassword="${ossrhPassword}" 8 | after_success: 9 | - ./gradlew jacocoTestReport coveralls -PossrhUsername="${ossrhUsername}" -PossrhPassword="${ossrhPassword}" 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring MVC RxJava handlers 2 | 3 | > A Spring Boot starter for RxJava integration 4 | 5 | [![Build Status](https://travis-ci.org/jmnarloch/rxjava-spring-boot-starter.svg?branch=master)](https://travis-ci.org/jmnarloch/rxjava-spring-boot-starter) 6 | [![Coverage Status](https://coveralls.io/repos/jmnarloch/rxjava-spring-boot-starter/badge.svg?branch=master&service=github)](https://coveralls.io/github/jmnarloch/rxjava-spring-boot-starter?branch=master) 7 | 8 | ## Setup 9 | 10 | Add the Spring Boot starter to your project: 11 | 12 | ```xml 13 | 14 | io.jmnarloch 15 | rxjava-spring-boot-starter 16 | 2.0.0 17 | 18 | ``` 19 | 20 | Note: 21 | If you need RxJava 1.4.x support use version 1.0.0. For RxJava2 use 2.x. 22 | 23 | ## Usage 24 | 25 | ### Basic 26 | 27 | Registers Spring's MVC return value handlers for `rx.Observable` and `rx.Single` types. You don't need to any longer use 28 | blocking operations or assign the values to DeferredResult or ListenableFuture instead you can declare that your REST 29 | endpoint returns Observable. 30 | 31 | Example: 32 | 33 | ``` 34 | @RestController 35 | public static class InvoiceResource { 36 | 37 | @RequestMapping(method = RequestMethod.GET, value = "/invoices", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 38 | public Observable getInvoices() { 39 | 40 | return Observable.just( 41 | new Invoice("Acme", new Date()), 42 | new Invoice("Oceanic", new Date()) 43 | ); 44 | } 45 | } 46 | ``` 47 | 48 | The `Observable` will wrap any produced results into a list and make it process through Spring's message converters. 49 | In case if you need to return exactly one result you can use `rx.Single` instead. You can think of `rx.Single` 50 | as counterpart of Spring's `DeferredResult` or `ListenableFuture`. Also with `rx.Single`, and unlike with `rx.Observable` 51 | it is possible to return `ResponseEntity` in order to have the control of the HTTP headers or the status code of the 52 | response. 53 | 54 | Note: The `HandlerReturnValueHandler` for Observable uses 'toList' operator to aggregate the results, which 55 | is not workable with really long infinitive running Observables, from which is not possible to unsubscribe. 56 | 57 | In some scenarios when you want to have more control over the async processing you can use either `ObservableDeferredResult` 58 | or `SingleDeferredResult`, those are the specialized implementation of `DeferredResult` allowing for instance of setting 59 | the processing timeout per response. 60 | 61 | ### Server side events 62 | 63 | Spring 4.2 introduced `ResponseBodyEmitter` for long-lived HTTP connections and streaming the response data. One of 64 | available specialized implementations is `ObservableSseEmitter` that allows to send server side event produced 65 | from `rx.Observable`. 66 | 67 | Example: 68 | 69 | ``` 70 | @RestController 71 | public static class Events { 72 | 73 | @RequestMapping(method = RequestMethod.GET, value = "/messages") 74 | public ObservableSseEmitter messages() { 75 | return new ObservableSseEmitter( 76 | Observable.just( 77 | "message 1", "message 2", "message 3" 78 | ) 79 | ); 80 | } 81 | } 82 | ``` 83 | 84 | This will output: 85 | 86 | ``` 87 | data: message 1 88 | 89 | data: message 2 90 | 91 | data: message 3 92 | ``` 93 | 94 | The SSE can be conveniently consumed by a JavaScript client for instance. 95 | 96 | ## Properties 97 | 98 | The only supported property is `rxjava.mvc.enabled` which allows to disable this extension. 99 | 100 | ``` 101 | rxjava.mvc.enabled=true # true by default 102 | ``` 103 | 104 | ## License 105 | 106 | Apache 2.0 107 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | } 6 | 7 | plugins { 8 | id "com.github.hierynomus.license" version "0.11.0" 9 | id 'net.researchgate.release' version '2.1.2' 10 | id 'com.github.kt3k.coveralls' version '2.4.0' 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: "jacoco" 15 | apply plugin: 'idea' 16 | 17 | apply from: 'libraries.gradle' 18 | apply from: 'gradle/license.gradle' 19 | apply from: 'gradle/release.gradle' 20 | 21 | apply plugin: 'findbugs' 22 | apply plugin: 'pmd' 23 | 24 | apply plugin: 'com.github.kt3k.coveralls' 25 | 26 | sourceCompatibility = 1.7 27 | 28 | group = "io.jmnarloch" 29 | archivesBaseName="rxjava-spring-boot-starter" 30 | 31 | ext { 32 | isReleaseVersion = !version.endsWith("SNAPSHOT") 33 | } 34 | 35 | task wrapper(type: Wrapper) { 36 | gradleVersion = '3.2.1' 37 | } 38 | 39 | jar { 40 | manifest { 41 | attributes 'Implementation-Title': 'rxjava-spring-cloud-starter', 42 | 'Implementation-Version': version 43 | } 44 | } 45 | 46 | repositories { 47 | jcenter() 48 | } 49 | 50 | compileJava { 51 | options.fork = true 52 | } 53 | 54 | dependencies { 55 | 56 | compile (libraries.springBootConfigurationProcessor) { 57 | ext.optional = true 58 | } 59 | compile (libraries.springBootWeb) 60 | compile (libraries.rxJava) 61 | 62 | testCompile (libraries.springBootTest) 63 | testCompile (libraries.junit) 64 | testCompile (libraries.mockito) 65 | } 66 | 67 | findbugs { 68 | ignoreFailures = true 69 | } 70 | 71 | jacocoTestReport { 72 | reports { 73 | xml.enabled = true 74 | html.enabled = true 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /codequality/HEADER: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015-${year} the original author or authors 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | #Sun, 27 Nov 2016 18:29:36 -0800 2 | version=2.0.1-SNAPSHOT 3 | -------------------------------------------------------------------------------- /gradle/license.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'license' 2 | 3 | license { 4 | 5 | header rootProject.file('codequality/HEADER') 6 | strictCheck true 7 | skipExistingHeaders true 8 | include "**/*.java" 9 | 10 | ext.year = Calendar.getInstance().get(Calendar.YEAR) 11 | } -------------------------------------------------------------------------------- /gradle/release.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven' 2 | apply plugin: 'signing' 3 | apply plugin: 'net.researchgate.release' 4 | 5 | task javadocJar(type: Jar) { 6 | classifier = 'javadoc' 7 | from javadoc 8 | } 9 | 10 | task sourcesJar(type: Jar) { 11 | classifier = 'sources' 12 | from sourceSets.main.allSource 13 | } 14 | 15 | artifacts { 16 | archives javadocJar, sourcesJar 17 | } 18 | 19 | signing { 20 | required { isReleaseVersion && gradle.taskGraph.hasTask("uploadArchives") } 21 | sign configurations.archives 22 | } 23 | 24 | uploadArchives { 25 | repositories { 26 | mavenDeployer { 27 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 28 | 29 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 30 | authentication(userName: rootProject.hasProperty('ossrhUsername') ? rootProject.ossrhUsername : '', password: rootProject.hasProperty('ossrhPassword') ? rootProject.ossrhPassword : '') 31 | } 32 | 33 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 34 | authentication(userName: rootProject.hasProperty('ossrhUsername') ? rootProject.ossrhUsername : '', password: rootProject.hasProperty('ossrhPassword') ? rootProject.ossrhPassword : '') 35 | } 36 | 37 | pom.project { 38 | name 'rxjava-spring-boot-starter' 39 | packaging 'jar' 40 | description 'Spring Boot Netflix RxJava' 41 | url 'https://github.com/jmnarloch/rxjava-spring-boot-starter' 42 | 43 | scm { 44 | connection 'scm:git:https://github.com/jmnarloch/rxjava-spring-boot-starter.git' 45 | developerConnection 'scm:git:https://github.com/jmnarloch/rxjava-spring-boot-starter.git' 46 | url 'https://github.com/jmnarloch/rxjava-spring-boot-starter.git' 47 | } 48 | 49 | licenses { 50 | license { 51 | name 'The Apache License, Version 2.0' 52 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 53 | } 54 | } 55 | 56 | developers { 57 | developer { 58 | id 'jmnarloch' 59 | name 'Jakub Narloch' 60 | email 'jmnarloch@gmail.com' 61 | } 62 | } 63 | } 64 | } 65 | } 66 | } 67 | 68 | def installer = install.repositories.mavenInstaller 69 | def deployer = uploadArchives.repositories.mavenDeployer 70 | 71 | [installer, deployer]*.pom*.whenConfigured {pom -> 72 | def dependencyMap = project.configurations.compile.dependencies.collectEntries { [it.name, it] } 73 | pom.dependencies.findAll { 74 | def dep = dependencyMap[it.artifactId] 75 | return dep?.hasProperty('optional') && dep.optional 76 | }*.optional = true 77 | } 78 | 79 | release { 80 | tagTemplate = '${version}' 81 | 82 | git { 83 | requireBranch = 'master' 84 | pushToRemote = 'origin' 85 | pushToCurrentBranch = false 86 | } 87 | } 88 | afterReleaseBuild.dependsOn uploadArchives -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmnarloch/rxjava-spring-boot-starter/b1abbd9ae7abc13e5d806de3115f671d88ab6da9/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Nov 27 16:19:20 PST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionSha256Sum=9843a3654d3e57dce54db06d05f18b664b95c22bf90c6becccb61fc63ce60689 7 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /libraries.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | 3 | libraries = [ 4 | 5 | springBootConfigurationProcessor: 'org.springframework.boot:spring-boot-configuration-processor:1.3.1.RELEASE', 6 | 7 | springBootWeb : 'org.springframework.boot:spring-boot-starter-web:1.3.1.RELEASE', 8 | springBootTest : 'org.springframework.boot:spring-boot-starter-test:1.3.1.RELEASE', 9 | 10 | rxJava : 'io.reactivex.rxjava2:rxjava:2.0.0', 11 | 12 | junit : 'junit:junit:4.12', 13 | mockito : 'org.mockito:mockito-all:1.10.19' 14 | ] 15 | } -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/async/DeferredResultObserver.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import io.reactivex.Observable; 19 | import io.reactivex.observers.DisposableObserver; 20 | import org.springframework.web.context.request.async.DeferredResult; 21 | 22 | /** 23 | * A subscriber that sets the single value produced by the {@link Observable} on the {@link DeferredResult}. 24 | * 25 | * @author Jakub Narloch 26 | * @author Robert Danci 27 | * @see DeferredResult 28 | */ 29 | class DeferredResultObserver extends DisposableObserver implements Runnable { 30 | 31 | private final DeferredResult deferredResult; 32 | 33 | public DeferredResultObserver(Observable observable, DeferredResult deferredResult) { 34 | this.deferredResult = deferredResult; 35 | this.deferredResult.onTimeout(this); 36 | this.deferredResult.onCompletion(this); 37 | observable.subscribe(this); 38 | } 39 | 40 | @Override 41 | public void onNext(T value) { 42 | deferredResult.setResult(value); 43 | } 44 | 45 | @Override 46 | public void onError(Throwable e) { 47 | deferredResult.setErrorResult(e); 48 | } 49 | 50 | @Override 51 | public void onComplete() { 52 | } 53 | 54 | @Override 55 | public void run() { 56 | this.dispose(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/async/ObservableDeferredResult.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import org.springframework.util.Assert; 19 | import org.springframework.web.context.request.async.DeferredResult; 20 | import io.reactivex.Observable; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * A specialized {@link DeferredResult} that handles {@link Observable} type. 26 | * 27 | * @author Jakub Narloch 28 | * @see DeferredResult 29 | */ 30 | public class ObservableDeferredResult extends DeferredResult> { 31 | 32 | private static final Object EMPTY_RESULT = new Object(); 33 | 34 | private final DeferredResultObserver> observer; 35 | 36 | public ObservableDeferredResult(Observable observable) { 37 | this(null, EMPTY_RESULT, observable); 38 | } 39 | 40 | public ObservableDeferredResult(long timeout, Observable observable) { 41 | this(timeout, EMPTY_RESULT, observable); 42 | } 43 | 44 | public ObservableDeferredResult(Long timeout, Object timeoutResult, Observable observable) { 45 | super(timeout, timeoutResult); 46 | Assert.notNull(observable, "observable can not be null"); 47 | 48 | observer = new DeferredResultObserver>(observable.toList().toObservable(), this); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/async/ObservableSseEmitter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import org.springframework.http.MediaType; 19 | import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; 20 | import io.reactivex.Observable; 21 | 22 | /** 23 | * A specialized {@link SseEmitter} that handles {@link Observable} types. The emitter subscribes to the 24 | * passed {@link Observable} instance and emits every produced value through {@link #send(Object, MediaType)}. 25 | * 26 | * @author Jakub Narloch 27 | * @see SseEmitter 28 | */ 29 | public class ObservableSseEmitter extends SseEmitter { 30 | 31 | private final ResponseBodyEmitterObserver observer; 32 | 33 | public ObservableSseEmitter(Observable observable) { 34 | this(null, observable); 35 | } 36 | 37 | public ObservableSseEmitter(MediaType mediaType, Observable observable) { 38 | this(null, mediaType, observable); 39 | } 40 | 41 | public ObservableSseEmitter(Long timeout, MediaType mediaType, Observable observable) { 42 | super(timeout); 43 | this.observer = new ResponseBodyEmitterObserver(mediaType, observable, this); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/async/ResponseBodyEmitterObserver.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import io.reactivex.Observable; 19 | import io.reactivex.observers.DisposableObserver; 20 | import org.springframework.http.MediaType; 21 | import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; 22 | 23 | import java.io.IOException; 24 | 25 | 26 | /** 27 | * Subscriber that any value produced by the {@link Observable} into the {@link ResponseBodyEmitter}. 28 | * 29 | * @author Jakub Narloch 30 | */ 31 | class ResponseBodyEmitterObserver extends DisposableObserver implements Runnable { 32 | 33 | private final MediaType mediaType; 34 | 35 | private final ResponseBodyEmitter responseBodyEmitter; 36 | 37 | private boolean completed; 38 | 39 | public ResponseBodyEmitterObserver(MediaType mediaType, Observable observable, ResponseBodyEmitter responseBodyEmitter) { 40 | 41 | this.mediaType = mediaType; 42 | this.responseBodyEmitter = responseBodyEmitter; 43 | this.responseBodyEmitter.onTimeout(this); 44 | this.responseBodyEmitter.onCompletion(this); 45 | observable.subscribe(this); 46 | } 47 | 48 | @Override 49 | public void onNext(T value) { 50 | 51 | try { 52 | if(!completed) { 53 | responseBodyEmitter.send(value, mediaType); 54 | } 55 | } catch (IOException e) { 56 | throw new RuntimeException(e.getMessage(), e); 57 | } 58 | } 59 | 60 | @Override 61 | public void onError(Throwable e) { 62 | responseBodyEmitter.completeWithError(e); 63 | } 64 | 65 | @Override 66 | public void onComplete() { 67 | if(!completed) { 68 | completed = true; 69 | responseBodyEmitter.complete(); 70 | } 71 | } 72 | 73 | @Override 74 | public void run() { 75 | this.dispose(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/async/SingleDeferredResult.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import org.springframework.util.Assert; 19 | import org.springframework.web.context.request.async.DeferredResult; 20 | import io.reactivex.Single; 21 | 22 | /** 23 | * A specialized {@link DeferredResult} that handles {@link Single} return type. 24 | * 25 | * @author Jakub Narloch 26 | * @see DeferredResult 27 | */ 28 | public class SingleDeferredResult extends DeferredResult { 29 | 30 | private static final Object EMPTY_RESULT = new Object(); 31 | 32 | private final DeferredResultObserver observer; 33 | 34 | public SingleDeferredResult(Single single) { 35 | this(null, EMPTY_RESULT, single); 36 | } 37 | 38 | public SingleDeferredResult(long timeout, Single single) { 39 | this(timeout, EMPTY_RESULT, single); 40 | } 41 | 42 | public SingleDeferredResult(Long timeout, Object timeoutResult, Single single) { 43 | super(timeout, timeoutResult); 44 | Assert.notNull(single, "single can not be null"); 45 | 46 | observer = new DeferredResultObserver(single.toObservable(), this); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/config/RxJava.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.config; 17 | 18 | import org.springframework.beans.factory.annotation.Qualifier; 19 | 20 | import java.lang.annotation.Documented; 21 | import java.lang.annotation.ElementType; 22 | import java.lang.annotation.Retention; 23 | import java.lang.annotation.RetentionPolicy; 24 | import java.lang.annotation.Target; 25 | 26 | /** 27 | * A qualifier annotation used for registering beans within this component. 28 | * 29 | * @author Jakub Narloch 30 | */ 31 | @Target({ElementType.TYPE, ElementType.PARAMETER, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) 32 | @Retention(RetentionPolicy.RUNTIME) 33 | @Documented 34 | @Qualifier 35 | public @interface RxJava { 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/config/RxJavaMvcAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.config; 17 | 18 | import io.jmnarloch.spring.boot.rxjava.mvc.ObservableReturnValueHandler; 19 | import io.jmnarloch.spring.boot.rxjava.mvc.SingleReturnValueHandler; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 22 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 23 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 24 | import org.springframework.context.annotation.Bean; 25 | import org.springframework.context.annotation.Configuration; 26 | import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler; 27 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 28 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 29 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 30 | import io.reactivex.Observable; 31 | import io.reactivex.Single; 32 | 33 | import java.util.ArrayList; 34 | import java.util.List; 35 | 36 | /** 37 | * The RxJava Spring MVC integration auto configuration. 38 | * 39 | * @author Jakub Narloch 40 | */ 41 | @Configuration 42 | @ConditionalOnProperty(value = "rxjava.mvc.enabled", matchIfMissing = true) 43 | public class RxJavaMvcAutoConfiguration { 44 | 45 | @Bean 46 | @RxJava 47 | @ConditionalOnMissingBean 48 | @ConditionalOnClass(Observable.class) 49 | public ObservableReturnValueHandler observableReturnValueHandler() { 50 | return new ObservableReturnValueHandler(); 51 | } 52 | 53 | @Bean 54 | @RxJava 55 | @ConditionalOnMissingBean 56 | @ConditionalOnClass(Single.class) 57 | public SingleReturnValueHandler singleReturnValueHandler() { 58 | return new SingleReturnValueHandler(); 59 | } 60 | 61 | @Configuration 62 | public static class RxJavaWebConfiguration { 63 | 64 | @RxJava 65 | @Autowired 66 | private List handlers = new ArrayList(); 67 | 68 | @Bean 69 | public WebMvcConfigurer rxJavaWebMvcConfiguration() { 70 | return new WebMvcConfigurerAdapter() { 71 | @Override 72 | public void addReturnValueHandlers(List returnValueHandlers) { 73 | if (handlers != null) { 74 | returnValueHandlers.addAll(handlers); 75 | } 76 | } 77 | }; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/mvc/ObservableReturnValueHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.mvc; 17 | 18 | import io.jmnarloch.spring.boot.rxjava.async.ObservableDeferredResult; 19 | import org.springframework.core.MethodParameter; 20 | import org.springframework.web.context.request.NativeWebRequest; 21 | import org.springframework.web.context.request.async.WebAsyncUtils; 22 | import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler; 23 | import org.springframework.web.method.support.ModelAndViewContainer; 24 | import io.reactivex.Observable; 25 | 26 | /** 27 | * A specialized {@link AsyncHandlerMethodReturnValueHandler} that handles {@link Observable} return types. 28 | * 29 | * @author Jakub Narloch 30 | * @see ObservableDeferredResult 31 | */ 32 | public class ObservableReturnValueHandler implements AsyncHandlerMethodReturnValueHandler { 33 | 34 | @Override 35 | public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { 36 | return returnValue != null && supportsReturnType(returnType); 37 | } 38 | 39 | @Override 40 | public boolean supportsReturnType(MethodParameter returnType) { 41 | return Observable.class.isAssignableFrom(returnType.getParameterType()); 42 | } 43 | 44 | @SuppressWarnings("unchecked") 45 | @Override 46 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 47 | 48 | if (returnValue == null) { 49 | mavContainer.setRequestHandled(true); 50 | return; 51 | } 52 | 53 | final Observable observable = Observable.class.cast(returnValue); 54 | WebAsyncUtils.getAsyncManager(webRequest) 55 | .startDeferredResultProcessing(new ObservableDeferredResult(observable), mavContainer); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/io/jmnarloch/spring/boot/rxjava/mvc/SingleReturnValueHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.mvc; 17 | 18 | import io.jmnarloch.spring.boot.rxjava.async.SingleDeferredResult; 19 | import org.springframework.core.MethodParameter; 20 | import org.springframework.web.context.request.NativeWebRequest; 21 | import org.springframework.web.context.request.async.WebAsyncUtils; 22 | import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler; 23 | import org.springframework.web.method.support.ModelAndViewContainer; 24 | import io.reactivex.Single; 25 | 26 | /** 27 | * A specialized {@link AsyncHandlerMethodReturnValueHandler} that handles {@link Single} return types. 28 | * 29 | * @author Jakub Narloch 30 | * @see SingleDeferredResult 31 | */ 32 | public class SingleReturnValueHandler implements AsyncHandlerMethodReturnValueHandler { 33 | 34 | @Override 35 | public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { 36 | return returnValue != null && supportsReturnType(returnType); 37 | } 38 | 39 | @Override 40 | public boolean supportsReturnType(MethodParameter returnType) { 41 | return Single.class.isAssignableFrom(returnType.getParameterType()); 42 | } 43 | 44 | @SuppressWarnings("unchecked") 45 | @Override 46 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 47 | 48 | if (returnValue == null) { 49 | mavContainer.setRequestHandled(true); 50 | return; 51 | } 52 | 53 | final Single single = Single.class.cast(returnValue); 54 | WebAsyncUtils.getAsyncManager(webRequest) 55 | .startDeferredResultProcessing(new SingleDeferredResult(single), mavContainer); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | io.jmnarloch.spring.boot.rxjava.config.RxJavaMvcAutoConfiguration -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/Demo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava; 17 | 18 | import com.fasterxml.jackson.annotation.JsonCreator; 19 | import com.fasterxml.jackson.annotation.JsonProperty; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.springframework.beans.factory.annotation.Value; 23 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 24 | import org.springframework.boot.test.IntegrationTest; 25 | import org.springframework.boot.test.SpringApplicationConfiguration; 26 | import org.springframework.boot.test.TestRestTemplate; 27 | import org.springframework.context.annotation.Configuration; 28 | import org.springframework.core.ParameterizedTypeReference; 29 | import org.springframework.http.HttpMethod; 30 | import org.springframework.http.HttpStatus; 31 | import org.springframework.http.MediaType; 32 | import org.springframework.http.ResponseEntity; 33 | import org.springframework.test.annotation.DirtiesContext; 34 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 35 | import org.springframework.test.context.web.WebAppConfiguration; 36 | import org.springframework.web.bind.annotation.RequestMapping; 37 | import org.springframework.web.bind.annotation.RequestMethod; 38 | import org.springframework.web.bind.annotation.RestController; 39 | import io.reactivex.Observable; 40 | 41 | import java.util.Date; 42 | import java.util.List; 43 | 44 | import static org.junit.Assert.assertEquals; 45 | import static org.junit.Assert.assertNotNull; 46 | 47 | /** 48 | * Demonstrates usage of this component. 49 | * 50 | * @author Jakub Narloch 51 | */ 52 | @RunWith(SpringJUnit4ClassRunner.class) 53 | @SpringApplicationConfiguration(classes = Demo.InvoiceResource.class) 54 | @WebAppConfiguration 55 | @IntegrationTest({"server.port=0"}) 56 | @DirtiesContext 57 | public class Demo { 58 | 59 | @Value("${local.server.port}") 60 | private int port = 0; 61 | 62 | private TestRestTemplate restTemplate = new TestRestTemplate(); 63 | 64 | @Configuration 65 | @EnableAutoConfiguration 66 | @RestController 67 | protected static class InvoiceResource { 68 | 69 | @RequestMapping(method = RequestMethod.GET, value = "/invoices", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 70 | public Observable getInvoices() { 71 | 72 | return Observable.just( 73 | new Invoice("Acme", new Date()), 74 | new Invoice("Oceanic", new Date()) 75 | ); 76 | } 77 | } 78 | 79 | @Test 80 | public void shouldRetrieveInvoices() { 81 | 82 | // when 83 | ResponseEntity> response = restTemplate.exchange(path("/invoices"), 84 | HttpMethod.GET, null, new ParameterizedTypeReference>() { 85 | }); 86 | 87 | // then 88 | assertNotNull(response); 89 | assertEquals(HttpStatus.OK, response.getStatusCode()); 90 | assertEquals("Acme", response.getBody().get(0).getTitle()); 91 | } 92 | 93 | private String path(String context) { 94 | return String.format("http://localhost:%d%s", port, context); 95 | } 96 | 97 | private static class Invoice { 98 | 99 | private final String title; 100 | 101 | private final Date issueDate; 102 | 103 | @JsonCreator 104 | public Invoice(@JsonProperty("title") String title, @JsonProperty("issueDate") Date issueDate) { 105 | this.title = title; 106 | this.issueDate = issueDate; 107 | } 108 | 109 | public String getTitle() { 110 | return title; 111 | } 112 | 113 | public Date getIssueDate() { 114 | return issueDate; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/async/ObservableDeferredResultTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import io.jmnarloch.spring.boot.rxjava.dto.EventDto; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.beans.factory.annotation.Value; 22 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 23 | import org.springframework.boot.test.IntegrationTest; 24 | import org.springframework.boot.test.SpringApplicationConfiguration; 25 | import org.springframework.boot.test.TestRestTemplate; 26 | import org.springframework.context.annotation.Configuration; 27 | import org.springframework.core.ParameterizedTypeReference; 28 | import org.springframework.http.HttpMethod; 29 | import org.springframework.http.HttpStatus; 30 | import org.springframework.http.ResponseEntity; 31 | import org.springframework.test.annotation.DirtiesContext; 32 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 33 | import org.springframework.test.context.web.WebAppConfiguration; 34 | import org.springframework.web.bind.annotation.RequestMapping; 35 | import org.springframework.web.bind.annotation.RequestMethod; 36 | import org.springframework.web.bind.annotation.RestController; 37 | import io.reactivex.Observable; 38 | import io.reactivex.functions.Function; 39 | 40 | import java.util.Arrays; 41 | import java.util.Collections; 42 | import java.util.Date; 43 | import java.util.List; 44 | import java.util.concurrent.TimeUnit; 45 | 46 | import static org.junit.Assert.assertEquals; 47 | import static org.junit.Assert.assertNotNull; 48 | import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; 49 | 50 | /** 51 | * Tests the {@link ObservableDeferredResult} class. 52 | * 53 | * @author Jakub Narloch 54 | */ 55 | @RunWith(SpringJUnit4ClassRunner.class) 56 | @SpringApplicationConfiguration(classes = ObservableDeferredResultTest.Application.class) 57 | @WebAppConfiguration 58 | @IntegrationTest({"server.port=0"}) 59 | @DirtiesContext 60 | public class ObservableDeferredResultTest { 61 | 62 | @Value("${local.server.port}") 63 | private int port = 0; 64 | 65 | private TestRestTemplate restTemplate = new TestRestTemplate(); 66 | 67 | @Configuration 68 | @EnableAutoConfiguration 69 | @RestController 70 | protected static class Application { 71 | 72 | @RequestMapping(method = RequestMethod.GET, value = "/empty") 73 | public ObservableDeferredResult empty() { 74 | return new ObservableDeferredResult(Observable.empty()); 75 | } 76 | 77 | @RequestMapping(method = RequestMethod.GET, value = "/single") 78 | public ObservableDeferredResult single() { 79 | return new ObservableDeferredResult(Observable.just("single value")); 80 | } 81 | 82 | @RequestMapping(method = RequestMethod.GET, value = "/multiple") 83 | public ObservableDeferredResult multiple() { 84 | return new ObservableDeferredResult(Observable.just("multiple", "values")); 85 | } 86 | 87 | @RequestMapping(method = RequestMethod.GET, value = "/event", produces = APPLICATION_JSON_UTF8_VALUE) 88 | public ObservableDeferredResult event() { 89 | return new ObservableDeferredResult( 90 | Observable.just( 91 | new EventDto("Spring.io", new Date()), 92 | new EventDto("JavaOne", new Date()) 93 | ) 94 | ); 95 | } 96 | 97 | @RequestMapping(method = RequestMethod.GET, value = "/throw") 98 | public ObservableDeferredResult error() { 99 | return new ObservableDeferredResult(Observable.error(new RuntimeException("Unexpected"))); 100 | } 101 | 102 | @RequestMapping(method = RequestMethod.GET, value = "/timeout") 103 | public ObservableDeferredResult timeout() { 104 | return new ObservableDeferredResult(Observable.timer(1, TimeUnit.MINUTES).map(new Function() { 105 | @Override 106 | public String apply(Long aLong) { 107 | return "single value"; 108 | } 109 | })); 110 | } 111 | } 112 | 113 | @Test 114 | public void shouldRetrieveEmptyResponse() { 115 | 116 | // when 117 | ResponseEntity response = restTemplate.getForEntity(path("/empty"), List.class); 118 | 119 | // then 120 | assertNotNull(response); 121 | assertEquals(HttpStatus.OK, response.getStatusCode()); 122 | assertEquals(Collections.emptyList(), response.getBody()); 123 | } 124 | 125 | @Test 126 | public void shouldRetrieveSingleValue() { 127 | 128 | // when 129 | ResponseEntity response = restTemplate.getForEntity(path("/single"), List.class); 130 | 131 | // then 132 | assertNotNull(response); 133 | assertEquals(HttpStatus.OK, response.getStatusCode()); 134 | assertEquals(Collections.singletonList("single value"), response.getBody()); 135 | } 136 | 137 | @Test 138 | public void shouldRetrieveMultipleValues() { 139 | 140 | // when 141 | ResponseEntity response = restTemplate.getForEntity(path("/multiple"), List.class); 142 | 143 | // then 144 | assertNotNull(response); 145 | assertEquals(HttpStatus.OK, response.getStatusCode()); 146 | assertEquals(Arrays.asList("multiple", "values"), response.getBody()); 147 | } 148 | 149 | @Test 150 | public void shouldRetrieveJsonSerializedListValues() { 151 | 152 | // when 153 | ResponseEntity> response = restTemplate.exchange(path("/event"), HttpMethod.GET, null, 154 | new ParameterizedTypeReference>() {}); 155 | 156 | // then 157 | assertNotNull(response); 158 | assertEquals(HttpStatus.OK, response.getStatusCode()); 159 | assertEquals(2, response.getBody().size()); 160 | assertEquals("JavaOne", response.getBody().get(1).getName()); 161 | } 162 | 163 | @Test 164 | public void shouldRetrieveErrorResponse() { 165 | 166 | // when 167 | ResponseEntity response = restTemplate.getForEntity(path("/throw"), Object.class); 168 | 169 | // then 170 | assertNotNull(response); 171 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); 172 | } 173 | 174 | @Test 175 | public void shouldTimeoutOnConnection() { 176 | 177 | // when 178 | ResponseEntity response = restTemplate.getForEntity(path("/timeout"), Object.class); 179 | 180 | // then 181 | assertNotNull(response); 182 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); 183 | } 184 | 185 | private String path(String context) { 186 | return String.format("http://localhost:%d%s", port, context); 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/async/ObservableSseEmitterTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import io.jmnarloch.spring.boot.rxjava.dto.EventDto; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.beans.factory.annotation.Value; 22 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 23 | import org.springframework.boot.test.IntegrationTest; 24 | import org.springframework.boot.test.SpringApplicationConfiguration; 25 | import org.springframework.boot.test.TestRestTemplate; 26 | import org.springframework.context.annotation.Configuration; 27 | import org.springframework.http.HttpStatus; 28 | import org.springframework.http.ResponseEntity; 29 | import org.springframework.test.annotation.DirtiesContext; 30 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 31 | import org.springframework.test.context.web.WebAppConfiguration; 32 | import org.springframework.web.bind.annotation.RequestMapping; 33 | import org.springframework.web.bind.annotation.RequestMethod; 34 | import org.springframework.web.bind.annotation.RestController; 35 | import io.reactivex.Observable; 36 | 37 | import java.util.Date; 38 | import java.util.GregorianCalendar; 39 | 40 | import static org.junit.Assert.assertEquals; 41 | import static org.junit.Assert.assertNotNull; 42 | import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8; 43 | 44 | /** 45 | * Tests the {@link ObservableSseEmitter} class. 46 | * 47 | * @author Jakub Narloch 48 | */ 49 | @RunWith(SpringJUnit4ClassRunner.class) 50 | @SpringApplicationConfiguration(classes = ObservableSseEmitterTest.Application.class) 51 | @WebAppConfiguration 52 | @IntegrationTest({"server.port=0"}) 53 | @DirtiesContext 54 | public class ObservableSseEmitterTest { 55 | 56 | @Value("${local.server.port}") 57 | private int port = 0; 58 | 59 | private TestRestTemplate restTemplate = new TestRestTemplate(); 60 | 61 | @Configuration 62 | @EnableAutoConfiguration 63 | @RestController 64 | protected static class Application { 65 | 66 | @RequestMapping(method = RequestMethod.GET, value = "/sse") 67 | public ObservableSseEmitter single() { 68 | return new ObservableSseEmitter(Observable.just("single value")); 69 | } 70 | 71 | @RequestMapping(method = RequestMethod.GET, value = "/messages") 72 | public ObservableSseEmitter messages() { 73 | return new ObservableSseEmitter(Observable.just("message 1", "message 2", "message 3")); 74 | } 75 | 76 | @RequestMapping(method = RequestMethod.GET, value = "/events") 77 | public ObservableSseEmitter event() { 78 | return new ObservableSseEmitter(APPLICATION_JSON_UTF8, Observable.just( 79 | new EventDto("Spring.io", getDate(2016, 5, 11)), 80 | new EventDto("JavaOne", getDate(2016, 9, 22)) 81 | )); 82 | } 83 | } 84 | 85 | @Test 86 | public void shouldRetrieveSse() { 87 | 88 | // when 89 | ResponseEntity response = restTemplate.getForEntity(path("/sse"), String.class); 90 | 91 | // then 92 | assertNotNull(response); 93 | assertEquals(HttpStatus.OK, response.getStatusCode()); 94 | assertEquals("data:single value\n\n", response.getBody()); 95 | } 96 | 97 | @Test 98 | public void shouldRetrieveSseWithMultipleMessages() { 99 | 100 | // when 101 | ResponseEntity response = restTemplate.getForEntity(path("/messages"), String.class); 102 | 103 | // then 104 | assertNotNull(response); 105 | assertEquals(HttpStatus.OK, response.getStatusCode()); 106 | assertEquals("data:message 1\n\ndata:message 2\n\ndata:message 3\n\n", response.getBody()); 107 | } 108 | 109 | @Test 110 | public void shouldRetrieveJsonOverSseWithMultipleMessages() { 111 | 112 | // when 113 | ResponseEntity response = restTemplate.getForEntity(path("/events"), String.class); 114 | 115 | // then 116 | assertNotNull(response); 117 | assertEquals(HttpStatus.OK, response.getStatusCode()); 118 | } 119 | 120 | private String path(String context) { 121 | return String.format("http://localhost:%d%s", port, context); 122 | } 123 | 124 | private static Date getDate(int year, int month, int day) { 125 | return new GregorianCalendar(year, month, day).getTime(); 126 | } 127 | } -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/async/SingleDeferredResultTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.async; 17 | 18 | import io.jmnarloch.spring.boot.rxjava.dto.EventDto; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.beans.factory.annotation.Value; 22 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 23 | import org.springframework.boot.test.IntegrationTest; 24 | import org.springframework.boot.test.SpringApplicationConfiguration; 25 | import org.springframework.boot.test.TestRestTemplate; 26 | import org.springframework.context.annotation.Configuration; 27 | import org.springframework.http.HttpStatus; 28 | import org.springframework.http.ResponseEntity; 29 | import org.springframework.test.annotation.DirtiesContext; 30 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 31 | import org.springframework.test.context.web.WebAppConfiguration; 32 | import org.springframework.web.bind.annotation.RequestMapping; 33 | import org.springframework.web.bind.annotation.RequestMethod; 34 | import org.springframework.web.bind.annotation.RestController; 35 | import io.reactivex.Single; 36 | 37 | import java.util.Date; 38 | 39 | import static org.junit.Assert.assertEquals; 40 | import static org.junit.Assert.assertNotNull; 41 | import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; 42 | 43 | /** 44 | * Tests the {@link SingleDeferredResult} class. 45 | * 46 | * @author Jakub Narloch 47 | */ 48 | @RunWith(SpringJUnit4ClassRunner.class) 49 | @SpringApplicationConfiguration(classes = SingleDeferredResultTest.Application.class) 50 | @WebAppConfiguration 51 | @IntegrationTest({"server.port=0"}) 52 | @DirtiesContext 53 | public class SingleDeferredResultTest { 54 | 55 | @Value("${local.server.port}") 56 | private int port = 0; 57 | 58 | private TestRestTemplate restTemplate = new TestRestTemplate(); 59 | 60 | @Configuration 61 | @EnableAutoConfiguration 62 | @RestController 63 | protected static class Application { 64 | 65 | @RequestMapping(method = RequestMethod.GET, value = "/single") 66 | public SingleDeferredResult single() { 67 | return new SingleDeferredResult(Single.just("single value")); 68 | } 69 | 70 | @RequestMapping(method = RequestMethod.GET, value = "/singleWithResponse") 71 | public SingleDeferredResult> singleWithResponse() { 72 | return new SingleDeferredResult>( 73 | Single.just(new ResponseEntity("single value", HttpStatus.NOT_FOUND))); 74 | } 75 | 76 | @RequestMapping(method = RequestMethod.GET, value = "/event", produces = APPLICATION_JSON_UTF8_VALUE) 77 | public SingleDeferredResult event() { 78 | return new SingleDeferredResult(Single.just(new EventDto("Spring.io", new Date()))); 79 | } 80 | 81 | @RequestMapping(method = RequestMethod.GET, value = "/throw") 82 | public SingleDeferredResult error() { 83 | return new SingleDeferredResult(Single.error(new RuntimeException("Unexpected"))); 84 | } 85 | } 86 | 87 | @Test 88 | public void shouldRetrieveSingleValue() { 89 | 90 | // when 91 | ResponseEntity response = restTemplate.getForEntity(path("/single"), String.class); 92 | 93 | // then 94 | assertNotNull(response); 95 | assertEquals(HttpStatus.OK, response.getStatusCode()); 96 | assertEquals("single value", response.getBody()); 97 | } 98 | 99 | @Test 100 | public void shouldRetrieveSingleValueWithStatusCode() { 101 | 102 | // when 103 | ResponseEntity response = restTemplate.getForEntity(path("/singleWithResponse"), String.class); 104 | 105 | // then 106 | assertNotNull(response); 107 | assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); 108 | assertEquals("single value", response.getBody()); 109 | } 110 | 111 | @Test 112 | public void shouldRetrieveJsonSerializedPojoValue() { 113 | 114 | // when 115 | ResponseEntity response = restTemplate.getForEntity(path("/event"), EventDto.class); 116 | 117 | // then 118 | assertNotNull(response); 119 | assertEquals(HttpStatus.OK, response.getStatusCode()); 120 | assertEquals("Spring.io", response.getBody().getName()); 121 | } 122 | 123 | @Test 124 | public void shouldRetrieveErrorResponse() { 125 | 126 | // when 127 | ResponseEntity response = restTemplate.getForEntity(path("/throw"), Object.class); 128 | 129 | // then 130 | assertNotNull(response); 131 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); 132 | } 133 | 134 | private String path(String context) { 135 | return String.format("http://localhost:%d%s", port, context); 136 | } 137 | } -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/dto/EventDto.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.dto; 17 | 18 | import com.fasterxml.jackson.annotation.JsonCreator; 19 | import com.fasterxml.jackson.annotation.JsonProperty; 20 | 21 | import java.util.Date; 22 | 23 | /** 24 | * A simple DTO used for testing purpose. 25 | * 26 | * @author Jakub Narloch 27 | */ 28 | public class EventDto { 29 | 30 | private final String name; 31 | 32 | private final Date date; 33 | 34 | @JsonCreator 35 | public EventDto(@JsonProperty("name") String name, @JsonProperty("date") Date date) { 36 | this.name = name; 37 | this.date = date; 38 | } 39 | 40 | public String getName() { 41 | return name; 42 | } 43 | 44 | public Date getDate() { 45 | return date; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/mvc/ObservableReturnValueHandlerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.mvc; 17 | 18 | import io.reactivex.Observable; 19 | import io.reactivex.functions.Function; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.beans.factory.annotation.Value; 24 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 25 | import org.springframework.boot.test.IntegrationTest; 26 | import org.springframework.boot.test.SpringApplicationConfiguration; 27 | import org.springframework.boot.test.TestRestTemplate; 28 | import org.springframework.context.annotation.Configuration; 29 | import org.springframework.http.HttpStatus; 30 | import org.springframework.http.ResponseEntity; 31 | import org.springframework.test.annotation.DirtiesContext; 32 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 33 | import org.springframework.test.context.web.WebAppConfiguration; 34 | import org.springframework.web.bind.annotation.RequestMapping; 35 | import org.springframework.web.bind.annotation.RequestMethod; 36 | import org.springframework.web.bind.annotation.RestController; 37 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 38 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 39 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; 40 | 41 | import javax.annotation.PostConstruct; 42 | import java.util.ArrayList; 43 | import java.util.Arrays; 44 | import java.util.Collections; 45 | import java.util.List; 46 | import java.util.concurrent.TimeUnit; 47 | 48 | import static org.junit.Assert.assertEquals; 49 | import static org.junit.Assert.assertNotNull; 50 | 51 | /** 52 | * Tests the {@link ObservableReturnValueHandler} class. 53 | * 54 | * @author Jakub Narloch 55 | */ 56 | @RunWith(SpringJUnit4ClassRunner.class) 57 | @SpringApplicationConfiguration(classes = ObservableReturnValueHandlerTest.Application.class) 58 | @WebAppConfiguration 59 | @IntegrationTest({"server.port=0"}) 60 | @DirtiesContext 61 | public class ObservableReturnValueHandlerTest { 62 | 63 | @Value("${local.server.port}") 64 | private int port = 0; 65 | 66 | private TestRestTemplate restTemplate = new TestRestTemplate(); 67 | 68 | @Configuration 69 | @EnableAutoConfiguration 70 | @RestController 71 | protected static class Application { 72 | 73 | @Autowired 74 | private RequestMappingHandlerAdapter adapter; 75 | 76 | @PostConstruct 77 | public void prioritizeCustomReturnValueHandlers () { 78 | final List returnValueHandlers = 79 | new ArrayList<>(adapter.getReturnValueHandlers()); 80 | final List customReturnValueHandlers = 81 | adapter.getCustomReturnValueHandlers(); 82 | returnValueHandlers.removeAll(customReturnValueHandlers); 83 | returnValueHandlers.addAll(0, customReturnValueHandlers); 84 | adapter.setReturnValueHandlers(returnValueHandlers); 85 | } 86 | 87 | @RequestMapping(method = RequestMethod.GET, value = "/empty") 88 | public Observable empty() { 89 | return Observable.empty(); 90 | } 91 | 92 | @RequestMapping(method = RequestMethod.GET, value = "/single") 93 | public Observable single() { 94 | return Observable.just("single value"); 95 | } 96 | 97 | @RequestMapping(method = RequestMethod.GET, value = "/multiple") 98 | public Observable multiple() { 99 | return Observable.just("multiple", "values"); 100 | } 101 | 102 | @RequestMapping(method = RequestMethod.GET, value = "/throw") 103 | public Observable error() { 104 | return Observable.error(new RuntimeException("Unexpected")); 105 | } 106 | 107 | @RequestMapping(method = RequestMethod.GET, value = "/timeout") 108 | public Observable timeout() { 109 | return Observable.timer(1, TimeUnit.MINUTES).map(new Function() { 110 | @Override 111 | public String apply(Long aLong) { 112 | return "single value"; 113 | } 114 | }); 115 | } 116 | } 117 | 118 | @Test 119 | public void shouldRetrieveEmptyResponse() { 120 | 121 | // when 122 | ResponseEntity response = restTemplate.getForEntity(path("/empty"), List.class); 123 | 124 | // then 125 | assertNotNull(response); 126 | assertEquals(HttpStatus.OK, response.getStatusCode()); 127 | assertEquals(Collections.emptyList(), response.getBody()); 128 | } 129 | 130 | @Test 131 | public void shouldRetrieveSingleValue() { 132 | 133 | // when 134 | ResponseEntity response = restTemplate.getForEntity(path("/single"), List.class); 135 | 136 | // then 137 | assertNotNull(response); 138 | assertEquals(HttpStatus.OK, response.getStatusCode()); 139 | assertEquals(Collections.singletonList("single value"), response.getBody()); 140 | } 141 | 142 | @Test 143 | public void shouldRetrieveMultipleValues() { 144 | 145 | // when 146 | ResponseEntity response = restTemplate.getForEntity(path("/multiple"), List.class); 147 | 148 | // then 149 | assertNotNull(response); 150 | assertEquals(HttpStatus.OK, response.getStatusCode()); 151 | assertEquals(Arrays.asList("multiple", "values"), response.getBody()); 152 | } 153 | 154 | @Test 155 | public void shouldRetrieveErrorResponse() { 156 | 157 | // when 158 | ResponseEntity response = restTemplate.getForEntity(path("/throw"), Object.class); 159 | 160 | // then 161 | assertNotNull(response); 162 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); 163 | } 164 | 165 | @Test 166 | public void shouldTimeoutOnConnection() { 167 | 168 | // when 169 | ResponseEntity response = restTemplate.getForEntity(path("/timeout"), Object.class); 170 | 171 | // then 172 | assertNotNull(response); 173 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); 174 | } 175 | 176 | private String path(String context) { 177 | return String.format("http://localhost:%d%s", port, context); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/test/java/io/jmnarloch/spring/boot/rxjava/mvc/SingleReturnValueHandlerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2016 the original author or authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.jmnarloch.spring.boot.rxjava.mvc; 17 | 18 | import org.junit.Test; 19 | import org.junit.runner.RunWith; 20 | import org.springframework.beans.factory.annotation.Value; 21 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 22 | import org.springframework.boot.test.IntegrationTest; 23 | import org.springframework.boot.test.SpringApplicationConfiguration; 24 | import org.springframework.boot.test.TestRestTemplate; 25 | import org.springframework.context.annotation.Configuration; 26 | import org.springframework.http.HttpStatus; 27 | import org.springframework.http.ResponseEntity; 28 | import org.springframework.test.annotation.DirtiesContext; 29 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 30 | import org.springframework.test.context.web.WebAppConfiguration; 31 | import org.springframework.web.bind.annotation.RequestMapping; 32 | import org.springframework.web.bind.annotation.RequestMethod; 33 | import org.springframework.web.bind.annotation.RestController; 34 | import io.reactivex.Single; 35 | 36 | import static org.junit.Assert.assertEquals; 37 | import static org.junit.Assert.assertNotNull; 38 | 39 | /** 40 | * Tests the {@link SingleReturnValueHandler} class. 41 | * 42 | * @author Jakub Narloch 43 | */ 44 | @RunWith(SpringJUnit4ClassRunner.class) 45 | @SpringApplicationConfiguration(classes = SingleReturnValueHandlerTest.Application.class) 46 | @WebAppConfiguration 47 | @IntegrationTest({"server.port=0"}) 48 | @DirtiesContext 49 | public class SingleReturnValueHandlerTest { 50 | 51 | @Value("${local.server.port}") 52 | private int port = 0; 53 | 54 | private TestRestTemplate restTemplate = new TestRestTemplate(); 55 | 56 | @Configuration 57 | @EnableAutoConfiguration 58 | @RestController 59 | protected static class Application { 60 | 61 | @RequestMapping(method = RequestMethod.GET, value = "/single") 62 | public Single single() { 63 | return Single.just("single value"); 64 | } 65 | 66 | @RequestMapping(method = RequestMethod.GET, value = "/singleWithResponse") 67 | public Single> singleWithResponse() { 68 | return Single.just(new ResponseEntity("single value", HttpStatus.NOT_FOUND)); 69 | } 70 | 71 | @RequestMapping(method = RequestMethod.GET, value = "/throw") 72 | public Single error() { 73 | return Single.error(new RuntimeException("Unexpected")); 74 | } 75 | } 76 | 77 | @Test 78 | public void shouldRetrieveSingleValue() { 79 | 80 | // when 81 | ResponseEntity response = restTemplate.getForEntity(path("/single"), String.class); 82 | 83 | // then 84 | assertNotNull(response); 85 | assertEquals(HttpStatus.OK, response.getStatusCode()); 86 | assertEquals("single value", response.getBody()); 87 | } 88 | 89 | @Test 90 | public void shouldRetrieveSingleValueWithStatusCode() { 91 | 92 | // when 93 | ResponseEntity response = restTemplate.getForEntity(path("/singleWithResponse"), String.class); 94 | 95 | // then 96 | assertNotNull(response); 97 | assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); 98 | assertEquals("single value", response.getBody()); 99 | } 100 | 101 | @Test 102 | public void shouldRetrieveErrorResponse() { 103 | 104 | // when 105 | ResponseEntity response = restTemplate.getForEntity(path("/throw"), Object.class); 106 | 107 | // then 108 | assertNotNull(response); 109 | assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); 110 | } 111 | 112 | private String path(String context) { 113 | return String.format("http://localhost:%d%s", port, context); 114 | } 115 | } --------------------------------------------------------------------------------