├── .github ├── ISSUE_TEMPLATE │ ├── ---1-report-an-issue.md │ ├── ---2-feature-request.md │ └── config.yml ├── pull_request_template.md └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── PATENTS ├── ParseLiveQuery ├── build.gradle ├── release-proguard.pro └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── parse │ │ └── livequery │ │ ├── ClientOperation.java │ │ ├── ConnectClientOperation.java │ │ ├── LiveQueryException.java │ │ ├── OkHttp3SocketClientFactory.java │ │ ├── ParseLiveQueryClient.java │ │ ├── ParseLiveQueryClientCallbacks.java │ │ ├── ParseLiveQueryClientImpl.java │ │ ├── SubscribeClientOperation.java │ │ ├── Subscription.java │ │ ├── SubscriptionHandling.java │ │ ├── UnsubscribeClientOperation.java │ │ ├── WebSocketClient.java │ │ └── WebSocketClientFactory.java │ └── test │ └── java │ └── com │ └── parse │ ├── ImmediateExecutor.java │ ├── TestOkHttpClientFactory.java │ └── TestParseLiveQueryClient.java ├── README.md ├── THIRD_PARTY_NOTICES.txt ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.github/ISSUE_TEMPLATE/---1-report-an-issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F41B Report an issue" 3 | about: A feature is not working as expected. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### New Issue Checklist 11 | 16 | 17 | - [ ] I am not disclosing a [vulnerability](https://github.com/parse-community/ParseLiveQuery-Android/security/policy). 18 | - [ ] I am not just asking a [question](https://github.com/parse-community/.github/blob/main/SUPPORT.md). 19 | - [ ] I have searched through [existing issues](https://github.com/parse-community/ParseLiveQuery-Android/issues?q=is%3Aissue). 20 | - [ ] I can reproduce the issue with the latest version of [Parse Server](https://github.com/parse-community/parse-server/releases) and the [Parse LiveQuery Android SDK](https://github.com/parse-community/ParseLiveQuery-Android/releases). 21 | 22 | ### Issue Description 23 | 24 | 25 | ### Steps to reproduce 26 | 27 | 28 | ### Actual Outcome 29 | 30 | 31 | ### Expected Outcome 32 | 33 | 34 | ### Environment 35 | 36 | 37 | Parse LiveQuery Android SDK 38 | - SDK version: `FILL_THIS_OUT` 39 | - Operating system version: `FILL_THIS_OUT` 40 | 41 | Server 42 | - Parse Server version: `FILL_THIS_OUT` 43 | - Operating system: `FILL_THIS_OUT` 44 | - Local or remote host (AWS, Azure, Google Cloud, Heroku, Digital Ocean, etc): `FILL_THIS_OUT` 45 | 46 | Database 47 | - System (MongoDB or Postgres): `FILL_THIS_OUT` 48 | - Database version: `FILL_THIS_OUT` 49 | - Local or remote host (MongoDB Atlas, mLab, AWS, Azure, Google Cloud, etc): `FILL_THIS_OUT` 50 | 51 | ### Logs 52 | 53 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---2-feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F4A1 Request a feature" 3 | about: Suggest new functionality or an enhancement of existing functionality. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### New Feature / Enhancement Checklist 11 | 16 | 17 | - [ ] I am not disclosing a [vulnerability](https://github.com/parse-community/ParseLiveQuery-Android/security/policy). 18 | - [ ] I am not just asking a [question](https://github.com/parse-community/.github/blob/main/SUPPORT.md). 19 | - [ ] I have searched through [existing issues](https://github.com/parse-community/ParseLiveQuery-Android/issues?q=is%3Aissue). 20 | 21 | ### Current Limitation 22 | 23 | 24 | ### Feature / Enhancement Description 25 | 26 | 27 | ### Example Use Case 28 | 29 | 30 | ### Alternatives / Workarounds 31 | 32 | 33 | ### 3rd Party References 34 | 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: 🙋🏽‍♀️ Getting help with code 4 | url: https://stackoverflow.com/questions/tagged/parse-platform 5 | about: Get help with code-level questions on Stack Overflow. 6 | - name: 🙋 Getting general help 7 | url: https://community.parseplatform.org 8 | about: Get help with other questions on our Community Forum. 9 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### New Pull Request Checklist 2 | 7 | 8 | - [ ] I am not disclosing a [vulnerability](https://github.com/parse-community/ParseLiveQuery-Android/blob/master/SECURITY.md). 9 | - [ ] I am creating this PR in reference to an [issue](https://github.com/parse-community/ParseLiveQuery-Android/issues?q=is%3Aissue). 10 | 11 | ### Issue Description 12 | 13 | 14 | Related issue: #`FILL_THIS_OUT` 15 | 16 | ### Approach 17 | 18 | 19 | ### TODOs before merging 20 | 24 | 25 | - [ ] Add tests 26 | - [ ] Add changes to documentation (guides, repository pages, in-code descriptions) 27 | - [ ] Add changelog entry 28 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 2 | 3 | name: ci 4 | on: 5 | push: 6 | branches: 7 | - master 8 | pull_request: 9 | branches: 10 | - '**' 11 | jobs: 12 | check-lint: 13 | name: Lint 14 | timeout-minutes: 5 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Fetch Sources 18 | uses: actions/checkout@v2 19 | - name: Set up JDK 11 20 | uses: actions/setup-java@v2 21 | with: 22 | java-version: '11' 23 | distribution: 'adopt' 24 | - name: Setup Gradle Dependencies Cache 25 | uses: actions/cache@v2 26 | with: 27 | path: ~/.gradle/caches 28 | key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle', '**/*.gradle.kts') }} 29 | - name: Setup Gradle Wrapper Cache 30 | uses: actions/cache@v2 31 | with: 32 | path: ~/.gradle/wrapper 33 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }} 34 | - name: Spotless check 35 | run: ./gradlew spotlessCheck --no-daemon 36 | check-gradlewrapper: 37 | name: Gradle Wrapper 38 | timeout-minutes: 5 39 | runs-on: ubuntu-latest 40 | steps: 41 | - name: Fetch Sources 42 | uses: actions/checkout@v2 43 | - name: Gradle Wrapper Validation 44 | uses: gradle/wrapper-validation-action@v1 45 | check-build: 46 | name: Gradle Build 47 | timeout-minutes: 15 48 | runs-on: ubuntu-latest 49 | steps: 50 | - name: Fetch Sources 51 | uses: actions/checkout@v2 52 | - name: Set up JDK 11 53 | uses: actions/setup-java@v2 54 | with: 55 | java-version: '11' 56 | distribution: 'adopt' 57 | - name: Setup Gradle Dependencies Cache 58 | uses: actions/cache@v2 59 | with: 60 | path: ~/.gradle/caches 61 | key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle', '**/*.gradle.kts') }} 62 | - name: Setup Gradle Wrapper Cache 63 | uses: actions/cache@v2 64 | with: 65 | path: ~/.gradle/wrapper 66 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }} 67 | - name: Run tests 68 | run: ./gradlew --no-daemon clean jacocoTestReport 69 | - name: Report test coverage 70 | run: | 71 | pip install --user codecov 72 | codecov 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # files for the dex VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # generated files 12 | bin/ 13 | gen/ 14 | 15 | # Local configuration file (sdk path, etc) 16 | local.properties 17 | 18 | # Android Studio 19 | .idea 20 | *.iml 21 | *.ipr 22 | *.iws 23 | classes 24 | gen-external-apklibs 25 | 26 | # Gradle 27 | .gradle 28 | build 29 | 30 | # Other 31 | .metadata 32 | */bin/* 33 | */gen/* 34 | testData 35 | testCache 36 | server.config 37 | 38 | # Jacoco 39 | jacoco.exec 40 | 41 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Changelog 2 | 3 | ### master 4 | 5 | ### 1.2.2 6 | - CHANGE: Change OkHttp dependency to allow for Android versions < 5.0 7 | 8 | ### 1.2.1 9 | > NOTE: 10 | > 11 | > This release requires Parse Android SDK >=`1.24.2` as dependency because of the transient depencency on the internalized bolts module. 12 | - CHANGE: Changed bolts references to use internalized bolts depedency. See [#1036](https://github.com/parse-community/Parse-SDK-Android/issues/1036) for details. Thanks to [Manuel Trezza](https://github.com/mtrezza) 13 | 14 | ### 1.2.0 15 | - Upgrade to avoid depending on outdated Bolts (#107) 16 | 17 | ### 1.1.0 18 | - Repackage from com.parse to com.parse.livequery 19 | - Bumps to use the latest dependency on JitPack for compatibility 20 | 21 | ### 1.0.6 22 | - Safely call close on the websocket client with synchronized calls 23 | thanks to @mmimeault (#83) 24 | 25 | ### 1.0.5 26 | - Back the subscriptions by a thread safe collection map thanks to @mmimeault (#80) 27 | 28 | ### 1.0.4 29 | - Change package name thanks to @hermanliang (#64) 30 | 31 | ### 1.0.3 32 | - Fix race condition by ensuring that op=connected has been received before sending a new subscribe event thanks to @jhansche (#48) 33 | 34 | ### 1.0.2 35 | - Dispatch better disconnect events thanks to @jhansche (#39) 36 | 37 | ### 1.0.1 38 | - getClient() method can get URL inferred from Parse.initialize() call thanks to @hermanliang (#30) 39 | - Bump to support Android API 25 (#32) 40 | - Bump to Parse Android 1.14.1 dependency (#32). 41 | - Switch from TubeSock library to OkHttp3 web scokets (#28) 42 | - Fix Locale lint errors thanks to @jhansche (#23) 43 | - Connect/disconnect on background executor thanks to @jhansche (#22) 44 | - Refactor ParseLiveQueryClient not to be typed thanks to @jhansche (#27) 45 | 46 | ### 1.0.0 47 | - Initial 1.0.0 release 48 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at codeofconduct@parseplatform.org. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Parse LiveQuery for Android 2 | We want to make contributing to this project as easy and transparent as possible. 3 | 4 | ## Code of Conduct 5 | Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated. 6 | 7 | ## Our Development Process 8 | Most of our work will be done in public directly on GitHub. There may be changes done through our internal source control, but it will be rare and only as needed. 9 | 10 | ### `master` is unsafe 11 | Our goal is to keep `master` stable, but there may be changes that your application may not be compatible with. We'll do our best to publicize any breaking changes, but try to use our specific releases in any production environment. 12 | 13 | ### Pull Requests 14 | We actively welcome your pull requests. When we get one, we'll run some Parse-specific integration tests on it first. From here, we'll need to get a core member to sign off on the changes and then merge the pull request. For API changes we may need to fix internal uses, which could cause some delay. We'll do our best to provide updates and feedback throughout the process. 15 | 16 | 1. Fork the repo and create your branch from `master`. 17 | 4. Add unit tests for any new code you add. 18 | 3. If you've changed APIs, update the documentation. 19 | 4. Ensure the test suite passes. 20 | 5. Make sure your code lints. 21 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 22 | 23 | ### Contributor License Agreement ("CLA") 24 | In order to accept your pull request, we need you to submit a CLA. You only need to do this once to work on any of Facebook's open source projects. 25 | 26 | Complete your CLA here: 27 | 28 | ## Bugs 29 | Although we try to keep developing on Parse easy, you still may run into some issues. General questions should be asked on [Google Groups][google-group], technical questions should be asked on [Stack Overflow][stack-overflow], and for everything else we'll be using GitHub issues. 30 | 31 | ### Known Issues 32 | We use GitHub issues to track public bugs. We will keep a close eye on this and try to make it clear when we have an internal fix in progress. Before filing a new issue, try to make sure your problem doesn't already exist. 33 | 34 | ### Reporting New Issues 35 | Details are key. The more information you provide us the easier it'll be for us to debug and the faster you'll receive a fix. Some examples of useful tidbits: 36 | 37 | * A description. What did you expect to happen and what actually happened? Why do you think that was wrong? 38 | * A simple unit test that fails. Refer [here][tests-dir] for examples of existing unit tests. See our [README](README.md#usage) for how to run unit tests. You can submit a pull request with your failing unit test so that our CI verifies that the test fails. 39 | * What version does this reproduce on? What version did it last work on? 40 | * [Stacktrace or GTFO][stacktrace-or-gtfo]. In all honesty, full stacktraces with line numbers make a happy developer. 41 | * Anything else you find relevant. 42 | 43 | ### Security Bugs 44 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. In those cases, please go through the process outlined on that page and do not file a public issue. 45 | 46 | ## Style Guide 47 | We're still working on providing a code style for your IDE and getting a linter on GitHub, but for now try to keep the following: 48 | 49 | * Most importantly, match the existing code style as much as possible. 50 | * Try to keep lines under 100 characters, if possible. 51 | 52 | ## License 53 | By contributing to Parse Android Parse LiveQuery, you agree that your contributions will be licensed under its license. 54 | 55 | [google-group]: https://groups.google.com/forum/#!forum/parse-developers 56 | [stack-overflow]: http://stackoverflow.com/tags/parse.com 57 | [bug-reports]: https://www.parse.com/help#report 58 | [rest-api]: https://www.parse.com/docs/rest/guide 59 | [network-debugging-tool]: https://github.com/ParsePlatform/ParseInterceptors-Android/wiki 60 | [parse-api-console]: http://blog.parse.com/announcements/introducing-the-parse-api-console/ 61 | [stacktrace-or-gtfo]: http://i.imgur.com/jacoj.jpg 62 | [tests-dir]: /Parse/src/test/java/com/parse 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD License 2 | 3 | For Parse LiveQueryClient for Android software 4 | 5 | Copyright (c) 2015-present, Parse, LLC. All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without modification, 8 | are permitted provided that the following conditions are met: 9 | 10 | * Redistributions of source code must retain the above copyright notice, this 11 | list of conditions and the following disclaimer. 12 | 13 | * Redistributions in binary form must reproduce the above copyright notice, 14 | this list of conditions and the following disclaimer in the documentation 15 | and/or other materials provided with the distribution. 16 | 17 | * Neither the name Parse nor the names of its contributors may be used to 18 | endorse or promote products derived from this software without specific 19 | prior written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 22 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 23 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 24 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 25 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 26 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 27 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 28 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 30 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | ----- 33 | 34 | As of April 5, 2017, Parse, LLC has transferred this code to the parse-community organization, and will no longer be contributing to or distributing this code. 35 | -------------------------------------------------------------------------------- /PATENTS: -------------------------------------------------------------------------------- 1 | Additional Grant of Patent Rights Version 2 2 | 3 | "Software" means the Parse Android LiveQuery Client software distributed by Parse, LLC. 4 | 5 | Parse, LLC. ("Parse") hereby grants to each recipient of the Software 6 | ("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable 7 | (subject to the termination provision below) license under any Necessary 8 | Claims, to make, have made, use, sell, offer to sell, import, and otherwise 9 | transfer the Software. For avoidance of doubt, no license is granted under 10 | Parse’s rights in any patent claims that are infringed by (i) modifications 11 | to the Software made by you or any third party or (ii) the Software in 12 | combination with any software or other technology. 13 | 14 | The license granted hereunder will terminate, automatically and without notice, 15 | if you (or any of your subsidiaries, corporate affiliates or agents) initiate 16 | directly or indirectly, or take a direct financial interest in, any Patent 17 | Assertion: (i) against Parse or any of its subsidiaries or corporate 18 | affiliates, (ii) against any party if such Patent Assertion arises in whole or 19 | in part from any software, technology, product or service of Parse or any of 20 | its subsidiaries or corporate affiliates, or (iii) against any party relating 21 | to the Software. Notwithstanding the foregoing, if Parse or any of its 22 | subsidiaries or corporate affiliates files a lawsuit alleging patent 23 | infringement against you in the first instance, and you respond by filing a 24 | patent infringement counterclaim in that lawsuit against that party that is 25 | unrelated to the Software, the license granted hereunder will not terminate 26 | under section (i) of this paragraph due to such counterclaim. 27 | 28 | A "Necessary Claim" is a claim of a patent owned by Parse that is 29 | necessarily infringed by the Software standing alone. 30 | 31 | A "Patent Assertion" is any lawsuit or other action alleging direct, indirect, 32 | or contributory infringement or inducement to infringe any patent, including a 33 | cross-claim or counterclaim. 34 | 35 | ----- 36 | 37 | As of April 5, 2017, Parse, LLC has transferred this code to the parse-community organization, and will no longer be contributing to or distributing this code. 38 | -------------------------------------------------------------------------------- /ParseLiveQuery/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.library" 2 | apply plugin: "com.github.kt3k.coveralls" 3 | 4 | android { 5 | compileSdkVersion 29 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 29 10 | versionCode 1 11 | versionName "1.0" 12 | consumerProguardFiles "release-proguard.pro" 13 | } 14 | 15 | lintOptions { 16 | abortOnError false 17 | } 18 | 19 | buildTypes { 20 | debug { 21 | testCoverageEnabled = true 22 | } 23 | } 24 | } 25 | 26 | dependencies { 27 | api "com.github.parse-community.Parse-SDK-Android:parse:1.24.2" 28 | 29 | // Note: Don't update past 3.12.x, as it sets the minSdk to Android 5.0 30 | api "com.squareup.okhttp3:okhttp:3.12.10" 31 | 32 | testImplementation "org.robolectric:robolectric:3.3.1" 33 | testImplementation "org.skyscreamer:jsonassert:1.5.0" 34 | testImplementation "junit:junit:4.12" 35 | testImplementation "org.mockito:mockito-core:1.10.19" 36 | } 37 | 38 | //region Code Coverage 39 | 40 | apply plugin: "jacoco" 41 | 42 | jacoco { 43 | toolVersion "0.7.1.201405082137" 44 | } 45 | 46 | task jacocoTestReport(type: JacocoReport, dependsOn: "testDebugUnitTest") { 47 | group = "Reporting" 48 | description = "Generate Jacoco coverage reports" 49 | 50 | classDirectories = fileTree( 51 | dir: "${buildDir}/intermediates/classes/debug", 52 | excludes: ['**/R.class', 53 | '**/R$*.class', 54 | '**/*$ViewInjector*.*', 55 | '**/BuildConfig.*', 56 | '**/Manifest*.*'] 57 | ) 58 | 59 | sourceDirectories = files("${buildDir.parent}/src/main/java") 60 | additionalSourceDirs = files([ 61 | "${buildDir}/generated/source/buildConfig/debug", 62 | "${buildDir}/generated/source/r/debug" 63 | ]) 64 | executionData = files("${buildDir}/jacoco/testDebugUnitTest.exec") 65 | 66 | reports { 67 | xml.enabled = true 68 | html.enabled = true 69 | } 70 | } 71 | 72 | //endregion 73 | 74 | //region Coveralls 75 | 76 | coveralls.jacocoReportPath = "${buildDir}/reports/jacoco/jacocoTestReport/jacocoTestReport.xml" 77 | 78 | //endregion 79 | 80 | apply from: "https://raw.githubusercontent.com/Commit451/gradle-android-javadocs/1.1.0/gradle-android-javadocs.gradle" 81 | -------------------------------------------------------------------------------- /ParseLiveQuery/release-proguard.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/opt/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Keep source file names, line numbers, and Parse class/method names for easier debugging 20 | -keepattributes SourceFile,LineNumberTable 21 | -keepnames class com.parse.** { *; } 22 | 23 | # Required for Parse 24 | -keepattributes *Annotation* 25 | -keepattributes Signature 26 | -dontwarn android.net.SSLCertificateSocketFactory 27 | -dontwarn android.app.Notification 28 | -dontwarn com.squareup.** 29 | -dontwarn okio.** 30 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/ClientOperation.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | 6 | abstract class ClientOperation { 7 | abstract JSONObject getJSONObjectRepresentation() throws JSONException; 8 | } 9 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/ConnectClientOperation.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | 6 | class ConnectClientOperation extends ClientOperation { 7 | 8 | private final String applicationId; 9 | private final String sessionToken; 10 | 11 | ConnectClientOperation(String applicationId, String sessionToken) { 12 | this.applicationId = applicationId; 13 | this.sessionToken = sessionToken; 14 | } 15 | 16 | @Override 17 | JSONObject getJSONObjectRepresentation() throws JSONException { 18 | JSONObject jsonObject = new JSONObject(); 19 | jsonObject.put("op", "connect"); 20 | jsonObject.put("applicationId", applicationId); 21 | jsonObject.put("sessionToken", sessionToken); 22 | return jsonObject; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/LiveQueryException.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import java.util.Locale; 4 | 5 | public abstract class LiveQueryException extends Exception { 6 | 7 | private LiveQueryException() { 8 | super(); 9 | } 10 | 11 | private LiveQueryException(String detailMessage) { 12 | super(detailMessage); 13 | } 14 | 15 | private LiveQueryException(String detailMessage, Throwable cause) { 16 | super(detailMessage, cause); 17 | } 18 | 19 | private LiveQueryException(Throwable cause) { 20 | super(cause); 21 | } 22 | 23 | /** 24 | * An error that is reported when any other unknown {@link RuntimeException} occurs unexpectedly. 25 | */ 26 | public static class UnknownException extends LiveQueryException { 27 | /* package */ UnknownException(String detailMessage, RuntimeException cause) { 28 | super(detailMessage, cause); 29 | } 30 | } 31 | 32 | /** 33 | * An error that is reported when the server returns a response that cannot be parsed. 34 | */ 35 | public static class InvalidResponseException extends LiveQueryException { 36 | /* package */ InvalidResponseException(String response) { 37 | super(response); 38 | } 39 | } 40 | 41 | /** 42 | * An error that is reported when the server does not accept a query we've sent to it. 43 | */ 44 | public static class InvalidQueryException extends LiveQueryException { 45 | 46 | } 47 | 48 | /** 49 | * An error that is reported when the server returns valid JSON, but it doesn't match the format we expect. 50 | */ 51 | public static class InvalidJSONException extends LiveQueryException { 52 | // JSON used for matching. 53 | private final String json; 54 | /// Key that was expected to match. 55 | private final String expectedKey; 56 | 57 | /* package */ InvalidJSONException(String json, String expectedKey) { 58 | super(String.format(Locale.US, "Invalid JSON; expectedKey: %s, json: %s", expectedKey, json)); 59 | this.json = json; 60 | this.expectedKey = expectedKey; 61 | } 62 | 63 | public String getJson() { 64 | return json; 65 | } 66 | 67 | public String getExpectedKey() { 68 | return expectedKey; 69 | } 70 | } 71 | 72 | /** 73 | * An error that is reported when the live query server encounters an internal error. 74 | */ 75 | public static class ServerReportedException extends LiveQueryException { 76 | 77 | private final int code; 78 | private final String error; 79 | private final boolean reconnect; 80 | 81 | public ServerReportedException(int code, String error, boolean reconnect) { 82 | super(String.format(Locale.US, "Server reported error; code: %d, error: %s, reconnect: %b", code, error, reconnect)); 83 | this.code = code; 84 | this.error = error; 85 | this.reconnect = reconnect; 86 | } 87 | 88 | public int getCode() { 89 | return code; 90 | } 91 | 92 | public String getError() { 93 | return error; 94 | } 95 | 96 | public boolean isReconnect() { 97 | return reconnect; 98 | } 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/OkHttp3SocketClientFactory.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import android.util.Log; 4 | 5 | import java.net.URI; 6 | import java.util.Locale; 7 | 8 | import okhttp3.OkHttpClient; 9 | import okhttp3.Request; 10 | import okhttp3.Response; 11 | import okhttp3.WebSocket; 12 | import okhttp3.WebSocketListener; 13 | import okio.ByteString; 14 | 15 | public class OkHttp3SocketClientFactory implements WebSocketClientFactory { 16 | 17 | OkHttpClient mClient; 18 | 19 | public OkHttp3SocketClientFactory(OkHttpClient client) { 20 | mClient = client; 21 | } 22 | 23 | public OkHttp3SocketClientFactory() { 24 | mClient = new OkHttpClient(); 25 | } 26 | 27 | @Override 28 | public WebSocketClient createInstance(WebSocketClient.WebSocketClientCallback webSocketClientCallback, URI hostUrl) { 29 | return new OkHttp3WebSocketClient(mClient, webSocketClientCallback, hostUrl); 30 | } 31 | 32 | static class OkHttp3WebSocketClient implements WebSocketClient { 33 | 34 | private static final String LOG_TAG = "OkHttpWebSocketClient"; 35 | 36 | private final WebSocketClientCallback webSocketClientCallback; 37 | private WebSocket webSocket; 38 | private volatile State state = State.NONE; 39 | private final OkHttpClient client; 40 | private final String url; 41 | private final int STATUS_CODE = 1000; 42 | private final String CLOSING_MSG = "User invoked close"; 43 | 44 | private final WebSocketListener handler = new WebSocketListener() { 45 | @Override 46 | public void onOpen(WebSocket webSocket, Response response) { 47 | setState(State.CONNECTED); 48 | webSocketClientCallback.onOpen(); 49 | } 50 | 51 | @Override 52 | public void onMessage(WebSocket webSocket, String text) { 53 | webSocketClientCallback.onMessage(text); 54 | } 55 | 56 | @Override 57 | public void onMessage(WebSocket webSocket, ByteString bytes) { 58 | Log.w(LOG_TAG, String.format(Locale.US, 59 | "Socket got into inconsistent state and received %s instead.", 60 | bytes.toString())); 61 | } 62 | 63 | @Override 64 | public void onClosed(WebSocket webSocket, int code, String reason) { 65 | setState(State.DISCONNECTED); 66 | webSocketClientCallback.onClose(); 67 | } 68 | 69 | @Override 70 | public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) { 71 | webSocketClientCallback.onError(t); 72 | } 73 | }; 74 | 75 | private OkHttp3WebSocketClient(OkHttpClient okHttpClient, 76 | WebSocketClientCallback webSocketClientCallback, URI hostUrl) { 77 | client = okHttpClient; 78 | this.webSocketClientCallback = webSocketClientCallback; 79 | url = hostUrl.toString(); 80 | } 81 | 82 | @Override 83 | public synchronized void open() { 84 | if (State.NONE == state) { 85 | // OkHttp3 connects as soon as the socket is created so do it here. 86 | Request request = new Request.Builder() 87 | .url(url) 88 | .build(); 89 | 90 | webSocket = client.newWebSocket(request, handler); 91 | setState(State.CONNECTING); 92 | } 93 | } 94 | 95 | @Override 96 | public synchronized void close() { 97 | if (State.NONE != state) { 98 | setState(State.DISCONNECTING); 99 | webSocket.close(STATUS_CODE, CLOSING_MSG); 100 | } 101 | } 102 | 103 | @Override 104 | public synchronized void send(String message) { 105 | if (state == State.CONNECTED) { 106 | webSocket.send(message); 107 | } 108 | } 109 | 110 | @Override 111 | public State getState() { 112 | return state; 113 | } 114 | 115 | private void setState(State newState) { 116 | synchronized (this) { 117 | this.state = newState; 118 | } 119 | this.webSocketClientCallback.stateChanged(); 120 | } 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/ParseLiveQueryClient.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import com.parse.ParseObject; 4 | import com.parse.ParseQuery; 5 | 6 | import java.net.URI; 7 | import java.util.concurrent.Executor; 8 | 9 | public interface ParseLiveQueryClient { 10 | SubscriptionHandling subscribe(ParseQuery query); 11 | 12 | void unsubscribe(final ParseQuery query); 13 | 14 | void unsubscribe(final ParseQuery query, final SubscriptionHandling subscriptionHandling); 15 | 16 | void connectIfNeeded(); 17 | 18 | void reconnect(); 19 | 20 | void disconnect(); 21 | 22 | void registerListener(ParseLiveQueryClientCallbacks listener); 23 | 24 | void unregisterListener(ParseLiveQueryClientCallbacks listener); 25 | 26 | class Factory { 27 | 28 | public static ParseLiveQueryClient getClient() { 29 | return new ParseLiveQueryClientImpl(); 30 | } 31 | 32 | public static ParseLiveQueryClient getClient(WebSocketClientFactory webSocketClientFactory) { 33 | return new ParseLiveQueryClientImpl(webSocketClientFactory); 34 | } 35 | 36 | public static ParseLiveQueryClient getClient(URI uri) { 37 | return new ParseLiveQueryClientImpl(uri); 38 | } 39 | 40 | public static ParseLiveQueryClient getClient(URI uri, WebSocketClientFactory webSocketClientFactory) { 41 | return new ParseLiveQueryClientImpl(uri, webSocketClientFactory); 42 | } 43 | 44 | public static ParseLiveQueryClient getClient(URI uri, WebSocketClientFactory webSocketClientFactory, Executor taskExecutor) { 45 | return new ParseLiveQueryClientImpl(uri, webSocketClientFactory, taskExecutor); 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/ParseLiveQueryClientCallbacks.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | public interface ParseLiveQueryClientCallbacks { 4 | void onLiveQueryClientConnected(ParseLiveQueryClient client); 5 | 6 | void onLiveQueryClientDisconnected(ParseLiveQueryClient client, boolean userInitiated); 7 | 8 | void onLiveQueryError(ParseLiveQueryClient client, LiveQueryException reason); 9 | 10 | void onSocketError(ParseLiveQueryClient client, Throwable reason); 11 | } 12 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/ParseLiveQueryClientImpl.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import android.util.Log; 4 | 5 | import com.parse.PLog; 6 | import com.parse.Parse; 7 | import com.parse.ParseDecoder; 8 | import com.parse.ParseObject; 9 | import com.parse.ParsePlugins; 10 | import com.parse.ParseQuery; 11 | import com.parse.ParseUser; 12 | 13 | import org.json.JSONException; 14 | import org.json.JSONObject; 15 | 16 | import java.net.URI; 17 | import java.net.URISyntaxException; 18 | import java.util.ArrayList; 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import java.util.concurrent.Callable; 22 | import java.util.concurrent.ConcurrentHashMap; 23 | import java.util.concurrent.Executor; 24 | 25 | import com.parse.boltsinternal.Continuation; 26 | import com.parse.boltsinternal.Task; 27 | import okhttp3.OkHttpClient; 28 | 29 | class ParseLiveQueryClientImpl implements ParseLiveQueryClient { 30 | 31 | private static final String LOG_TAG = "ParseLiveQueryClient"; 32 | 33 | private final Executor taskExecutor; 34 | private final String applicationId; 35 | private final String clientKey; 36 | private final ConcurrentHashMap> subscriptions = new ConcurrentHashMap<>(); 37 | private final URI uri; 38 | private final WebSocketClientFactory webSocketClientFactory; 39 | private final WebSocketClient.WebSocketClientCallback webSocketClientCallback; 40 | 41 | private final List mCallbacks = new ArrayList<>(); 42 | 43 | private WebSocketClient webSocketClient; 44 | private int requestIdCount = 1; 45 | private boolean userInitiatedDisconnect = false; 46 | private boolean hasReceivedConnected = false; 47 | 48 | /* package */ ParseLiveQueryClientImpl() { 49 | this(getDefaultUri()); 50 | } 51 | 52 | /* package */ ParseLiveQueryClientImpl(URI uri) { 53 | this(uri, new OkHttp3SocketClientFactory(new OkHttpClient()), Task.BACKGROUND_EXECUTOR); 54 | } 55 | 56 | /* package */ ParseLiveQueryClientImpl(URI uri, WebSocketClientFactory webSocketClientFactory) { 57 | this(uri, webSocketClientFactory, Task.BACKGROUND_EXECUTOR); 58 | } 59 | 60 | /* package */ ParseLiveQueryClientImpl(WebSocketClientFactory webSocketClientFactory) { 61 | this(getDefaultUri(), webSocketClientFactory, Task.BACKGROUND_EXECUTOR); 62 | } 63 | 64 | /* package */ ParseLiveQueryClientImpl(URI uri, WebSocketClientFactory webSocketClientFactory, Executor taskExecutor) { 65 | Parse.checkInit(); 66 | this.uri = uri; 67 | this.applicationId = ParsePlugins.get().applicationId(); 68 | this.clientKey = ParsePlugins.get().clientKey(); 69 | this.webSocketClientFactory = webSocketClientFactory; 70 | this.taskExecutor = taskExecutor; 71 | this.webSocketClientCallback = getWebSocketClientCallback(); 72 | } 73 | 74 | private static URI getDefaultUri() { 75 | String url = ParsePlugins.get().server(); 76 | if (url.contains("https")) { 77 | url = url.replaceFirst("https", "wss"); 78 | } else { 79 | url = url.replaceFirst("http", "ws"); 80 | } 81 | try { 82 | return new URI(url); 83 | } catch (URISyntaxException e) { 84 | e.printStackTrace(); 85 | throw new RuntimeException(e.getMessage()); 86 | } 87 | } 88 | 89 | @Override 90 | public SubscriptionHandling subscribe(ParseQuery query) { 91 | int requestId = requestIdGenerator(); 92 | Subscription subscription = new Subscription<>(requestId, query); 93 | subscriptions.put(requestId, subscription); 94 | 95 | if (isConnected()) { 96 | sendSubscription(subscription); 97 | } else if (userInitiatedDisconnect) { 98 | Log.w(LOG_TAG, "Warning: The client was explicitly disconnected! You must explicitly call .reconnect() in order to process your subscriptions."); 99 | } else { 100 | connectIfNeeded(); 101 | } 102 | 103 | return subscription; 104 | } 105 | 106 | public void connectIfNeeded() { 107 | switch (getWebSocketState()) { 108 | case CONNECTED: 109 | // nothing to do 110 | break; 111 | case CONNECTING: 112 | // just wait for it to finish connecting 113 | break; 114 | 115 | case NONE: 116 | case DISCONNECTING: 117 | case DISCONNECTED: 118 | reconnect(); 119 | break; 120 | 121 | default: 122 | 123 | break; 124 | } 125 | } 126 | 127 | @Override 128 | public void unsubscribe(final ParseQuery query) { 129 | if (query != null) { 130 | for (Subscription subscription : subscriptions.values()) { 131 | if (query.equals(subscription.getQuery())) { 132 | sendUnsubscription(subscription); 133 | } 134 | } 135 | } 136 | } 137 | 138 | @Override 139 | public void unsubscribe(final ParseQuery query, final SubscriptionHandling subscriptionHandling) { 140 | if (query != null && subscriptionHandling != null) { 141 | for (Subscription subscription : subscriptions.values()) { 142 | if (query.equals(subscription.getQuery()) && subscriptionHandling.equals(subscription)) { 143 | sendUnsubscription(subscription); 144 | } 145 | } 146 | } 147 | } 148 | 149 | @Override 150 | public synchronized void reconnect() { 151 | if (webSocketClient != null) { 152 | webSocketClient.close(); 153 | } 154 | 155 | userInitiatedDisconnect = false; 156 | hasReceivedConnected = false; 157 | webSocketClient = webSocketClientFactory.createInstance(webSocketClientCallback, uri); 158 | webSocketClient.open(); 159 | } 160 | 161 | @Override 162 | public synchronized void disconnect() { 163 | if (webSocketClient != null) { 164 | webSocketClient.close(); 165 | webSocketClient = null; 166 | } 167 | 168 | userInitiatedDisconnect = true; 169 | hasReceivedConnected = false; 170 | } 171 | 172 | @Override 173 | public void registerListener(ParseLiveQueryClientCallbacks listener) { 174 | mCallbacks.add(listener); 175 | } 176 | 177 | @Override 178 | public void unregisterListener(ParseLiveQueryClientCallbacks listener) { 179 | mCallbacks.remove(listener); 180 | } 181 | 182 | // Private methods 183 | 184 | private synchronized int requestIdGenerator() { 185 | return requestIdCount++; 186 | } 187 | 188 | private WebSocketClient.State getWebSocketState() { 189 | WebSocketClient.State state = webSocketClient == null ? null : webSocketClient.getState(); 190 | return state == null ? WebSocketClient.State.NONE : state; 191 | } 192 | 193 | private boolean isConnected() { 194 | return hasReceivedConnected && inAnyState(WebSocketClient.State.CONNECTED); 195 | } 196 | 197 | private boolean inAnyState(WebSocketClient.State... states) { 198 | return Arrays.asList(states).contains(getWebSocketState()); 199 | } 200 | 201 | private Task handleOperationAsync(final String message) { 202 | return Task.call(new Callable() { 203 | public Void call() throws Exception { 204 | parseMessage(message); 205 | return null; 206 | } 207 | }, taskExecutor); 208 | } 209 | 210 | private Task sendOperationAsync(final ClientOperation clientOperation) { 211 | return Task.call(new Callable() { 212 | public Void call() throws Exception { 213 | JSONObject jsonEncoded = clientOperation.getJSONObjectRepresentation(); 214 | String jsonString = jsonEncoded.toString(); 215 | if (Parse.getLogLevel() <= Parse.LOG_LEVEL_DEBUG) { 216 | Log.d(LOG_TAG, "Sending over websocket: " + jsonString); 217 | } 218 | webSocketClient.send(jsonString); 219 | return null; 220 | } 221 | }, taskExecutor); 222 | } 223 | 224 | private void parseMessage(String message) throws LiveQueryException { 225 | try { 226 | JSONObject jsonObject = new JSONObject(message); 227 | String rawOperation = jsonObject.getString("op"); 228 | 229 | switch (rawOperation) { 230 | case "connected": 231 | hasReceivedConnected = true; 232 | dispatchConnected(); 233 | Log.v(LOG_TAG, "Connected, sending pending subscription"); 234 | for (Subscription subscription : subscriptions.values()) { 235 | sendSubscription(subscription); 236 | } 237 | break; 238 | case "redirect": 239 | String url = jsonObject.getString("url"); 240 | // TODO: Handle redirect. 241 | Log.d(LOG_TAG, "Redirect is not yet handled"); 242 | break; 243 | case "subscribed": 244 | handleSubscribedEvent(jsonObject); 245 | break; 246 | case "unsubscribed": 247 | handleUnsubscribedEvent(jsonObject); 248 | break; 249 | case "enter": 250 | handleObjectEvent(Subscription.Event.ENTER, jsonObject); 251 | break; 252 | case "leave": 253 | handleObjectEvent(Subscription.Event.LEAVE, jsonObject); 254 | break; 255 | case "update": 256 | handleObjectEvent(Subscription.Event.UPDATE, jsonObject); 257 | break; 258 | case "create": 259 | handleObjectEvent(Subscription.Event.CREATE, jsonObject); 260 | break; 261 | case "delete": 262 | handleObjectEvent(Subscription.Event.DELETE, jsonObject); 263 | break; 264 | case "error": 265 | handleErrorEvent(jsonObject); 266 | break; 267 | default: 268 | throw new LiveQueryException.InvalidResponseException(message); 269 | } 270 | } catch (JSONException e) { 271 | throw new LiveQueryException.InvalidResponseException(message); 272 | } 273 | } 274 | 275 | private void dispatchConnected() { 276 | for (ParseLiveQueryClientCallbacks callback : mCallbacks) { 277 | callback.onLiveQueryClientConnected(this); 278 | } 279 | } 280 | 281 | private void dispatchDisconnected() { 282 | for (ParseLiveQueryClientCallbacks callback : mCallbacks) { 283 | callback.onLiveQueryClientDisconnected(this, userInitiatedDisconnect); 284 | } 285 | } 286 | 287 | 288 | private void dispatchServerError(LiveQueryException exc) { 289 | for (ParseLiveQueryClientCallbacks callback : mCallbacks) { 290 | callback.onLiveQueryError(this, exc); 291 | } 292 | } 293 | 294 | private void dispatchSocketError(Throwable reason) { 295 | userInitiatedDisconnect = false; 296 | 297 | for (ParseLiveQueryClientCallbacks callback : mCallbacks) { 298 | callback.onSocketError(this, reason); 299 | } 300 | 301 | dispatchDisconnected(); 302 | } 303 | 304 | private void handleSubscribedEvent(JSONObject jsonObject) throws JSONException { 305 | final int requestId = jsonObject.getInt("requestId"); 306 | final Subscription subscription = subscriptionForRequestId(requestId); 307 | if (subscription != null) { 308 | subscription.didSubscribe(subscription.getQuery()); 309 | } 310 | } 311 | 312 | private void handleUnsubscribedEvent(JSONObject jsonObject) throws JSONException { 313 | final int requestId = jsonObject.getInt("requestId"); 314 | final Subscription subscription = subscriptionForRequestId(requestId); 315 | if (subscription != null) { 316 | subscription.didUnsubscribe(subscription.getQuery()); 317 | subscriptions.remove(requestId); 318 | } 319 | } 320 | 321 | private void handleObjectEvent(Subscription.Event event, JSONObject jsonObject) throws JSONException { 322 | final int requestId = jsonObject.getInt("requestId"); 323 | final Subscription subscription = subscriptionForRequestId(requestId); 324 | if (subscription != null) { 325 | T object = ParseObject.fromJSON(jsonObject.getJSONObject("object"), subscription.getQueryState().className(), ParseDecoder.get(), subscription.getQueryState().selectedKeys()); 326 | subscription.didReceive(event, subscription.getQuery(), object); 327 | } 328 | } 329 | 330 | private void handleErrorEvent(JSONObject jsonObject) throws JSONException { 331 | int requestId = jsonObject.getInt("requestId"); 332 | int code = jsonObject.getInt("code"); 333 | String error = jsonObject.getString("error"); 334 | Boolean reconnect = jsonObject.getBoolean("reconnect"); 335 | final Subscription subscription = subscriptionForRequestId(requestId); 336 | LiveQueryException exc = new LiveQueryException.ServerReportedException(code, error, reconnect); 337 | 338 | if (subscription != null) { 339 | subscription.didEncounter(exc, subscription.getQuery()); 340 | } 341 | 342 | dispatchServerError(exc); 343 | } 344 | 345 | private Subscription subscriptionForRequestId(int requestId) { 346 | //noinspection unchecked 347 | return (Subscription) subscriptions.get(requestId); 348 | } 349 | 350 | private void sendSubscription(final Subscription subscription) { 351 | ParseUser.getCurrentSessionTokenAsync().onSuccess(new Continuation() { 352 | @Override 353 | public Void then(Task task) throws Exception { 354 | String sessionToken = task.getResult(); 355 | SubscribeClientOperation op = new SubscribeClientOperation<>(subscription.getRequestId(), subscription.getQueryState(), sessionToken); 356 | 357 | // dispatch errors 358 | sendOperationAsync(op).continueWith(new Continuation() { 359 | public Void then(Task task) { 360 | Exception error = task.getError(); 361 | if (error != null) { 362 | if (error instanceof RuntimeException) { 363 | subscription.didEncounter(new LiveQueryException.UnknownException( 364 | "Error when subscribing", (RuntimeException) error), subscription.getQuery()); 365 | } 366 | } 367 | return null; 368 | } 369 | }); 370 | return null; 371 | } 372 | }); 373 | } 374 | 375 | private void sendUnsubscription(Subscription subscription) { 376 | sendOperationAsync(new UnsubscribeClientOperation(subscription.getRequestId())); 377 | } 378 | 379 | private WebSocketClient.WebSocketClientCallback getWebSocketClientCallback() { 380 | return new WebSocketClient.WebSocketClientCallback() { 381 | @Override 382 | public void onOpen() { 383 | hasReceivedConnected = false; 384 | Log.v(LOG_TAG, "Socket opened"); 385 | ParseUser.getCurrentSessionTokenAsync().onSuccessTask(new Continuation>() { 386 | @Override 387 | public Task then(Task task) throws Exception { 388 | String sessionToken = task.getResult(); 389 | return sendOperationAsync(new ConnectClientOperation(applicationId, sessionToken)); 390 | } 391 | }).continueWith(new Continuation() { 392 | public Void then(Task task) { 393 | Exception error = task.getError(); 394 | if (error != null) { 395 | Log.e(LOG_TAG, "Error when connection client", error); 396 | } 397 | return null; 398 | } 399 | }); 400 | } 401 | 402 | @Override 403 | public void onMessage(String message) { 404 | Log.v(LOG_TAG, "Socket onMessage " + message); 405 | handleOperationAsync(message).continueWith(new Continuation() { 406 | public Void then(Task task) { 407 | Exception error = task.getError(); 408 | if (error != null) { 409 | Log.e(LOG_TAG, "Error handling message", error); 410 | } 411 | return null; 412 | } 413 | }); 414 | } 415 | 416 | @Override 417 | public void onClose() { 418 | Log.v(LOG_TAG, "Socket onClose"); 419 | hasReceivedConnected = false; 420 | dispatchDisconnected(); 421 | } 422 | 423 | @Override 424 | public void onError(Throwable exception) { 425 | PLog.e(LOG_TAG, "Socket onError", exception); 426 | hasReceivedConnected = false; 427 | dispatchSocketError(exception); 428 | } 429 | 430 | @Override 431 | public void stateChanged() { 432 | PLog.v(LOG_TAG, "Socket stateChanged"); 433 | } 434 | }; 435 | } 436 | } 437 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/SubscribeClientOperation.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import com.parse.ParseObject; 4 | import com.parse.ParseQuery; 5 | import com.parse.PointerEncoder; 6 | import com.parse.livequery.ClientOperation; 7 | 8 | import org.json.JSONException; 9 | import org.json.JSONObject; 10 | 11 | class SubscribeClientOperation extends ClientOperation { 12 | 13 | private final int requestId; 14 | private final ParseQuery.State state; 15 | private final String sessionToken; 16 | 17 | /* package */ SubscribeClientOperation(int requestId, ParseQuery.State state, String sessionToken) { 18 | this.requestId = requestId; 19 | this.state = state; 20 | this.sessionToken = sessionToken; 21 | } 22 | 23 | @Override 24 | /* package */ JSONObject getJSONObjectRepresentation() throws JSONException { 25 | JSONObject jsonObject = new JSONObject(); 26 | jsonObject.put("op", "subscribe"); 27 | jsonObject.put("requestId", requestId); 28 | jsonObject.put("sessionToken", sessionToken); 29 | 30 | JSONObject queryJsonObject = new JSONObject(); 31 | queryJsonObject.put("className", state.className()); 32 | 33 | // TODO: add support for fields 34 | // https://github.com/ParsePlatform/parse-server/issues/3671 35 | 36 | PointerEncoder pointerEncoder = PointerEncoder.get(); 37 | queryJsonObject.put("where", pointerEncoder.encode(state.constraints())); 38 | 39 | jsonObject.put("query", queryJsonObject); 40 | 41 | return jsonObject; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/Subscription.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import com.parse.ParseObject; 4 | import com.parse.ParseQuery; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | class Subscription implements SubscriptionHandling { 10 | 11 | private final List> handleEventsCallbacks = new ArrayList<>(); 12 | private final List> handleErrorCallbacks = new ArrayList<>(); 13 | private final List> handleSubscribeCallbacks = new ArrayList<>(); 14 | private final List> handleUnsubscribeCallbacks = new ArrayList<>(); 15 | 16 | private final int requestId; 17 | private final ParseQuery query; 18 | private final ParseQuery.State state; 19 | 20 | /* package */ Subscription(int requestId, ParseQuery query) { 21 | this.requestId = requestId; 22 | this.query = query; 23 | this.state = query.getBuilder().build(); 24 | } 25 | 26 | @Override 27 | public Subscription handleEvents(HandleEventsCallback callback) { 28 | handleEventsCallbacks.add(callback); 29 | return this; 30 | } 31 | 32 | @Override 33 | public Subscription handleEvent(final Event event, final HandleEventCallback callback) { 34 | return handleEvents(new HandleEventsCallback() { 35 | @Override 36 | public void onEvents(ParseQuery query, Event callbackEvent, T object) { 37 | if (callbackEvent == event) { 38 | callback.onEvent(query, object); 39 | } 40 | } 41 | }); 42 | } 43 | 44 | @Override 45 | public Subscription handleError(HandleErrorCallback callback) { 46 | handleErrorCallbacks.add(callback); 47 | return this; 48 | } 49 | 50 | @Override 51 | public Subscription handleSubscribe(HandleSubscribeCallback callback) { 52 | handleSubscribeCallbacks.add(callback); 53 | return this; 54 | } 55 | 56 | @Override 57 | public Subscription handleUnsubscribe(HandleUnsubscribeCallback callback) { 58 | handleUnsubscribeCallbacks.add(callback); 59 | return this; 60 | } 61 | 62 | @Override 63 | public int getRequestId() { 64 | return requestId; 65 | } 66 | 67 | /* package */ ParseQuery getQuery() { 68 | return query; 69 | } 70 | 71 | /* package */ ParseQuery.State getQueryState() { 72 | return state; 73 | } 74 | 75 | /** 76 | * Tells the handler that an event has been received from the live query server. 77 | * 78 | * @param event The event that has been received from the server. 79 | * @param query The query that the event occurred on. 80 | */ 81 | /* package */ void didReceive(Event event, ParseQuery query, T object) { 82 | for (HandleEventsCallback handleEventsCallback : handleEventsCallbacks) { 83 | handleEventsCallback.onEvents(query, event, object); 84 | } 85 | } 86 | 87 | /** 88 | * Tells the handler that an error has been received from the live query server. 89 | * 90 | * @param error The error that the server has encountered. 91 | * @param query The query that the error occurred on. 92 | */ 93 | /* package */ void didEncounter(LiveQueryException error, ParseQuery query) { 94 | for (HandleErrorCallback handleErrorCallback : handleErrorCallbacks) { 95 | handleErrorCallback.onError(query, error); 96 | } 97 | } 98 | 99 | /** 100 | * Tells the handler that a query has been successfully registered with the server. 101 | * - note: This may be invoked multiple times if the client disconnects/reconnects. 102 | * 103 | * @param query The query that has been subscribed. 104 | */ 105 | /* package */ void didSubscribe(ParseQuery query) { 106 | for (HandleSubscribeCallback handleSubscribeCallback : handleSubscribeCallbacks) { 107 | handleSubscribeCallback.onSubscribe(query); 108 | } 109 | } 110 | 111 | /** 112 | * Tells the handler that a query has been successfully deregistered from the server. 113 | * - note: This is not called unless `unregister()` is explicitly called. 114 | * 115 | * @param query The query that has been unsubscribed. 116 | */ 117 | /* package */ void didUnsubscribe(ParseQuery query) { 118 | for (HandleUnsubscribeCallback handleUnsubscribeCallback : handleUnsubscribeCallbacks) { 119 | handleUnsubscribeCallback.onUnsubscribe(query); 120 | } 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/SubscriptionHandling.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import com.parse.ParseObject; 4 | import com.parse.ParseQuery; 5 | 6 | public interface SubscriptionHandling { 7 | 8 | /** 9 | * Register a callback for when an event occurs. 10 | * 11 | * @param callback The callback to register. 12 | * @return The same SubscriptionHandling, for easy chaining. 13 | */ 14 | SubscriptionHandling handleEvents(Subscription.HandleEventsCallback callback); 15 | 16 | /** 17 | * Register a callback for when an event occurs. 18 | * 19 | * @param event The event type to handle. You should pass one of the enum cases in Event 20 | * @param callback The callback to register. 21 | * @return The same SubscriptionHandling, for easy chaining. 22 | */ 23 | SubscriptionHandling handleEvent(Subscription.Event event, Subscription.HandleEventCallback callback); 24 | 25 | /** 26 | * Register a callback for when an event occurs. 27 | * 28 | * @param callback The callback to register. 29 | * @return The same SubscriptionHandling, for easy chaining. 30 | */ 31 | SubscriptionHandling handleError(Subscription.HandleErrorCallback callback); 32 | 33 | /** 34 | * Register a callback for when a client succesfully subscribes to a query. 35 | * 36 | * @param callback The callback to register. 37 | * @return The same SubscriptionHandling, for easy chaining. 38 | */ 39 | SubscriptionHandling handleSubscribe(Subscription.HandleSubscribeCallback callback); 40 | 41 | /** 42 | * Register a callback for when a query has been unsubscribed. 43 | * 44 | * @param callback The callback to register. 45 | * @return The same SubscriptionHandling, for easy chaining. 46 | */ 47 | SubscriptionHandling handleUnsubscribe(Subscription.HandleUnsubscribeCallback callback); 48 | 49 | int getRequestId(); 50 | 51 | interface HandleEventsCallback { 52 | void onEvents(ParseQuery query, Subscription.Event event, T object); 53 | } 54 | 55 | interface HandleEventCallback { 56 | void onEvent(ParseQuery query, T object); 57 | } 58 | 59 | interface HandleErrorCallback { 60 | void onError(ParseQuery query, LiveQueryException exception); 61 | } 62 | 63 | interface HandleSubscribeCallback { 64 | void onSubscribe(ParseQuery query); 65 | } 66 | 67 | interface HandleUnsubscribeCallback { 68 | void onUnsubscribe(ParseQuery query); 69 | } 70 | 71 | enum Event { 72 | CREATE, ENTER, UPDATE, LEAVE, DELETE 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/UnsubscribeClientOperation.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | 6 | class UnsubscribeClientOperation extends ClientOperation { 7 | 8 | private final int requestId; 9 | 10 | UnsubscribeClientOperation(int requestId) { 11 | this.requestId = requestId; 12 | } 13 | 14 | @Override 15 | JSONObject getJSONObjectRepresentation() throws JSONException { 16 | JSONObject jsonObject = new JSONObject(); 17 | jsonObject.put("op", "unsubscribe"); 18 | jsonObject.put("requestId", requestId); 19 | return jsonObject; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/WebSocketClient.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | public interface WebSocketClient { 4 | 5 | void open(); 6 | 7 | void close(); 8 | 9 | void send(String message); 10 | 11 | State getState(); 12 | 13 | interface WebSocketClientCallback { 14 | void onOpen(); 15 | 16 | void onMessage(String message); 17 | 18 | void onClose(); 19 | 20 | void onError(Throwable exception); 21 | 22 | void stateChanged(); 23 | } 24 | 25 | enum State {NONE, CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED} 26 | 27 | } 28 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/main/java/com/parse/livequery/WebSocketClientFactory.java: -------------------------------------------------------------------------------- 1 | package com.parse.livequery; 2 | 3 | import java.net.URI; 4 | 5 | public interface WebSocketClientFactory { 6 | 7 | WebSocketClient createInstance(WebSocketClient.WebSocketClientCallback webSocketClientCallback, URI hostUrl); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/test/java/com/parse/ImmediateExecutor.java: -------------------------------------------------------------------------------- 1 | package com.parse; 2 | 3 | import java.util.concurrent.Executor; 4 | 5 | class ImmediateExecutor implements Executor { 6 | @Override 7 | public void execute(Runnable runnable) { 8 | runnable.run(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/test/java/com/parse/TestOkHttpClientFactory.java: -------------------------------------------------------------------------------- 1 | package com.parse; 2 | 3 | import com.parse.livequery.OkHttp3SocketClientFactory; 4 | import com.parse.livequery.WebSocketClient; 5 | 6 | import junit.framework.Assert; 7 | 8 | import org.junit.After; 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | import org.mockito.Mock; 13 | import org.mockito.runners.MockitoJUnitRunner; 14 | 15 | import java.net.URI; 16 | 17 | import okhttp3.OkHttpClient; 18 | 19 | import static com.parse.livequery.WebSocketClient.State.NONE; 20 | 21 | @RunWith(MockitoJUnitRunner.class) 22 | public class TestOkHttpClientFactory { 23 | 24 | @Mock 25 | private OkHttpClient okHttpClientMock; 26 | 27 | @Mock 28 | private WebSocketClient.WebSocketClientCallback webSocketClientCallbackMock; 29 | 30 | private OkHttp3SocketClientFactory okHttp3SocketClientFactory; 31 | private WebSocketClient webSocketClient; 32 | 33 | @Before 34 | public void setUp() throws Exception { 35 | okHttp3SocketClientFactory = new OkHttp3SocketClientFactory(okHttpClientMock); 36 | webSocketClient = okHttp3SocketClientFactory.createInstance(webSocketClientCallbackMock, new URI("http://www.test.com")); 37 | } 38 | 39 | @After 40 | public void tearDown() { 41 | webSocketClient.close(); 42 | } 43 | 44 | @Test 45 | public void testClientCloseWithoutOpenShouldBeNoOp() { 46 | Assert.assertEquals(NONE, webSocketClient.getState()); 47 | webSocketClient.close(); 48 | webSocketClient.send("test"); 49 | Assert.assertEquals(NONE, webSocketClient.getState()); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /ParseLiveQuery/src/test/java/com/parse/TestParseLiveQueryClient.java: -------------------------------------------------------------------------------- 1 | package com.parse; 2 | 3 | import com.parse.livequery.BuildConfig; 4 | import com.parse.livequery.LiveQueryException; 5 | import com.parse.livequery.ParseLiveQueryClient; 6 | import com.parse.livequery.ParseLiveQueryClientCallbacks; 7 | import com.parse.livequery.SubscriptionHandling; 8 | import com.parse.livequery.WebSocketClient; 9 | import com.parse.livequery.WebSocketClientFactory; 10 | 11 | import org.json.JSONException; 12 | import org.json.JSONObject; 13 | import org.junit.After; 14 | import org.junit.Before; 15 | import org.junit.Test; 16 | import org.junit.runner.RunWith; 17 | import org.mockito.ArgumentCaptor; 18 | import org.mockito.invocation.InvocationOnMock; 19 | import org.mockito.stubbing.Answer; 20 | import org.robolectric.RobolectricTestRunner; 21 | import org.robolectric.annotation.Config; 22 | import org.robolectric.util.Transcript; 23 | 24 | import java.io.IOException; 25 | import java.net.URI; 26 | 27 | import com.parse.boltsinternal.Task; 28 | 29 | import static junit.framework.Assert.assertEquals; 30 | import static junit.framework.Assert.assertNotNull; 31 | import static junit.framework.Assert.assertTrue; 32 | import static org.mockito.AdditionalMatchers.and; 33 | import static org.mockito.AdditionalMatchers.not; 34 | import static org.mockito.Matchers.any; 35 | import static org.mockito.Matchers.anyBoolean; 36 | import static org.mockito.Matchers.anyString; 37 | import static org.mockito.Matchers.contains; 38 | import static org.mockito.Matchers.eq; 39 | import static org.mockito.Mockito.mock; 40 | import static org.mockito.Mockito.never; 41 | import static org.mockito.Mockito.times; 42 | import static org.mockito.Mockito.verify; 43 | import static org.mockito.Mockito.when; 44 | 45 | @RunWith(RobolectricTestRunner.class) 46 | @Config(constants = BuildConfig.class, sdk = 21) 47 | public class TestParseLiveQueryClient { 48 | 49 | private WebSocketClient webSocketClient; 50 | private WebSocketClient.WebSocketClientCallback webSocketClientCallback; 51 | private ParseLiveQueryClient parseLiveQueryClient; 52 | 53 | private ParseUser mockUser; 54 | 55 | @Before 56 | public void setUp() throws Exception { 57 | Parse.Configuration configuration = new Parse.Configuration.Builder(null) 58 | .applicationId("1234") 59 | .build(); 60 | ParsePlugins.initialize(null, configuration); 61 | 62 | // Register a mock currentUserController to make getCurrentUser work 63 | mockUser = mock(ParseUser.class); 64 | ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class); 65 | when(currentUserController.getAsync(anyBoolean())).thenAnswer(new Answer>() { 66 | @Override 67 | public Task answer(InvocationOnMock invocation) throws Throwable { 68 | return Task.forResult(mockUser); 69 | } 70 | }); 71 | when(currentUserController.getCurrentSessionTokenAsync()).thenAnswer(new Answer>() { 72 | @Override 73 | public Task answer(InvocationOnMock invocation) throws Throwable { 74 | return Task.forResult(mockUser.getSessionToken()); 75 | } 76 | }); 77 | ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController); 78 | 79 | parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(new URI(""), new WebSocketClientFactory() { 80 | @Override 81 | public WebSocketClient createInstance(WebSocketClient.WebSocketClientCallback webSocketClientCallback, URI hostUrl) { 82 | TestParseLiveQueryClient.this.webSocketClientCallback = webSocketClientCallback; 83 | webSocketClient = mock(WebSocketClient.class); 84 | return webSocketClient; 85 | } 86 | }, new ImmediateExecutor()); 87 | reconnect(); 88 | } 89 | 90 | @After 91 | public void tearDown() throws Exception { 92 | ParseCorePlugins.getInstance().reset(); 93 | ParsePlugins.reset(); 94 | } 95 | 96 | @Test 97 | public void testSubscribeAfterSocketConnectBeforeConnectedOp() throws Exception { 98 | // Bug: https://github.com/parse-community/ParseLiveQuery-Android/issues/46 99 | ParseQuery queryA = ParseQuery.getQuery("objA"); 100 | ParseQuery queryB = ParseQuery.getQuery("objB"); 101 | clearConnection(); 102 | 103 | // This will trigger connectIfNeeded(), which calls reconnect() 104 | SubscriptionHandling subA = parseLiveQueryClient.subscribe(queryA); 105 | 106 | verify(webSocketClient, times(1)).open(); 107 | verify(webSocketClient, never()).send(anyString()); 108 | 109 | // Now the socket is open 110 | webSocketClientCallback.onOpen(); 111 | when(webSocketClient.getState()).thenReturn(WebSocketClient.State.CONNECTED); 112 | // and we send op=connect 113 | verify(webSocketClient, times(1)).send(contains("\"op\":\"connect\"")); 114 | 115 | // Now if we subscribe to queryB, we SHOULD NOT send the subscribe yet, until we get op=connected 116 | SubscriptionHandling subB = parseLiveQueryClient.subscribe(queryB); 117 | verify(webSocketClient, never()).send(contains("\"op\":\"subscribe\"")); 118 | 119 | // on op=connected, _then_ we should send both subscriptions 120 | webSocketClientCallback.onMessage(createConnectedMessage().toString()); 121 | verify(webSocketClient, times(2)).send(contains("\"op\":\"subscribe\"")); 122 | } 123 | 124 | @Test 125 | public void testSubscribeWhenSubscribedToCallback() throws Exception { 126 | SubscriptionHandling.HandleSubscribeCallback subscribeMockCallback = mock(SubscriptionHandling.HandleSubscribeCallback.class); 127 | 128 | ParseQuery parseQuery = new ParseQuery<>("test"); 129 | createSubscription(parseQuery, subscribeMockCallback); 130 | 131 | verify(subscribeMockCallback, times(1)).onSubscribe(parseQuery); 132 | } 133 | 134 | @Test 135 | public void testUnsubscribeWhenSubscribedToCallback() throws Exception { 136 | ParseQuery parseQuery = new ParseQuery<>("test"); 137 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 138 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 139 | 140 | parseLiveQueryClient.unsubscribe(parseQuery); 141 | verify(webSocketClient, times(1)).send(any(String.class)); 142 | 143 | SubscriptionHandling.HandleUnsubscribeCallback unsubscribeMockCallback = mock( 144 | SubscriptionHandling.HandleUnsubscribeCallback.class); 145 | subscriptionHandling.handleUnsubscribe(unsubscribeMockCallback); 146 | webSocketClientCallback.onMessage(createUnsubscribedMessage(subscriptionHandling.getRequestId()).toString()); 147 | 148 | verify(unsubscribeMockCallback, times(1)).onUnsubscribe(parseQuery); 149 | } 150 | 151 | @Test 152 | public void testErrorWhileSubscribing() throws Exception { 153 | ParseQuery.State state = mock(ParseQuery.State.class); 154 | when(state.constraints()).thenThrow(new RuntimeException("forced error")); 155 | 156 | ParseQuery.State.Builder builder = mock(ParseQuery.State.Builder.class); 157 | when(builder.build()).thenReturn(state); 158 | ParseQuery query = mock(ParseQuery.class); 159 | when(query.getBuilder()).thenReturn(builder); 160 | 161 | SubscriptionHandling handling = parseLiveQueryClient.subscribe(query); 162 | 163 | SubscriptionHandling.HandleErrorCallback errorMockCallback = mock(SubscriptionHandling.HandleErrorCallback.class); 164 | handling.handleError(errorMockCallback); 165 | 166 | // Trigger a re-subscribe 167 | webSocketClientCallback.onMessage(createConnectedMessage().toString()); 168 | 169 | // This will never get a chance to call op=subscribe, because an exception was thrown 170 | verify(webSocketClient, never()).send(anyString()); 171 | 172 | ArgumentCaptor errorCaptor = ArgumentCaptor.forClass(LiveQueryException.class); 173 | verify(errorMockCallback, times(1)).onError(eq(query), errorCaptor.capture()); 174 | 175 | assertEquals("Error when subscribing", errorCaptor.getValue().getMessage()); 176 | assertNotNull(errorCaptor.getValue().getCause()); 177 | } 178 | 179 | @Test 180 | public void testErrorWhenSubscribedToCallback() throws Exception { 181 | ParseQuery parseQuery = new ParseQuery<>("test"); 182 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 183 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 184 | 185 | SubscriptionHandling.HandleErrorCallback errorMockCallback = mock(SubscriptionHandling.HandleErrorCallback.class); 186 | subscriptionHandling.handleError(errorMockCallback); 187 | webSocketClientCallback.onMessage(createErrorMessage(subscriptionHandling.getRequestId()).toString()); 188 | 189 | ArgumentCaptor errorCaptor = ArgumentCaptor.forClass(LiveQueryException.class); 190 | verify(errorMockCallback, times(1)).onError(eq(parseQuery), errorCaptor.capture()); 191 | 192 | LiveQueryException genericError = errorCaptor.getValue(); 193 | assertTrue(genericError instanceof LiveQueryException.ServerReportedException); 194 | 195 | LiveQueryException.ServerReportedException serverError = (LiveQueryException.ServerReportedException) genericError; 196 | assertEquals(serverError.getError(), "testError"); 197 | assertEquals(serverError.getCode(), 1); 198 | assertEquals(serverError.isReconnect(), true); 199 | } 200 | 201 | @Test 202 | public void testHeterogeneousSubscriptions() throws Exception { 203 | ParseObject.registerSubclass(MockClassA.class); 204 | ParseObject.registerSubclass(MockClassB.class); 205 | 206 | ParseQuery query1 = ParseQuery.getQuery(MockClassA.class); 207 | ParseQuery query2 = ParseQuery.getQuery(MockClassB.class); 208 | SubscriptionHandling handle1 = parseLiveQueryClient.subscribe(query1); 209 | SubscriptionHandling handle2 = parseLiveQueryClient.subscribe(query2); 210 | 211 | handle1.handleError(new SubscriptionHandling.HandleErrorCallback() { 212 | @Override 213 | public void onError(ParseQuery query, LiveQueryException exception) { 214 | throw new RuntimeException(exception); 215 | } 216 | }); 217 | handle2.handleError(new SubscriptionHandling.HandleErrorCallback() { 218 | @Override 219 | public void onError(ParseQuery query, LiveQueryException exception) { 220 | throw new RuntimeException(exception); 221 | } 222 | }); 223 | 224 | SubscriptionHandling.HandleEventCallback eventMockCallback1 = mock(SubscriptionHandling.HandleEventCallback.class); 225 | SubscriptionHandling.HandleEventCallback eventMockCallback2 = mock(SubscriptionHandling.HandleEventCallback.class); 226 | 227 | handle1.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback1); 228 | handle2.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback2); 229 | 230 | ParseObject parseObject1 = new MockClassA(); 231 | parseObject1.setObjectId("testId1"); 232 | 233 | ParseObject parseObject2 = new MockClassB(); 234 | parseObject2.setObjectId("testId2"); 235 | 236 | webSocketClientCallback.onMessage(createObjectCreateMessage(handle1.getRequestId(), parseObject1).toString()); 237 | webSocketClientCallback.onMessage(createObjectCreateMessage(handle2.getRequestId(), parseObject2).toString()); 238 | 239 | validateSameObject((SubscriptionHandling.HandleEventCallback) eventMockCallback1, (ParseQuery) query1, parseObject1); 240 | validateSameObject((SubscriptionHandling.HandleEventCallback) eventMockCallback2, (ParseQuery) query2, parseObject2); 241 | } 242 | 243 | @Test 244 | public void testCreateEventWhenSubscribedToCallback() throws Exception { 245 | ParseQuery parseQuery = new ParseQuery<>("test"); 246 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 247 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 248 | 249 | SubscriptionHandling.HandleEventCallback eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class); 250 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback); 251 | 252 | ParseObject parseObject = new ParseObject("Test"); 253 | parseObject.setObjectId("testId"); 254 | 255 | webSocketClientCallback.onMessage(createObjectCreateMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 256 | 257 | validateSameObject(eventMockCallback, parseQuery, parseObject); 258 | } 259 | 260 | @Test 261 | public void testEnterEventWhenSubscribedToCallback() throws Exception { 262 | ParseQuery parseQuery = new ParseQuery<>("test"); 263 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 264 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 265 | 266 | SubscriptionHandling.HandleEventCallback eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class); 267 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.ENTER, eventMockCallback); 268 | 269 | ParseObject parseObject = new ParseObject("Test"); 270 | parseObject.setObjectId("testId"); 271 | 272 | webSocketClientCallback.onMessage(createObjectEnterMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 273 | 274 | validateSameObject(eventMockCallback, parseQuery, parseObject); 275 | } 276 | 277 | @Test 278 | public void testUpdateEventWhenSubscribedToCallback() throws Exception { 279 | ParseQuery parseQuery = new ParseQuery<>("test"); 280 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 281 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 282 | 283 | SubscriptionHandling.HandleEventCallback eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class); 284 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.UPDATE, eventMockCallback); 285 | 286 | ParseObject parseObject = new ParseObject("Test"); 287 | parseObject.setObjectId("testId"); 288 | 289 | webSocketClientCallback.onMessage(createObjectUpdateMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 290 | 291 | validateSameObject(eventMockCallback, parseQuery, parseObject); 292 | } 293 | 294 | @Test 295 | public void testLeaveEventWhenSubscribedToCallback() throws Exception { 296 | ParseQuery parseQuery = new ParseQuery<>("test"); 297 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 298 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 299 | 300 | SubscriptionHandling.HandleEventCallback eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class); 301 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.LEAVE, eventMockCallback); 302 | 303 | ParseObject parseObject = new ParseObject("Test"); 304 | parseObject.setObjectId("testId"); 305 | 306 | webSocketClientCallback.onMessage(createObjectLeaveMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 307 | 308 | validateSameObject(eventMockCallback, parseQuery, parseObject); 309 | } 310 | 311 | @Test 312 | public void testDeleteEventWhenSubscribedToCallback() throws Exception { 313 | ParseQuery parseQuery = new ParseQuery<>("test"); 314 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 315 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 316 | 317 | SubscriptionHandling.HandleEventCallback eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class); 318 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.DELETE, eventMockCallback); 319 | 320 | ParseObject parseObject = new ParseObject("Test"); 321 | parseObject.setObjectId("testId"); 322 | 323 | webSocketClientCallback.onMessage(createObjectDeleteMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 324 | 325 | validateSameObject(eventMockCallback, parseQuery, parseObject); 326 | } 327 | 328 | @Test 329 | public void testCreateEventWhenSubscribedToAnyCallback() throws Exception { 330 | ParseQuery parseQuery = new ParseQuery<>("test"); 331 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 332 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 333 | 334 | SubscriptionHandling.HandleEventsCallback eventsMockCallback = mock(SubscriptionHandling.HandleEventsCallback.class); 335 | subscriptionHandling.handleEvents(eventsMockCallback); 336 | 337 | ParseObject parseObject = new ParseObject("Test"); 338 | parseObject.setObjectId("testId"); 339 | 340 | webSocketClientCallback.onMessage(createObjectCreateMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 341 | 342 | ArgumentCaptor objectCaptor = ArgumentCaptor.forClass(ParseObject.class); 343 | verify(eventsMockCallback, times(1)).onEvents(eq(parseQuery), eq(SubscriptionHandling.Event.CREATE), objectCaptor.capture()); 344 | 345 | ParseObject newParseObject = objectCaptor.getValue(); 346 | 347 | assertEquals(parseObject.getObjectId(), newParseObject.getObjectId()); 348 | } 349 | 350 | @Test 351 | public void testSubscriptionStoppedAfterUnsubscribe() throws Exception { 352 | ParseQuery parseQuery = new ParseQuery<>("test"); 353 | SubscriptionHandling subscriptionHandling = createSubscription(parseQuery, 354 | mock(SubscriptionHandling.HandleSubscribeCallback.class)); 355 | 356 | SubscriptionHandling.HandleEventCallback eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class); 357 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback); 358 | 359 | SubscriptionHandling.HandleUnsubscribeCallback unsubscribeMockCallback = mock( 360 | SubscriptionHandling.HandleUnsubscribeCallback.class); 361 | subscriptionHandling.handleUnsubscribe(unsubscribeMockCallback); 362 | 363 | parseLiveQueryClient.unsubscribe(parseQuery); 364 | verify(webSocketClient, times(1)).send(any(String.class)); 365 | webSocketClientCallback.onMessage(createUnsubscribedMessage(subscriptionHandling.getRequestId()).toString()); 366 | verify(unsubscribeMockCallback, times(1)).onUnsubscribe(parseQuery); 367 | 368 | ParseObject parseObject = new ParseObject("Test"); 369 | parseObject.setObjectId("testId"); 370 | webSocketClientCallback.onMessage(createObjectCreateMessage(subscriptionHandling.getRequestId(), parseObject).toString()); 371 | 372 | ArgumentCaptor objectCaptor = ArgumentCaptor.forClass(ParseObject.class); 373 | verify(eventMockCallback, times(0)).onEvent(eq(parseQuery), objectCaptor.capture()); 374 | } 375 | 376 | @Test 377 | public void testSubscriptionReplayedAfterReconnect() throws Exception { 378 | SubscriptionHandling.HandleSubscribeCallback subscribeMockCallback = mock(SubscriptionHandling.HandleSubscribeCallback.class); 379 | 380 | ParseQuery parseQuery = new ParseQuery<>("test"); 381 | createSubscription(parseQuery, subscribeMockCallback); 382 | 383 | parseLiveQueryClient.disconnect(); 384 | reconnect(); 385 | 386 | verify(webSocketClient, times(2)).send(any(String.class)); 387 | } 388 | 389 | @Test 390 | public void testSessionTokenSentOnConnect() { 391 | when(mockUser.getSessionToken()).thenReturn("the token"); 392 | parseLiveQueryClient.reconnect(); 393 | webSocketClientCallback.onOpen(); 394 | verify(webSocketClient, times(1)).send(contains("\"sessionToken\":\"the token\"")); 395 | } 396 | 397 | @Test 398 | public void testEmptySessionTokenOnConnect() { 399 | parseLiveQueryClient.reconnect(); 400 | webSocketClientCallback.onOpen(); 401 | verify(webSocketClient, times(1)).send(not(contains("\"sessionToken\":"))); 402 | } 403 | 404 | @Test 405 | public void testSessionTokenSentOnSubscribe() { 406 | when(mockUser.getSessionToken()).thenReturn("the token"); 407 | when(webSocketClient.getState()).thenReturn(WebSocketClient.State.CONNECTED); 408 | parseLiveQueryClient.subscribe(ParseQuery.getQuery("Test")); 409 | verify(webSocketClient, times(1)).send(and( 410 | contains("\"op\":\"subscribe\""), 411 | contains("\"sessionToken\":\"the token\""))); 412 | } 413 | 414 | @Test 415 | public void testEmptySessionTokenOnSubscribe() { 416 | when(mockUser.getSessionToken()).thenReturn("the token"); 417 | when(webSocketClient.getState()).thenReturn(WebSocketClient.State.CONNECTED); 418 | parseLiveQueryClient.subscribe(ParseQuery.getQuery("Test")); 419 | verify(webSocketClient, times(1)).send(contains("\"op\":\"connect\"")); 420 | verify(webSocketClient, times(1)).send(and( 421 | contains("\"op\":\"subscribe\""), 422 | contains("\"sessionToken\":\"the token\""))); 423 | } 424 | 425 | @Test 426 | public void testCallbackNotifiedOnUnexpectedDisconnect() throws Exception { 427 | LoggingCallbacks callbacks = new LoggingCallbacks(); 428 | parseLiveQueryClient.registerListener(callbacks); 429 | callbacks.transcript.assertNoEventsSoFar(); 430 | 431 | // Unexpected close from the server: 432 | webSocketClientCallback.onClose(); 433 | callbacks.transcript.assertEventsSoFar("onLiveQueryClientDisconnected: false"); 434 | } 435 | 436 | @Test 437 | public void testCallbackNotifiedOnExpectedDisconnect() throws Exception { 438 | LoggingCallbacks callbacks = new LoggingCallbacks(); 439 | parseLiveQueryClient.registerListener(callbacks); 440 | callbacks.transcript.assertNoEventsSoFar(); 441 | 442 | parseLiveQueryClient.disconnect(); 443 | verify(webSocketClient, times(1)).close(); 444 | 445 | callbacks.transcript.assertNoEventsSoFar(); 446 | // the client is a mock, so it won't actually invoke the callback automatically 447 | webSocketClientCallback.onClose(); 448 | callbacks.transcript.assertEventsSoFar("onLiveQueryClientDisconnected: true"); 449 | } 450 | 451 | @Test 452 | public void testCallbackNotifiedOnConnect() throws Exception { 453 | LoggingCallbacks callbacks = new LoggingCallbacks(); 454 | parseLiveQueryClient.registerListener(callbacks); 455 | callbacks.transcript.assertNoEventsSoFar(); 456 | 457 | reconnect(); 458 | callbacks.transcript.assertEventsSoFar("onLiveQueryClientConnected"); 459 | } 460 | 461 | @Test 462 | public void testCallbackNotifiedOnSocketError() throws Exception { 463 | LoggingCallbacks callbacks = new LoggingCallbacks(); 464 | parseLiveQueryClient.registerListener(callbacks); 465 | callbacks.transcript.assertNoEventsSoFar(); 466 | 467 | webSocketClientCallback.onError(new IOException("bad things happened")); 468 | callbacks.transcript.assertEventsSoFar("onSocketError: java.io.IOException: bad things happened", 469 | "onLiveQueryClientDisconnected: false"); 470 | } 471 | 472 | @Test 473 | public void testCallbackNotifiedOnServerError() throws Exception { 474 | LoggingCallbacks callbacks = new LoggingCallbacks(); 475 | parseLiveQueryClient.registerListener(callbacks); 476 | callbacks.transcript.assertNoEventsSoFar(); 477 | 478 | webSocketClientCallback.onMessage(createErrorMessage(1).toString()); 479 | callbacks.transcript.assertEventsSoFar("onLiveQueryError: com.parse.livequery.LiveQueryException$ServerReportedException: Server reported error; code: 1, error: testError, reconnect: true"); 480 | } 481 | 482 | private SubscriptionHandling createSubscription(ParseQuery parseQuery, 483 | SubscriptionHandling.HandleSubscribeCallback subscribeMockCallback) throws Exception { 484 | SubscriptionHandling subscriptionHandling = parseLiveQueryClient.subscribe(parseQuery).handleSubscribe(subscribeMockCallback); 485 | webSocketClientCallback.onMessage(createSubscribedMessage(subscriptionHandling.getRequestId()).toString()); 486 | return subscriptionHandling; 487 | } 488 | 489 | private void validateSameObject(SubscriptionHandling.HandleEventCallback eventMockCallback, 490 | ParseQuery parseQuery, 491 | ParseObject originalParseObject) { 492 | ArgumentCaptor objectCaptor = ArgumentCaptor.forClass(ParseObject.class); 493 | verify(eventMockCallback, times(1)).onEvent(eq(parseQuery), objectCaptor.capture()); 494 | 495 | ParseObject newParseObject = objectCaptor.getValue(); 496 | 497 | assertEquals(originalParseObject.getClassName(), newParseObject.getClassName()); 498 | assertEquals(originalParseObject.getObjectId(), newParseObject.getObjectId()); 499 | } 500 | 501 | private void clearConnection() { 502 | webSocketClient = null; 503 | webSocketClientCallback = null; 504 | } 505 | 506 | private void reconnect() { 507 | parseLiveQueryClient.reconnect(); 508 | webSocketClientCallback.onOpen(); 509 | try { 510 | webSocketClientCallback.onMessage(createConnectedMessage().toString()); 511 | } catch (JSONException e) { 512 | e.printStackTrace(); 513 | } 514 | } 515 | 516 | private static JSONObject createConnectedMessage() throws JSONException { 517 | JSONObject jsonObject = new JSONObject(); 518 | jsonObject.put("op", "connected"); 519 | return jsonObject; 520 | } 521 | 522 | private static JSONObject createSubscribedMessage(int requestId) throws JSONException { 523 | JSONObject jsonObject = new JSONObject(); 524 | jsonObject.put("op", "subscribed"); 525 | jsonObject.put("clientId", 1); 526 | jsonObject.put("requestId", requestId); 527 | return jsonObject; 528 | } 529 | 530 | private static JSONObject createUnsubscribedMessage(int requestId) throws JSONException { 531 | JSONObject jsonObject = new JSONObject(); 532 | jsonObject.put("op", "unsubscribed"); 533 | jsonObject.put("requestId", requestId); 534 | return jsonObject; 535 | } 536 | 537 | private static JSONObject createErrorMessage(int requestId) throws JSONException { 538 | JSONObject jsonObject = new JSONObject(); 539 | jsonObject.put("op", "error"); 540 | jsonObject.put("requestId", requestId); 541 | jsonObject.put("code", 1); 542 | jsonObject.put("error", "testError"); 543 | jsonObject.put("reconnect", true); 544 | return jsonObject; 545 | } 546 | 547 | private static JSONObject createObjectCreateMessage(int requestId, ParseObject parseObject) throws JSONException { 548 | JSONObject jsonObject = new JSONObject(); 549 | jsonObject.put("op", "create"); 550 | jsonObject.put("requestId", requestId); 551 | jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject)); 552 | return jsonObject; 553 | } 554 | 555 | private static JSONObject createObjectEnterMessage(int requestId, ParseObject parseObject) throws JSONException { 556 | JSONObject jsonObject = new JSONObject(); 557 | jsonObject.put("op", "enter"); 558 | jsonObject.put("requestId", requestId); 559 | jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject)); 560 | return jsonObject; 561 | } 562 | 563 | private static JSONObject createObjectUpdateMessage(int requestId, ParseObject parseObject) throws JSONException { 564 | JSONObject jsonObject = new JSONObject(); 565 | jsonObject.put("op", "update"); 566 | jsonObject.put("requestId", requestId); 567 | jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject)); 568 | return jsonObject; 569 | } 570 | 571 | private static JSONObject createObjectLeaveMessage(int requestId, ParseObject parseObject) throws JSONException { 572 | JSONObject jsonObject = new JSONObject(); 573 | jsonObject.put("op", "leave"); 574 | jsonObject.put("requestId", requestId); 575 | jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject)); 576 | return jsonObject; 577 | } 578 | 579 | private static JSONObject createObjectDeleteMessage(int requestId, ParseObject parseObject) throws JSONException { 580 | JSONObject jsonObject = new JSONObject(); 581 | jsonObject.put("op", "delete"); 582 | jsonObject.put("requestId", requestId); 583 | jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject)); 584 | return jsonObject; 585 | } 586 | 587 | private static class LoggingCallbacks implements ParseLiveQueryClientCallbacks { 588 | final Transcript transcript = new Transcript(); 589 | 590 | @Override 591 | public void onLiveQueryClientConnected(ParseLiveQueryClient client) { 592 | transcript.add("onLiveQueryClientConnected"); 593 | } 594 | 595 | @Override 596 | public void onLiveQueryClientDisconnected(ParseLiveQueryClient client, boolean userInitiated) { 597 | transcript.add("onLiveQueryClientDisconnected: " + userInitiated); 598 | } 599 | 600 | @Override 601 | public void onLiveQueryError(ParseLiveQueryClient client, LiveQueryException reason) { 602 | transcript.add("onLiveQueryError: " + reason); 603 | } 604 | 605 | @Override 606 | public void onSocketError(ParseLiveQueryClient client, Throwable reason) { 607 | transcript.add("onSocketError: " + reason); 608 | } 609 | } 610 | 611 | @ParseClassName("MockA") 612 | static class MockClassA extends ParseObject { 613 | } 614 | 615 | @ParseClassName("MockB") 616 | static class MockClassB extends ParseObject { 617 | } 618 | } 619 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Parse LiveQuery Client for Android 2 | [![License][license-svg]][license-link] [![Build Status][build-status-svg]][build-status-link] [![](https://jitpack.io/v/parse-community/ParseLiveQuery-Android.svg)](https://jitpack.io/#parse-community/ParseLiveQuery-Android) 3 | 4 | `ParseQuery` is one of the key concepts for Parse. It allows you to retrieve `ParseObject`s by specifying some conditions, making it easy to build apps such as a dashboard, a todo list or even some strategy games. However, `ParseQuery` is based on a pull model, which is not suitable for apps that need real-time support. 5 | 6 | Suppose you are building an app that allows multiple users to edit the same file at the same time. `ParseQuery` would not be an ideal tool since you can not know when to query from the server to get the updates. 7 | 8 | To solve this problem, we introduce Parse LiveQuery. This tool allows you to subscribe to a `ParseQuery` you are interested in. Once subscribed, the server will notify clients whenever a `ParseObject` that matches the `ParseQuery` is created or updated, in real-time. 9 | 10 | ## Setup Server 11 | 12 | Parse LiveQuery contains two parts, the LiveQuery server and the LiveQuery clients. In order to use live queries, you need to set up both of them. 13 | 14 | The easiest way to setup the LiveQuery server is to make it run with the [Open Source Parse Server](https://github.com/parse-community/parse-server/wiki/Parse-LiveQuery#server-setup). 15 | 16 | ## Dependency 17 | 18 | Add this in your root `build.gradle` file (**not** your module `build.gradle` file): 19 | 20 | ```gradle 21 | allprojects { 22 | repositories { 23 | ... 24 | maven { url "https://jitpack.io" } 25 | } 26 | } 27 | ``` 28 | 29 | Then, add the library to your project `build.gradle` 30 | ```gradle 31 | dependencies { 32 | implementation 'com.github.parse-community:ParseLiveQuery-Android:latest.version.here' 33 | } 34 | ``` 35 | 36 | ## Use Client 37 | 38 | The LiveQuery client interface is based around the concept of `Subscriptions`. You can register any `ParseQuery` for live updates from the associated live query server, by simply calling `subscribe()` on the client: 39 | ```java 40 | // Parse.initialize should be called first 41 | 42 | ParseLiveQueryClient parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(); 43 | ``` 44 | 45 | ### Creating Live Queries 46 | 47 | Live querying depends on creating a subscription to a `ParseQuery`: 48 | 49 | ```java 50 | ParseQuery parseQuery = ParseQuery.getQuery(Message.class); 51 | 52 | SubscriptionHandling subscriptionHandling = parseLiveQueryClient.subscribe(parseQuery) 53 | ``` 54 | 55 | Once you've subscribed to a query, you can `handle` events on them, like so: 56 | ```java 57 | subscriptionHandling.handleEvents(new SubscriptionHandling.HandleEventsCallback() { 58 | @Override 59 | public void onEvents(ParseQuery query, SubscriptionHandling.Event event, ParseObject object) { 60 | // HANDLING all events 61 | } 62 | }) 63 | ``` 64 | 65 | You can also handle a single type of event, if that's all you're interested in: 66 | ```java 67 | subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, new SubscriptionHandling.HandleEventCallback() { 68 | @Override 69 | public void onEvent(ParseQuery query, ParseObject object) { 70 | // HANDLING create event 71 | } 72 | }) 73 | ``` 74 | 75 | Handling errors is and other events is similar, take a look at the `SubscriptionHandling` class for more information. 76 | 77 | ## Advanced Usage 78 | 79 | If you wish to pass in your own OkHttpClient instance for troubleshooting or custom configs, you can instantiate the client as follows: 80 | 81 | ```java 82 | ParseLiveQueryClient parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(new OkHttp3SocketClientFactory(new OkHttpClient())); 83 | ``` 84 | 85 | The URL is determined by the Parse initialization, but you can override by specifying a `URI` object: 86 | 87 | ```java 88 | ParseLiveQueryClient parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(new URI("wss://myparseinstance.com")); 89 | ``` 90 | 91 | Note: The expected protocol for URI is `ws` instead of `http`, like in this example: `URI("ws://192.168.0.1:1337/1")`. 92 | 93 | ## How Do I Contribute? 94 | We want to make contributing to this project as easy and transparent as possible. Please refer to the [Contribution Guidelines](https://github.com/parse-community/Parse-SDK-Android/blob/master/CONTRIBUTING.md). 95 | 96 | ----- 97 | 98 | As of April 5, 2017, Parse, LLC has transferred this code to the parse-community organization, and will no longer be contributing to or distributing this code. 99 | 100 | [build-status-svg]: https://travis-ci.org/parse-community/ParseLiveQuery-Android.svg?branch=master 101 | [build-status-link]: https://travis-ci.org/parse-community/ParseLiveQuery-Android 102 | 103 | [license-svg]: https://img.shields.io/badge/license-BSD-lightgrey.svg 104 | [license-link]: https://github.com/parse-community/ParseLiveQuery-Android/blob/master/LICENSE 105 | -------------------------------------------------------------------------------- /THIRD_PARTY_NOTICES.txt: -------------------------------------------------------------------------------- 1 | This project contains portions of third party software provided under the following terms: 2 | 3 | Apache Commons IO 4 | Copyright 2002-2014 The Apache Software Foundation 5 | 6 | This product includes software developed at 7 | The Apache Software Foundation (http://www.apache.org/). 8 | 9 | Files from this library have been modified. Parse provides its modifications under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. 10 | 11 | Apache License 12 | 13 | Version 2.0, January 2004 14 | 15 | http://www.apache.org/licenses/ 16 | 17 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 18 | 19 | 1. Definitions. 20 | 21 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 22 | 23 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 24 | 25 | "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. 26 | 27 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 28 | 29 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 30 | 31 | "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. 32 | 33 | "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). 34 | 35 | "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. 36 | 37 | "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." 38 | 39 | "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. 40 | 41 | 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. 42 | 43 | 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. 44 | 45 | 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: 46 | 47 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 48 | You must cause any modified files to carry prominent notices stating that You changed the files; and 49 | 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 50 | 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. 51 | 52 | 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. 53 | 54 | 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. 55 | 56 | 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. 57 | 58 | 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. 59 | 60 | 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. 61 | 62 | 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. 63 | 64 | END OF TERMS AND CONDITIONS 65 | 66 | ----- 67 | 68 | Guava 69 | 70 | /* 71 | * Copyright (C) 2009 The Guava Authors 72 | * 73 | * Licensed under the Apache License, Version 2.0 (the "License"); 74 | * you may not use this file except in compliance with the License. 75 | * You may obtain a copy of the License at 76 | * 77 | * http://www.apache.org/licenses/LICENSE-2.0 78 | * 79 | * Unless required by applicable law or agreed to in writing, software 80 | * distributed under the License is distributed on an "AS IS" BASIS, 81 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 82 | * See the License for the specific language governing permissions and 83 | * limitations under the License. 84 | */ 85 | 86 | Files from this library have been modified. Parse provides its modifications under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. 87 | 88 | Apache License 89 | 90 | Version 2.0, January 2004 91 | 92 | http://www.apache.org/licenses/ 93 | 94 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 95 | 96 | 1. Definitions. 97 | 98 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 99 | 100 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 101 | 102 | "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. 103 | 104 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 105 | 106 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 107 | 108 | "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. 109 | 110 | "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). 111 | 112 | "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. 113 | 114 | "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." 115 | 116 | "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. 117 | 118 | 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. 119 | 120 | 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. 121 | 122 | 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: 123 | 124 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 125 | You must cause any modified files to carry prominent notices stating that You changed the files; and 126 | 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 127 | 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. 128 | 129 | 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. 130 | 131 | 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. 132 | 133 | 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. 134 | 135 | 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. 136 | 137 | 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. 138 | 139 | 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. 140 | 141 | END OF TERMS AND CONDITIONS 142 | 143 | ----- 144 | 145 | Android Open Source Project 146 | 147 | /* 148 | * Copyright (C) 2012 The Android Open Source Project 149 | * 150 | * Licensed under the Apache License, Version 2.0 (the "License"); 151 | * you may not use this file except in compliance with the License. 152 | * You may obtain a copy of the License at 153 | * 154 | * http://www.apache.org/licenses/LICENSE-2.0 155 | * 156 | * Unless required by applicable law or agreed to in writing, software 157 | * distributed under the License is distributed on an "AS IS" BASIS, 158 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 159 | * See the License for the specific language governing permissions and 160 | * limitations under the License. 161 | */ 162 | 163 | Files from this library have been modified. Parse provides its modifications under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. 164 | 165 | Apache License 166 | 167 | Version 2.0, January 2004 168 | 169 | http://www.apache.org/licenses/ 170 | 171 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 172 | 173 | 1. Definitions. 174 | 175 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 176 | 177 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 178 | 179 | "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. 180 | 181 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 182 | 183 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 184 | 185 | "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. 186 | 187 | "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). 188 | 189 | "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. 190 | 191 | "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." 192 | 193 | "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. 194 | 195 | 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. 196 | 197 | 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. 198 | 199 | 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: 200 | 201 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 202 | You must cause any modified files to carry prominent notices stating that You changed the files; and 203 | 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 204 | 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. 205 | 206 | 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. 207 | 208 | 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. 209 | 210 | 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. 211 | 212 | 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. 213 | 214 | 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. 215 | 216 | 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. 217 | 218 | END OF TERMS AND CONDITIONS 219 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | jcenter() 5 | } 6 | dependencies { 7 | classpath "com.android.tools.build:gradle:3.5.2" 8 | classpath "org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.8.2" 9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 10 | } 11 | } 12 | 13 | plugins { 14 | id "com.github.ben-manes.versions" version "0.27.0" 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | jcenter() 21 | maven { url "https://jitpack.io" } 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parse-community/ParseLiveQuery-Android/902b791cf1f7d97488e4e8a56bd76d55698ae95a/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':ParseLiveQuery' 2 | --------------------------------------------------------------------------------