Repository: ReactiveX/RxJavaReactiveStreams Branch: 1.x Commit: 1c6a64de2c9f Files: 46 Total size: 103.3 KB Directory structure: gitextract_fwl8m9s9/ ├── .editorconfig ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── build.gradle ├── examples/ │ ├── build.gradle │ └── ratpack/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── rx/ │ │ └── reactivestreams/ │ │ └── example/ │ │ └── ratpack/ │ │ └── Dummy.java │ └── test/ │ └── java/ │ └── rx/ │ └── reactivestreams/ │ └── example/ │ └── ratpack/ │ ├── RatpackExamples.java │ └── RecordingWebSocketClient.java ├── gradle/ │ ├── buildViaTravis.sh │ └── wrapper/ │ ├── .gitignore │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── rxjava-reactive-streams/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── rx/ │ │ ├── RxReactiveStreams.java │ │ └── internal/ │ │ └── reactivestreams/ │ │ ├── CompletableAsPublisher.java │ │ ├── PublisherAdapter.java │ │ ├── PublisherAsCompletable.java │ │ ├── PublisherAsSingle.java │ │ ├── RxJavaSynchronizedProducer.java │ │ ├── SingleAsPublisher.java │ │ └── SubscriberAdapter.java │ └── test/ │ └── java/ │ └── rx/ │ └── reactivestreams/ │ ├── NonTckTest.java │ ├── TckAsynchronousPublisherTest.java │ ├── TckCompletableAsyncConversionTest.java │ ├── TckCompletableConversionTest.java │ ├── TckSingleAsyncConversionTest.java │ ├── TckSingleConversionTest.java │ ├── TckSubscriberBlackboxTest.java │ ├── TckSubscriberWhiteboxTest.java │ ├── TckSynchronousPublisherTest.java │ └── test/ │ ├── CompletableAsPublisherTest.java │ ├── CountdownIterable.java │ ├── IterablePublisher.java │ ├── PublisherAsCompletableTest.java │ ├── PublisherAsSingleTest.java │ ├── RsSubscriber.java │ ├── RxSubscriber.java │ ├── SingleAsPublisherTest.java │ └── WrapUnwrap.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # EditorConfig helps developers define and maintain consistent # coding styles between different editors and IDEs # editorconfig.org root = true [*] # Change these settings to your own preference indent_style = space indent_size = 4 # We recommend you to keep these unchanged end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.md] trim_trailing_whitespace = false indent_style = space ================================================ FILE: .gitignore ================================================ # Compiled source # ################### *.com *.class *.dll *.exe *.o *.so # Packages # ############ # it's better to unpack these files and commit the raw source # git has its own built in compression methods *.7z *.dmg *.gz *.iso *.jar *.rar *.tar *.zip # Logs and databases # ###################### *.log # OS generated files # ###################### .DS_Store* ehthumbs.db Icon? Thumbs.db # Editor Files # ################ *~ *.swp # Gradle Files # ################ .gradle .gradletasknamecache .m2 # Build output directies target/ build/ # IntelliJ specific files/directories out .idea *.ipr *.iws *.iml atlassian-ide-plugin.xml # Eclipse specific files/directories .classpath .project .settings .metadata bin/ # NetBeans specific files/directories .nbattrs /.nb-gradle/profiles/private/ .nb-gradle-properties # Scala build *.cache /.nb-gradle/private/ ================================================ FILE: .travis.yml ================================================ language: java jdk: - oraclejdk7 sudo: false # as per http://blog.travis-ci.com/2014-12-17-faster-builds-with-container-based-infrastructure/ # script for build and release via Travis to Bintray script: gradle/buildViaTravis.sh # Code coverage after_success: - bash <(curl -s https://codecov.io/bash) # cache between builds cache: directories: - $HOME/.m2 - $HOME/.gradle env: global: - secure: "WP1xTcv1Ti9vozsZSZYTPxi2iW4KVW9MmlZaQgnHvrDZRo+Z/VvugG1Ww49TY9qv/xd3d+sw8SuRu/yBP/KOAeaQLJ6mjeVcWKUngIJv70/mfp5d4ErnU0D7ntzyi00K9Q0C7cKO3sxaPAynGHeVAFKopjaXxQT4171QFoUZNq0=" - secure: "pNrV8dNdQMgZcH4EtrG15tPWwDM2kOTEdMumuU8c7xU20pXvQrYuoi4XEt3bdROz772uFuqGhxbxGjoXJiqg2DxIrYHVgbCJzTiifIiW/19poqplNNLfSPwmE7u4YXLgKXKPLs4SO1LsFmPkn5KoopCTChbqJYnGXLj2EtU7wcQ=" - secure: "J38VYI7m7sIGJtM+xdkuSZ5YoROjrM8Be74JDLHs+MH22n6uqupoRRWUAkSP4gCMA/kp7WKNFJsv+6OBUCxSdMUVA2x7dFJ5ocV9zAZuPXTBaR9k/cWmOrKg7ih23LntQbp/6vBoGMv+qwJ0HuFZefh0lSRfBvbJ+BYROxgWJiI=" - secure: "O7JOWfyyKOBoXCM/P7kHE/72rPcdlweW14f22G+CzD8+5WYaVch4XtQiXvLNvw6K/xNn5xFSGtTdBYPXXENrhxKZcRkNjfxAMCZO5HwtPeRwLdem1IxdoJkkU1iinJDqLRVy1KFU3pzSH+6SINtpLKZZe3Zc1bCZ8ECxlsaV4rg=" ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to RxJava If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request (on a branch other than `master` or `gh-pages`). When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. ## License By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/ReactiveX/RxJava/blob/master/LICENSE All files are released with the Apache 2.0 license. If you are adding a new file it should have a header like this: ``` /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ``` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2012 Netflix, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # RxJava Reactive Streams [![codecov.io](http://codecov.io/github/ReactiveX/RxJavaReactiveStreams/coverage.svg?branch=1.x)](http://codecov.io/github/ReactiveX/RxJavaReactiveStreams?branch=1.x) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.reactivex/rxjava-reactive-streams/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.reactivex/rxjava-reactive-streams) This library provides adapters between RxJava and [Reactive Streams](http://www.reactive-streams.org). The Reactive Streams standard defines an API and runtime semantics for reactive data streams, that different tools can implement in order to interoperate with each other. This library allows RxJava to interoperate with other implementors of the Reactive Streams API. It provides the following API: ```java package rx; import org.reactivestreams.Publisher; public abstract class RxReactiveStreams { public static Publisher toPublisher(Observable observable) { … } public static Observable toObservable(Publisher publisher) { … } public static Publisher toPublisher(Single observable) { … } public static Single toSingle(Publisher publisher) { … } public static Publisher toPublisher(Completable observable) { … } public static Completable toCompletable(Publisher publisher) { … } } ``` These methods can be used to convert between the Reactive Streams `Publisher` type, and RxJava's `Observable` type. Some [examples of this library being used for interop](https://github.com/ReactiveX/RxJavaReactiveStreams/tree/0.x/examples) are available as part of this repository. See the [Reactive Streams](http://www.reactive-streams.org) website for links to other libraries that implement the Reactive Streams API, and can therefore interoperate with RxJava via these methods. Learn more about RxJava on the Wiki Home and the Netflix TechBlog post where RxJava was introduced. ## Communication - Google Group: [RxJava](http://groups.google.com/d/forum/rxjava) - Twitter: [@RxJava](http://twitter.com/RxJava) - [GitHub Issues](https://github.com/ReactiveX/RxJava/issues) ## Binaries Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cio.reactivex.rxjava-reactive-streams). Example for Maven: ```xml io.reactivex rxjava-reactive-streams x.y.z ``` and for Ivy: ```xml ``` ## Build To build: ``` $ git clone git@github.com:ReactiveX/RxJavaReactiveStreams.git $ cd RxJavaReactiveStreams/ $ ./gradlew build ``` ## Bugs and Feedback For bugs, questions and discussions please use the [Github Issues](https://github.com/ReactiveX/RxJavaReactiveStreams/issues). ## LICENSE Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: build.gradle ================================================ buildscript { repositories { jcenter() } dependencies { classpath 'com.netflix.nebula:gradle-rxjava-project-plugin:4.0.0' } } allprojects { apply plugin: 'nebula.rxjava-project' } idea { project { jdkName = "1.6" } } // support for snapshot/final releases with the various branches RxJava uses nebulaRelease { addReleaseBranchPattern(/\d+\.\d+\.\d+/) addReleaseBranchPattern('HEAD') } if (project.hasProperty('release.useLastTag')) { tasks.prepare.enabled = false } ================================================ FILE: examples/build.gradle ================================================ subprojects { bintrayUpload.enabled = false artifactoryPublish.skip = true } ================================================ FILE: examples/ratpack/build.gradle ================================================ plugins { id "org.gradle.java" } dependencies { testCompile project(":rxjava-reactive-streams") testCompile "io.ratpack:ratpack-test:0.9.10" testCompile 'org.java-websocket:Java-WebSocket:1.3.0' testCompile 'junit:junit:4.11' } sourceCompatibility = "1.8" targetCompatibility = "1.8" // The implementation builds with Java 1.6 - we need to use Java 8 for Ratpack idea { module { jdkName = "1.8" iml.withXml { XmlProvider xml -> node.component.find { it.'@name' == 'NewModuleRootManager' }.@LANGUAGE_LEVEL = "JDK_1_8" } } } ================================================ FILE: examples/ratpack/src/main/java/rx/reactivestreams/example/ratpack/Dummy.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.example.ratpack; // Just here to appease the build // TODO LD: remove need for public class Dummy { } ================================================ FILE: examples/ratpack/src/test/java/rx/reactivestreams/example/ratpack/RatpackExamples.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.example.ratpack; import com.google.common.collect.ContiguousSet; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.Lists; import com.google.common.collect.Range; import org.junit.Assert; import org.junit.Test; import org.reactivestreams.Publisher; import ratpack.http.ResponseChunks; import ratpack.http.client.ReceivedResponse; import ratpack.sse.ServerSentEvents; import ratpack.stream.Streams; import ratpack.test.embed.EmbeddedApp; import ratpack.test.http.TestHttpClient; import ratpack.websocket.WebSockets; import rx.Observable; import rx.RxReactiveStreams; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import static java.util.stream.Collectors.joining; public class RatpackExamples { private Iterable createIntRange(int upper) { return ContiguousSet.create(Range.closedOpen(0, upper), DiscreteDomain.integers()); } /** * Tests rendering an observable as a chunked response. *

* Data flow: *

* 1. Observable of ints * 2. Convert to Publisher * 3. Use Ratpack Publisher transform * 4. Convert to Observable * 5. Use Observable transform * 6. Convert to Publisher * 7. Render Publisher *

* Back pressure is being applied but it's hard to test for, as it's being applied by the HTTP client ultimately. */ @Test public void testChunkStreaming() { Iterable ints = createIntRange(100); EmbeddedApp.fromHandler(ctx -> { // Create a publisher Observable observable = Observable.from(ints); Publisher publisher = RxReactiveStreams.toPublisher(observable); // Use one of Ratpack's transforms to convert them into strings Publisher strings = Streams.map(publisher, Object::toString); // Convert back to an Rx Observable to do further transforms Observable lines = RxReactiveStreams.toObservable(strings).map(s -> s + "\n"); // Now render the observable by going back to a publisher Publisher linesPublisher = RxReactiveStreams.toPublisher(lines); ctx.render(ResponseChunks.stringChunks(linesPublisher)); }).test(httpClient -> { String text = httpClient.getText().trim(); List strings = Arrays.asList(text.split("\n")); List expectedInts = Lists.newArrayList(ints); List receivedInts = Lists.transform(strings, Integer::new); Assert.assertEquals(expectedInts, receivedInts); }); } /** * Test streaming Server Sent Events */ @Test public void testServerSentEvents() { Iterable ints = createIntRange(5); EmbeddedApp.fromHandler(ctx -> { Observable observable = Observable.from(ints); Publisher publisher = RxReactiveStreams.toPublisher(observable); ctx.render( ServerSentEvents.serverSentEvents(publisher, e -> e.event("counter").data("event " + e.getItem()) ) ); }).test(httpClient -> { ReceivedResponse response = httpClient.get(); Assert.assertEquals("text/event-stream;charset=UTF-8", response.getHeaders().get("Content-Type")); String expectedOutput = Arrays.asList(0, 1, 2, 3, 4) .stream() .map(i -> "event: counter\ndata: event " + i + "\n") .collect(joining("\n")) + "\n"; Assert.assertEquals(expectedOutput, response.getBody().getText()); }); } /** * Test streaming to a Websocket. * * Note: Ratpack doesn't yet support consuming the incoming data as a stream. */ @Test public void testWebsocket() { Iterable ints = createIntRange(3); EmbeddedApp.fromHandler(ctx -> { Observable observable = Observable.from(ints).map(Object::toString); WebSockets.websocketBroadcast(ctx, RxReactiveStreams.toPublisher(observable)); }).test(httpClient -> { URI wsAddress = getWsAddress(httpClient); RecordingWebSocketClient wsClient = new RecordingWebSocketClient(wsAddress); try { Assert.assertTrue(wsClient.connectBlocking()); Assert.assertEquals("0", wsClient.next()); Assert.assertEquals("1", wsClient.next()); Assert.assertEquals("2", wsClient.next()); wsClient.waitForClose(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); } private URI getWsAddress(TestHttpClient httpClient) { URI httpAddress = httpClient.getApplicationUnderTest().getAddress(); URI wsAddress; try { wsAddress = new URI("ws", null, httpAddress.getHost(), httpAddress.getPort(), httpAddress.getPath(), null, null); } catch (URISyntaxException e) { throw new RuntimeException(e); } return wsAddress; } } ================================================ FILE: examples/ratpack/src/test/java/rx/reactivestreams/example/ratpack/RecordingWebSocketClient.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.example.ratpack; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * Fast and loose websocket client for testing purposes. */ public class RecordingWebSocketClient extends WebSocketClient { final BlockingQueue received = new LinkedBlockingQueue<>(); public Exception exception; public int closeCode; public String closeReason; public boolean closeRemote; public ServerHandshake serverHandshake; private final CountDownLatch closeLatch = new CountDownLatch(1); public RecordingWebSocketClient(URI serverURI) { super(serverURI); } @Override public void onOpen(ServerHandshake handshakedata) { serverHandshake = handshakedata; } @Override public void onMessage(String message) { try { received.put(message); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Override public void onClose(int code, String reason, boolean remote) { this.closeCode = code; this.closeReason = reason; this.closeRemote = remote; closeLatch.countDown(); } void waitForClose() throws InterruptedException { if (!closeLatch.await(5, TimeUnit.SECONDS)) { throw new RuntimeException("Socket did not close in time"); } } @Override public void onError(Exception ex) { this.exception = ex; } public String next() { try { return received.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } ================================================ FILE: gradle/buildViaTravis.sh ================================================ #!/bin/bash # This script will build the project. if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then echo -e "Build Pull Request #$TRAVIS_PULL_REQUEST => Branch [$TRAVIS_BRANCH]" ./gradlew -Prelease.useLastTag=true build elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" == "" ]; then echo -e 'Build Branch with Snapshot => Branch ['$TRAVIS_BRANCH']' ./gradlew -Prelease.travisci=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build snapshot --stacktrace elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" != "" ]; then echo -e 'Build Branch for Release => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG']' ./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" final --stacktrace else echo -e 'WARN: Should not be here => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG'] Pull Request ['$TRAVIS_PULL_REQUEST']' ./gradlew -Prelease.useLastTag=true build fi ================================================ FILE: gradle/wrapper/.gitignore ================================================ !*.jar ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Thu Jun 30 22:23:34 CEST 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: rxjava-reactive-streams/build.gradle ================================================ description = "Adapter between RxJava and ReactiveStreams" apply plugin: 'java' apply plugin: 'jacoco' dependencies { compile 'io.reactivex:rxjava:1.2.2' compile 'org.reactivestreams:reactive-streams:1.0.0' testCompile 'org.reactivestreams:reactive-streams-tck:1.0.0' testCompile group: 'org.testng', name: 'testng', version: '6.9.10' } test { useTestNG() testLogging { events=['passed', 'skipped', 'failed'] exceptionFormat="full" debug.events = ['passed', 'skipped', 'failed'] debug.exceptionFormat="full" info.events = ['passed', 'skipped', 'failed'] info.exceptionFormat="full" warn.events = ['passed', 'skipped', 'failed'] warn.exceptionFormat="full" } } jacoco { toolVersion = '0.7.7.201606060606' // See http://www.eclemma.org/jacoco/. } jacocoTestReport { reports { xml.enabled = true html.enabled = true } } build.dependsOn jacocoTestReport ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/RxReactiveStreams.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx; import org.reactivestreams.Publisher; import rx.internal.reactivestreams.*; /** * This type provides static factory methods for converting to and from RxJava types and Reactive Streams types. *

* The Reactive Streams API provides a common API for interoperability * between different reactive streaming libraries, of which RxJava is one. * Using the methods of this class, RxJava can collaborate with other such libraries that also implement the standard. */ public abstract class RxReactiveStreams { private RxReactiveStreams() { } /** * Convert a Rx {@link Observable} into a Reactive Streams {@link Publisher}. *

* Use this method when you have an RxJava observable, that you want to be consumed by another library. * * @param the value type * @param observable the {@link Observable} to convert * @return the converted {@link Publisher} */ public static Publisher toPublisher(Observable observable) { return new PublisherAdapter(observable); } /** * Convert a Reactive Streams {@link Publisher} into a Rx {@link Observable}. *

* Use this method when you have a stream from another library, that you want to be consume as an RxJava observable. * * @param the value type * @param publisher the {@link Publisher} to convert. * @return the converted {@link Observable} */ public static Observable toObservable(final Publisher publisher) { return Observable.create(new Observable.OnSubscribe() { @Override public void call(final rx.Subscriber rxSubscriber) { publisher.subscribe(toSubscriber(rxSubscriber)); } }); } /** * Convert an RxJava {@link rx.Subscriber} into a Reactive Streams {@link org.reactivestreams.Subscriber}. * * @param the value type * @param rxSubscriber an RxJava subscriber * @return a Reactive Streams subscriber */ public static org.reactivestreams.Subscriber toSubscriber(final rx.Subscriber rxSubscriber) { return new SubscriberAdapter(rxSubscriber); } /** * Converts an RxJava Completable into a Publisher that emits only onError or onComplete. * @param the target value type * @param completable the Completable instance to convert * @return the new Publisher instance * @since 1.1 * @throws NullPointerException if completable is null */ public static Publisher toPublisher(Completable completable) { if (completable == null) { throw new NullPointerException("completable"); } return new CompletableAsPublisher(completable); } /** * Converst a Publisher into a Completable by ignoring all onNext values and emitting * onError or onComplete only. * @param publisher the Publisher instance to convert * @return the Completable instance * @since 1.1 * @throws NullPointerException if publisher is null */ public static Completable toCompletable(Publisher publisher) { if (publisher == null) { throw new NullPointerException("publisher"); } return Completable.create(new PublisherAsCompletable(publisher)); } /** * Converts a Single into a Publisher which emits an onNext+onComplete if * the source Single signals a non-null onSuccess; or onError if the source signals * onError(NullPointerException) or a null value. * @param the value type * @param single the Single instance to convert * @return the Publisher instance * @since 1.1 * @throws NullPointerException if single is null */ public static Publisher toPublisher(Single single) { if (single == null) { throw new NullPointerException("single"); } return new SingleAsPublisher(single); } /** * Converts a Publisher into a Single which emits onSuccess if the * Publisher signals an onNext+onComplete; or onError if the publisher signals an * onError, the source Publisher is empty (NoSuchElementException) or the * source Publisher signals more than one onNext (IndexOutOfBoundsException). * @param the value type * @param publisher the Publisher instance to convert * @return the Single instance * @since 1.1 * @throws NullPointerException if publisher is null */ public static Single toSingle(Publisher publisher) { if (publisher == null) { throw new NullPointerException("publisher"); } return Single.create(new PublisherAsSingle(publisher)); } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/CompletableAsPublisher.java ================================================ /** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import rx.*; /** * Wraps a Completable and exposes it as a Publisher. * * @param the value type of the publisher */ public final class CompletableAsPublisher implements Publisher { final Completable completable; public CompletableAsPublisher(Completable completable) { this.completable = completable; } @Override public void subscribe(Subscriber s) { if (s == null) { throw new NullPointerException(); } completable.subscribe(new CompletableAsPublisherSubscriber(s)); } static final class CompletableAsPublisherSubscriber implements CompletableSubscriber, Subscription { final Subscriber actual; rx.Subscription d; public CompletableAsPublisherSubscriber(Subscriber actual) { this.actual = actual; } @Override public void onSubscribe(rx.Subscription d) { this.d = d; actual.onSubscribe(this); } @Override public void onError(Throwable e) { actual.onError(e); } @Override public void onCompleted() { actual.onComplete(); } @Override public void request(long n) { // No values will be emitted } @Override public void cancel() { d.unsubscribe(); } } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/PublisherAdapter.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import rx.Observable; import rx.internal.operators.BackpressureUtils; public class PublisherAdapter implements Publisher { private final Observable observable; public PublisherAdapter(final Observable observable) { this.observable = observable.serialize(); } @Override public void subscribe(final Subscriber s) { observable.subscribe(new rx.Subscriber() { private final AtomicBoolean done = new AtomicBoolean(); private final AtomicLong childRequested = new AtomicLong(); private void doRequest(long n) { if (!done.get()) { BackpressureUtils.getAndAddRequest(childRequested, n); request(n); } } @Override public void onStart() { final AtomicBoolean requested = new AtomicBoolean(); s.onSubscribe(new Subscription() { @Override public void request(long n) { if (n < 1) { unsubscribe(); onError(new IllegalArgumentException("3.9 While the Subscription is not cancelled, Subscription.request(long n) MUST throw a java.lang.IllegalArgumentException if the argument is <= 0.")); return; } requested.set(true); doRequest(n); } @Override public void cancel() { unsubscribe(); fireDone(); } }); if (!requested.get()) { request(0); } } boolean fireDone() { return done.compareAndSet(false, true); } @Override public void onCompleted() { if (fireDone()) { s.onComplete(); } } @Override public void onError(Throwable e) { if (fireDone()) { s.onError(e); } } @Override public void onNext(T t) { if (!done.get()) { if (childRequested.get() > 0) { s.onNext(t); childRequested.decrementAndGet(); } else { try { onError(new IllegalStateException("1.1 source doesn't respect backpressure")); } finally { unsubscribe(); } } } } }); } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/PublisherAsCompletable.java ================================================ /** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import org.reactivestreams.*; import rx.CompletableSubscriber; /** * Wraps an arbitrary Publisher and exposes it as a Completable, ignoring any onNext events. */ public final class PublisherAsCompletable implements rx.Completable.OnSubscribe { final Publisher publisher; public PublisherAsCompletable(Publisher publisher) { this.publisher = publisher; } @Override public void call(CompletableSubscriber t) { publisher.subscribe(new PublisherAsCompletableSubscriber(t)); } static final class PublisherAsCompletableSubscriber implements Subscriber, rx.Subscription { final CompletableSubscriber actual; Subscription s; volatile boolean unsubscribed; public PublisherAsCompletableSubscriber(CompletableSubscriber actual) { this.actual = actual; } @Override public void onSubscribe(Subscription s) { this.s = s; actual.onSubscribe(this); s.request(Long.MAX_VALUE); } @Override public void onNext(Object t) { // values are ignored } @Override public void onError(Throwable t) { actual.onError(t); } @Override public void onComplete() { actual.onCompleted(); } @Override public boolean isUnsubscribed() { return unsubscribed; } @Override public void unsubscribe() { if (!unsubscribed) { unsubscribed = true; s.cancel(); } } } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/PublisherAsSingle.java ================================================ /** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import java.util.NoSuchElementException; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import rx.*; /** * Wraps a Publisher and exposes it as a Single, signalling NoSuchElementException * if the Publisher is empty or IndexOutOfBoundsExcepion if the Publisher produces * more than one element. * * @param the value type */ public final class PublisherAsSingle implements Single.OnSubscribe { final Publisher publisher; public PublisherAsSingle(Publisher publisher) { this.publisher = publisher; } @Override public void call(SingleSubscriber t) { publisher.subscribe(new PublisherAsSingleSubscriber(t)); } static final class PublisherAsSingleSubscriber implements Subscriber, rx.Subscription { final SingleSubscriber actual; Subscription s; T value; boolean hasValue; boolean done; public PublisherAsSingleSubscriber(SingleSubscriber actual) { this.actual = actual; } @Override public void onSubscribe(Subscription s) { this.s = s; actual.add(this); s.request(Long.MAX_VALUE); } @Override public void onNext(T t) { if (done) { return; } if (hasValue) { done = true; s.cancel(); actual.onError(new IndexOutOfBoundsException("The source Publisher emitted multiple values")); } else { value = t; hasValue = true; } } @Override public void onError(Throwable t) { if (done) { return; } actual.onError(t); } @Override public void onComplete() { if (done) { return; } if (hasValue) { T v = value; value = null; actual.onSuccess(v); } else { actual.onError(new NoSuchElementException("The source Publisher was empty")); } } @Override public boolean isUnsubscribed() { return actual.isUnsubscribed(); } @Override public void unsubscribe() { s.cancel(); } } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/RxJavaSynchronizedProducer.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import java.util.*; import org.reactivestreams.Subscription; public final class RxJavaSynchronizedProducer implements rx.Producer, rx.Subscription { private final Subscription subscription; private volatile boolean unsubscribed; /** Guarded by this. */ private boolean emitting; /** Guarded by this. */ private List requests; public RxJavaSynchronizedProducer(Subscription subscription) { if (subscription == null) { throw new NullPointerException("subscription"); } this.subscription = subscription; } @Override public boolean isUnsubscribed() { return unsubscribed; } @Override public void request(long n) { if (n > 0 && !unsubscribed) { synchronized (this) { if (unsubscribed) { return; } if (emitting) { if (requests == null) { requests = new ArrayList(4); } requests.add(n); return; } emitting = true; } boolean skipFinal = false; try { subscription.request(n); for (;;) { List list; synchronized (this) { list = requests; requests = null; if (list == null) { emitting = false; skipFinal = true; return; } } for (Long v : list) { if (v.longValue() == 0L) { unsubscribed = true; subscription.cancel(); skipFinal = true; return; } else { subscription.request(v); } } } } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } } } @Override public void unsubscribe() { if (!unsubscribed) { synchronized (this) { if (unsubscribed) { return; } if (emitting) { // replace all pending requests with this single cancel indicator requests = new ArrayList(4); requests.add(0L); return; } emitting = true; } unsubscribed = true; subscription.cancel(); // no need to leave emitting as this is a terminal state } } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/SingleAsPublisher.java ================================================ /** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import rx.Single; import rx.SingleSubscriber; import java.util.concurrent.atomic.AtomicInteger; /** * Wraps a Single and exposes it as a Publisher. * * @param the value type */ public final class SingleAsPublisher implements Publisher { final Single single; public SingleAsPublisher(Single single) { this.single = single; } @Override public void subscribe(Subscriber s) { SingleAsPublisherSubscriber parent = new SingleAsPublisherSubscriber(s); s.onSubscribe(parent); single.subscribe(parent); } static final class SingleAsPublisherSubscriber extends SingleSubscriber implements Subscription { final Subscriber actual; final AtomicInteger state; T value; volatile boolean cancelled; static final int NO_REQUEST_NO_VALUE = 0; static final int NO_REQUEST_HAS_VALUE = 1; static final int HAS_REQUEST_NO_VALUE = 2; static final int HAS_REQUEST_HAS_VALUE = 3; public SingleAsPublisherSubscriber(Subscriber actual) { this.actual = actual; this.state = new AtomicInteger(); } @Override public void onSuccess(T value) { if (cancelled) { return; } if (value == null) { state.lazySet(HAS_REQUEST_HAS_VALUE); actual.onError(new NullPointerException("value")); return; } for (;;) { int s = state.get(); if (s == NO_REQUEST_HAS_VALUE || s == HAS_REQUEST_HAS_VALUE || cancelled) { break; } else if (s == HAS_REQUEST_NO_VALUE) { actual.onNext(value); if (!cancelled) { actual.onComplete(); } return; } else { this.value = value; if (state.compareAndSet(s, NO_REQUEST_HAS_VALUE)) { break; } } } } @Override public void onError(Throwable error) { if (cancelled) { return; } state.lazySet(HAS_REQUEST_HAS_VALUE); actual.onError(error); } @Override public void request(long n) { if (n > 0) { for (;;) { int s = state.get(); if (s == HAS_REQUEST_HAS_VALUE || s == HAS_REQUEST_NO_VALUE || cancelled) { break; } if (s == NO_REQUEST_HAS_VALUE) { if (state.compareAndSet(s, HAS_REQUEST_HAS_VALUE)) { T v = value; value = null; actual.onNext(v); if (!cancelled) { actual.onComplete(); } } break; } if (state.compareAndSet(NO_REQUEST_NO_VALUE, HAS_REQUEST_NO_VALUE)) { break; } } } } @Override public void cancel() { if (!cancelled) { cancelled = true; if (state.getAndSet(HAS_REQUEST_HAS_VALUE) == NO_REQUEST_HAS_VALUE) { value = null; } unsubscribe(); } } } } ================================================ FILE: rxjava-reactive-streams/src/main/java/rx/internal/reactivestreams/SubscriberAdapter.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.reactivestreams; import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.*; public class SubscriberAdapter implements Subscriber { private final rx.Subscriber rxSubscriber; private final AtomicBoolean started = new AtomicBoolean(); public SubscriberAdapter(rx.Subscriber rxSubscriber) { this.rxSubscriber = rxSubscriber; } @Override public void onSubscribe(final Subscription rsSubscription) { if (rsSubscription == null) { throw new NullPointerException("onSubscribe(null)"); } if (started.compareAndSet(false, true)) { RxJavaSynchronizedProducer sp = new RxJavaSynchronizedProducer(rsSubscription); rxSubscriber.add(sp); rxSubscriber.setProducer(sp); } else { rsSubscription.cancel(); } } @Override public void onNext(T t) { if (t == null) { throw new NullPointerException("onNext(null)"); } rxSubscriber.onNext(t); } @Override public void onError(Throwable t) { if (t == null) { throw new NullPointerException("onError(null)"); } rxSubscriber.onError(t); } @Override public void onComplete() { rxSubscriber.onCompleted(); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/NonTckTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import static org.testng.Assert.*; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static rx.RxReactiveStreams.toObservable; import static rx.RxReactiveStreams.toPublisher; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.reactivestreams.Publisher; import org.testng.annotations.Test; import rx.Observable; import rx.Subscriber; import rx.reactivestreams.test.IterablePublisher; import rx.reactivestreams.test.RsSubscriber; import rx.reactivestreams.test.RxSubscriber; import rx.subjects.PublishSubject; public class NonTckTest { private RsSubscriber subscribe(Observable observable) { return subscribe(toPublisher(observable)); } private RsSubscriber subscribe(Publisher publisher) { RsSubscriber subscriber = new RsSubscriber(); publisher.subscribe(subscriber); return subscriber; } @Test public void canSubscribeToObservableAsPublisher() { RsSubscriber subscriber = subscribe(Observable.just(1, 2, 3)); assertEquals("no items sent", 0, subscriber.received.size()); subscriber.subscription.request(1); assertEquals("one item sent", 1, subscriber.received.size()); subscriber.subscription.request(2); assertEquals("two items sent", 3, subscriber.received.size()); assertTrue(subscriber.complete); assertNull(subscriber.error); } @Test public void canSubscribeToPublisherAsObservable() { Publisher publisher = new IterablePublisher(Arrays.asList(1, 2, 3)); Observable observable = toObservable(publisher); RxSubscriber subscriber = new RxSubscriber(0); observable.subscribe(subscriber); assertEquals("no items sent", 0, subscriber.received.size()); subscriber.makeRequest(1); assertEquals("one item sent", 1, subscriber.received.size()); subscriber.makeRequest(2); assertEquals("two items sent", 3, subscriber.received.size()); assertTrue(subscriber.complete); assertNull(subscriber.error); } @Test public void rxSubscriberNotMakingInitialRequestConsumesPublisher() { Publisher publisher = new IterablePublisher(Arrays.asList(1, 2, 3)); Observable observable = toObservable(publisher); RxSubscriber subscriber = new RxSubscriber(-1); // -1 means no initial request observable.subscribe(subscriber); assertEquals("all items sent", 3, subscriber.received.size()); assertTrue(subscriber.complete); assertNull(subscriber.error); } @Test void errorStatePublisherSendsSingleErrorPostSubscribe() { RsSubscriber subscriber = subscribe(Observable.error(new RuntimeException("!"))); // An error state observable always allows subscription, but then immediately sends onError. // The spec suggests not trying to subscribe but immediately firing onError without an onSubscribe. // However, this isn't a spec violation. assertNotNull(subscriber.subscription); assertFalse(subscriber.complete); assertEquals(subscriber.error.getClass(), RuntimeException.class); assertEquals(subscriber.error.getMessage(), "!"); } @Test void rxFailingOnSubscribeSendsSingleErrorPostSubscribe() { RsSubscriber subscriber = subscribe(Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { throw new RuntimeException("!"); } })); // An error state observable always allows subscription, but then immediately sends onError. // The spec suggests not trying to subscribe but immediately firing onError without an onSubscribe. // However, this isn't a spec violation. assertNotNull(subscriber.subscription); assertFalse(subscriber.complete); assertEquals(subscriber.error.getClass(), RuntimeException.class); assertEquals(subscriber.error.getMessage(), "!"); } @Test(enabled = false) // failing void subscribingToHotObservableWithNoBackpressureStrategy() throws InterruptedException { RsSubscriber subscriber = subscribe(Observable.interval(1, TimeUnit.NANOSECONDS)); // Long enough for the observable to fire if it's going to Thread.sleep(10); assertEquals(subscriber.received.size(), 0); // fails, data is coming through before being requested } @Test void subscribingToHotObservableWithBackpressureStrategy() throws InterruptedException { Observable observable = Observable.interval(1, TimeUnit.NANOSECONDS).onBackpressureDrop(); RsSubscriber subscriber = subscribe(observable); subscriber.subscription.request(1); subscriber.waitForNumItems(1); assertEquals(subscriber.received.size(), 1); assertNull(subscriber.error); subscriber.subscription.request(10); subscriber.waitForNumItems(11); assertEquals(subscriber.received.size(), 11); assertNull(subscriber.error); subscriber.subscription.cancel(); } @Test public void subscribeToPublishSubjectEmitsRuleViolationException() { PublishSubject source = PublishSubject.create(); RsSubscriber rxs = subscribe(source); source.onNext(1); assertEquals(0, rxs.received.size()); assertNotNull(rxs.error); } @Test public void subscribeToPublishSubjectEmitsRuleViolationExceptionAfterOneRequest() { PublishSubject source = PublishSubject.create(); RsSubscriber rxs = subscribe(source); rxs.subscription.request(1); source.onNext(1); source.onNext(2); assertEquals(1, rxs.received.size()); assertNotNull(rxs.error); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckAsynchronousPublisherTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.Test; import rx.Observable; import rx.RxReactiveStreams; import rx.reactivestreams.test.CountdownIterable; import rx.schedulers.Schedulers; @Test public class TckAsynchronousPublisherTest extends PublisherVerification { public TckAsynchronousPublisherTest() { super(new TestEnvironment(300L)); } @Override public Publisher createPublisher(long elements) { return RxReactiveStreams.toPublisher(Observable.from(new CountdownIterable(elements)).observeOn(Schedulers.computation())); } @Override public Publisher createFailedPublisher() { // Null because we always successfully subscribe. // If the observable is in error state, it will subscribe and then emit the error as the first item // This is not an “error state” publisher as defined by RS return null; } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckCompletableAsyncConversionTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import java.io.IOException; import org.reactivestreams.Publisher; import org.reactivestreams.tck.*; import org.testng.annotations.Test; import rx.*; import rx.schedulers.Schedulers; @Test public class TckCompletableAsyncConversionTest extends PublisherVerification { public TckCompletableAsyncConversionTest() { super(new TestEnvironment(300L)); } @Override public Publisher createPublisher(long elements) { return RxReactiveStreams.toPublisher(Completable.complete().observeOn(Schedulers.computation())); } @Override public long maxElementsFromPublisher() { return 0L; } @Override public Publisher createFailedPublisher() { return RxReactiveStreams.toPublisher(Completable.error(new IOException()).observeOn(Schedulers.computation())); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckCompletableConversionTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import java.io.IOException; import org.reactivestreams.Publisher; import org.reactivestreams.tck.*; import org.testng.annotations.Test; import rx.*; @Test public class TckCompletableConversionTest extends PublisherVerification { public TckCompletableConversionTest() { super(new TestEnvironment(300L)); } @Override public Publisher createPublisher(long elements) { return RxReactiveStreams.toPublisher(Completable.complete()); } @Override public long maxElementsFromPublisher() { return 0L; } @Override public Publisher createFailedPublisher() { return RxReactiveStreams.toPublisher(Completable.error(new IOException())); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckSingleAsyncConversionTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import java.io.IOException; import org.reactivestreams.Publisher; import org.reactivestreams.tck.*; import org.testng.annotations.Test; import rx.*; import rx.schedulers.Schedulers; @Test public class TckSingleAsyncConversionTest extends PublisherVerification { public TckSingleAsyncConversionTest() { super(new TestEnvironment(300L)); } @Override public Publisher createPublisher(long elements) { return RxReactiveStreams.toPublisher(Single.just(1L).observeOn(Schedulers.computation())); } @Override public long maxElementsFromPublisher() { return 1L; } @Override public Publisher createFailedPublisher() { return RxReactiveStreams.toPublisher(Single.error(new IOException()).observeOn(Schedulers.computation())); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckSingleConversionTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import java.io.IOException; import org.reactivestreams.Publisher; import org.reactivestreams.tck.*; import org.testng.annotations.Test; import rx.*; @Test public class TckSingleConversionTest extends PublisherVerification { public TckSingleConversionTest() { super(new TestEnvironment(300L)); } @Override public Publisher createPublisher(long elements) { return RxReactiveStreams.toPublisher(Single.just(1L)); } @Override public long maxElementsFromPublisher() { return 1L; } @Override public Publisher createFailedPublisher() { return RxReactiveStreams.toPublisher(Single.error(new IOException())); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckSubscriberBlackboxTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.tck.SubscriberBlackboxVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.Test; import rx.Observable; import rx.RxReactiveStreams; import rx.internal.reactivestreams.SubscriberAdapter; import rx.reactivestreams.test.CountdownIterable; @Test public class TckSubscriberBlackboxTest extends SubscriberBlackboxVerification { public static final long DEFAULT_TIMEOUT_MILLIS = 300L; public TckSubscriberBlackboxTest() { super(new TestEnvironment(DEFAULT_TIMEOUT_MILLIS)); } @Override public Subscriber createSubscriber() { rx.Subscriber rxSubscriber = new rx.Subscriber() { @Override public void onStart() { super.request(1); } @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Long aLong) { request(1); } }; rxSubscriber.onStart(); // Observable.subscribe() calls this automatically return new SubscriberAdapter(rxSubscriber); } @Override public Long createElement(int element) { return Long.valueOf(Integer.toString(element)); } @Override public Publisher createHelperPublisher(long elements) { return RxReactiveStreams.toPublisher(Observable.from(new CountdownIterable(elements))); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckSubscriberWhiteboxTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.Test; import rx.Observable; import rx.RxReactiveStreams; import rx.internal.reactivestreams.SubscriberAdapter; import rx.reactivestreams.test.CountdownIterable; import java.util.concurrent.atomic.AtomicBoolean; @Test public class TckSubscriberWhiteboxTest extends SubscriberWhiteboxVerification { public static final long DEFAULT_TIMEOUT_MILLIS = 300L; public TckSubscriberWhiteboxTest() { super(new TestEnvironment(DEFAULT_TIMEOUT_MILLIS)); } private static class IgnoreSubscriber extends rx.Subscriber { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(T t) { } } @Override public Subscriber createSubscriber(final WhiteboxSubscriberProbe probe) { return new SubscriberAdapter(new IgnoreSubscriber()) { @Override public void onSubscribe(final Subscription rsSubscription) { final AtomicBoolean cancelled = new AtomicBoolean(); super.onSubscribe(new Subscription() { @Override public void request(long n) { rsSubscription.request(n); } @Override public void cancel() { cancelled.set(true); rsSubscription.cancel(); } }); if (!cancelled.get()) { probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { rsSubscription.request(elements); } @Override public void signalCancel() { rsSubscription.cancel(); } }); } } @Override public void onNext(Long aLong) { probe.registerOnNext(aLong); super.onNext(aLong); } @Override public void onError(Throwable t) { probe.registerOnError(t); super.onError(t); } @Override public void onComplete() { probe.registerOnComplete(); super.onComplete(); } }; } @Override public Long createElement(int element) { return Long.valueOf(Integer.toString(element)); } @Override public Publisher createHelperPublisher(long elements) { return RxReactiveStreams.toPublisher(Observable.from(new CountdownIterable(elements))); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/TckSynchronousPublisherTest.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.Test; import rx.Observable; import rx.RxReactiveStreams; import rx.reactivestreams.test.CountdownIterable; @Test public class TckSynchronousPublisherTest extends PublisherVerification { public TckSynchronousPublisherTest() { super(new TestEnvironment(300L)); } @Override public Publisher createPublisher(long elements) { return RxReactiveStreams.toPublisher(Observable.from(new CountdownIterable(elements))); } @Override public Publisher createFailedPublisher() { // Null because we always successfully subscribe. // If the observable is in error state, it will subscribe and then emit the error as the first item // This is not an “error state” publisher as defined by RS return null; } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/CompletableAsPublisherTest.java ================================================ package rx.reactivestreams.test; import org.testng.Assert; import org.testng.annotations.Test; import rx.*; import rx.subjects.PublishSubject; import static rx.RxReactiveStreams.*; public class CompletableAsPublisherTest { @Test(expectedExceptions = { NullPointerException.class }) public void nullCheck() { toPublisher((Completable)null); } @Test public void empty() { RsSubscriber ts = new RsSubscriber(); toPublisher(Completable.complete()).subscribe(ts); Assert.assertTrue(ts.complete); Assert.assertNull(ts.error); Assert.assertTrue(ts.received.isEmpty()); } @Test public void error() { RsSubscriber ts = new RsSubscriber(); toPublisher(Completable.error(new RuntimeException("Forced failure"))).subscribe(ts); Assert.assertFalse(ts.complete); Assert.assertNotNull(ts.error); Assert.assertTrue(ts.error instanceof RuntimeException); Assert.assertEquals(ts.error.getMessage(), "Forced failure"); Assert.assertTrue(ts.received.isEmpty()); } @Test public void cancellation() { RsSubscriber ts = new RsSubscriber(); PublishSubject ps = PublishSubject.create(); toPublisher(ps.toCompletable()).subscribe(ts); Assert.assertTrue(ps.hasObservers()); ts.subscription.cancel(); Assert.assertFalse(ts.complete); Assert.assertNull(ts.error); Assert.assertTrue(ts.received.isEmpty()); Assert.assertFalse(ps.hasObservers()); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/CountdownIterable.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.test; import java.util.Iterator; public class CountdownIterable implements Iterable { private final long from; public CountdownIterable(final long from) { if (from < 0) { throw new IllegalArgumentException("from < 0"); } this.from = from; } @Override public Iterator iterator() { return new Iterator() { private long i = from; @Override public boolean hasNext() { return i > 0; } @Override public Long next() { return --i; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/IterablePublisher.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.Iterator; public class IterablePublisher implements Publisher { private final Iterable iterable; public IterablePublisher(Iterable iterable) { this.iterable = iterable; } @Override public void subscribe(final Subscriber subscriber) { subscriber.onSubscribe(new Subscription() { Iterator iterator = iterable.iterator(); @Override public void request(long n) { for (int i = 0; i < n; ++i) { if (iterator.hasNext()) { T next; try { next = iterator.next(); } catch (Exception e) { subscriber.onError(e); return; } subscriber.onNext(next); } else { break; } } if (!iterator.hasNext()) { subscriber.onComplete(); } } @Override public void cancel() { } }); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/PublisherAsCompletableTest.java ================================================ package rx.reactivestreams.test; import static rx.RxReactiveStreams.*; import org.reactivestreams.*; import org.testng.Assert; import org.testng.annotations.Test; import rx.observers.TestSubscriber; import rx.subjects.PublishSubject; public class PublisherAsCompletableTest { @Test(expectedExceptions = { NullPointerException.class }) public void nullCheck() { toCompletable(null); } @Test public void empty() { TestSubscriber ts = new TestSubscriber(); toCompletable(new PublisherEmpty()).subscribe(ts); ts.assertNoValues(); ts.assertCompleted(); ts.assertNoErrors(); } @Test public void error() { TestSubscriber ts = new TestSubscriber(); toCompletable(new PublisherFail()).subscribe(ts); ts.assertNoValues(); ts.assertNotCompleted(); ts.assertError(RuntimeException.class); Assert.assertEquals(ts.getOnErrorEvents().get(0).getMessage(), "Forced failure"); } @Test public void cancellation() { PublishSubject ps = PublishSubject.create(); TestSubscriber ts = new TestSubscriber(); toCompletable(toPublisher(ps)).subscribe(ts); Assert.assertTrue(ps.hasObservers()); ts.unsubscribe(); ts.assertNoValues(); ts.assertNotCompleted(); ts.assertNoErrors(); Assert.assertFalse(ps.hasObservers()); } static final class PublisherEmpty implements Publisher { @Override public void subscribe(Subscriber s) { final boolean[] cancelled = { false }; s.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { cancelled[0] = true; } }); if (!cancelled[0]) { s.onComplete(); } } } static final class PublisherFail implements Publisher { @Override public void subscribe(Subscriber s) { final boolean[] cancelled = { false }; s.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { cancelled[0] = true; } }); if (!cancelled[0]) { s.onError(new RuntimeException("Forced failure")); } } } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/PublisherAsSingleTest.java ================================================ package rx.reactivestreams.test; import org.testng.Assert; import org.testng.annotations.Test; import rx.Observable; import rx.Single; import rx.observers.TestSubscriber; import rx.reactivestreams.test.PublisherAsCompletableTest.PublisherEmpty; import rx.reactivestreams.test.PublisherAsCompletableTest.PublisherFail; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import static rx.RxReactiveStreams.toPublisher; import static rx.RxReactiveStreams.toSingle; public class PublisherAsSingleTest { @Test(expectedExceptions = { NullPointerException.class }) public void nullCheck() { toPublisher((Single)null); } @Test public void just() { TestSubscriber ts = new TestSubscriber(); toSingle(toPublisher(Observable.just(1))).subscribe(ts); ts.assertValue(1); ts.assertCompleted(); ts.assertNoErrors(); } @Test public void singleJust() { TestSubscriber ts = new TestSubscriber(); toSingle(toPublisher(Single.just(1))).subscribeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(3, TimeUnit.SECONDS); ts.assertValue(1); ts.assertCompleted(); ts.assertNoErrors(); } @Test public void empty() { TestSubscriber ts = new TestSubscriber(); toSingle(new PublisherEmpty()).subscribe(ts); ts.assertNoValues(); ts.assertNotCompleted(); ts.assertError(NoSuchElementException.class); } @Test public void range() { TestSubscriber ts = new TestSubscriber(); toSingle(toPublisher(Observable.range(1, 2))).subscribe(ts); ts.assertNoValues(); ts.assertNotCompleted(); ts.assertError(IndexOutOfBoundsException.class); } @Test public void error() { TestSubscriber ts = new TestSubscriber(); toSingle(new PublisherFail()).subscribe(ts); ts.assertNoValues(); ts.assertNotCompleted(); ts.assertError(RuntimeException.class); Assert.assertEquals(ts.getOnErrorEvents().get(0).getMessage(), "Forced failure"); } @Test public void cancellation() { PublishSubject ps = PublishSubject.create(); TestSubscriber ts = new TestSubscriber(); toSingle(toPublisher(ps)).subscribe(ts); Assert.assertTrue(ps.hasObservers()); ts.unsubscribe(); ts.assertNoValues(); ts.assertNotCompleted(); ts.assertNoErrors(); Assert.assertFalse(ps.hasObservers()); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/RsSubscriber.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; public class RsSubscriber implements Subscriber { public final Queue received = new ConcurrentLinkedQueue(); public volatile Subscription subscription; public volatile Throwable error; public volatile boolean complete; private static class Wait { private final long count; private final CountDownLatch latch; public Wait(long count, CountDownLatch latch) { this.count = count; this.latch = latch; } } private final List waits = new CopyOnWriteArrayList(); @Override public void onSubscribe(Subscription s) { if (s == null) { throw new NullPointerException("onSubscribe(null)"); } subscription = s; } @Override public void onNext(T t) { if (t == null) { throw new NullPointerException("onNext(null)"); } received.add(t); for (Wait wait : waits) { if (received.size() >= wait.count) { wait.latch.countDown(); } } } @Override public void onError(Throwable t) { if (t == null) { throw new NullPointerException("onError(null)"); } error = t; unwaitAll(); } @Override public void onComplete() { complete = true; unwaitAll(); } public void waitForNumItems(long n) throws InterruptedException { if (complete || error != null) { return; } CountDownLatch latch = new CountDownLatch(1); waits.add(new Wait(n, latch)); if (complete || error != null) { unwaitAll(); } if (received.size() >= n) { latch.countDown(); } latch.await(); } private void unwaitAll() { while (!waits.isEmpty()) { waits.remove(0).latch.countDown(); } } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/RxSubscriber.java ================================================ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.test; import rx.Subscriber; import java.util.LinkedList; import java.util.List; public class RxSubscriber extends Subscriber { public final List received = new LinkedList(); private final long initialRequest; public Throwable error; public boolean complete; public RxSubscriber(long initialRequest) { this.initialRequest = initialRequest; } @Override public void onStart() { if (initialRequest >= 0) { request(initialRequest); } } @Override public void onCompleted() { complete = true; } @Override public void onError(Throwable e) { error = e; } @Override public void onNext(T t) { received.add(t); } public void makeRequest(long n) { request(n); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/SingleAsPublisherTest.java ================================================ package rx.reactivestreams.test; import org.testng.Assert; import org.testng.annotations.Test; import rx.*; import rx.subjects.PublishSubject; import static rx.RxReactiveStreams.*; public class SingleAsPublisherTest { @Test(expectedExceptions = { NullPointerException.class }) public void nullCheck() { toPublisher((Single)null); } @Test public void just() { RsSubscriber ts = new RsSubscriber(); toPublisher(Single.just(1)).subscribe(ts); Assert.assertFalse(ts.complete); Assert.assertNull(ts.error); Assert.assertTrue(ts.received.isEmpty()); ts.subscription.request(1); Assert.assertTrue(ts.complete); Assert.assertNull(ts.error); Assert.assertEquals(ts.received.size(), 1); Assert.assertEquals(ts.received.poll(), 1); } @Test public void justNull() { RsSubscriber ts = new RsSubscriber(); toPublisher(Single.just(null)).subscribe(ts); Assert.assertFalse(ts.complete); Assert.assertNotNull(ts.error); Assert.assertTrue(ts.error instanceof NullPointerException); Assert.assertTrue(ts.received.isEmpty()); } @Test public void error() { RsSubscriber ts = new RsSubscriber(); toPublisher(Single.error(new RuntimeException("Forced failure"))).subscribe(ts); Assert.assertFalse(ts.complete); Assert.assertNotNull(ts.error); Assert.assertTrue(ts.error instanceof RuntimeException); Assert.assertEquals(ts.error.getMessage(), "Forced failure"); Assert.assertTrue(ts.received.isEmpty()); } @Test public void cancellation() { RsSubscriber ts = new RsSubscriber(); PublishSubject ps = PublishSubject.create(); toPublisher(ps.toSingle()).subscribe(ts); Assert.assertTrue(ps.hasObservers()); ts.subscription.cancel(); Assert.assertFalse(ts.complete); Assert.assertNull(ts.error); Assert.assertTrue(ts.received.isEmpty()); Assert.assertFalse(ps.hasObservers()); } } ================================================ FILE: rxjava-reactive-streams/src/test/java/rx/reactivestreams/test/WrapUnwrap.java ================================================ /** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.reactivestreams.test; import org.reactivestreams.Publisher; import org.testng.annotations.Test; import rx.*; import rx.functions.Func1; public class WrapUnwrap { @Test public void wrapUnwrap() { Observable o = Observable.range(1, 350); Observable> p = Observable.just( RxReactiveStreams.toPublisher(o)).asObservable(); for (int u : p.flatMap(new Func1, Observable>() { @Override public Observable call(Publisher v) { return RxReactiveStreams.toObservable(v); } }) .toBlocking() .toIterable()) { System.out.println(u); } } } ================================================ FILE: settings.gradle ================================================ rootProject.name = 'rxjava-reactive-streams' include "rxjava-reactive-streams" if (JavaVersion.current().java8Compatible) { include "examples:ratpack" }