Base Configuration

This commit is contained in:
2018-03-25 13:13:01 +02:00
commit bcac6a3b85
334 changed files with 56965 additions and 0 deletions

View File

@ -0,0 +1,40 @@
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
# Android Studio
.idea
*.iml
*.ipr
*.iws
classes
gen-external-apklibs
# Gradle
.gradle
build
# Other
.metadata
*/bin/*
*/gen/*
testData
testCache
server.config
# Jacoco
jacoco.exec

View File

@ -0,0 +1,42 @@
branches:
only:
- master
- /^\d+\.\d+\.\d+$/ # regex
language: android
sudo: false
jdk:
- oraclejdk8
android:
components:
- tools # to get the new `repository-11.xml`
- platform-tools
- build-tools-25.0.2
- android-25
- doc-25
- extra-google-m2repository
- extra-android-m2repository
licenses:
- 'android-sdk-license-.+'
before_install:
- pip install --user codecov
script:
- ./gradlew clean testDebugUnitTest jacocoTestReport --info
after_success:
- codecov
- ./scripts/publish_snapshot.sh
cache:
directories:
- $HOME/.gradle
- $HOME/.m2/repository
deploy:
provider: script
script: ./gradlew bintrayUpload
skip_cleanup: true
on:
branch: master
tags: true

View File

@ -0,0 +1,62 @@
# Contributing to Parse LiveQuery for Android
We want to make contributing to this project as easy and transparent as possible.
## Code of Conduct
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.
## Our Development Process
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.
### `master` is unsafe
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.
### Pull Requests
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.
1. Fork the repo and create your branch from `master`.
4. Add unit tests for any new code you add.
3. If you've changed APIs, update the documentation.
4. Ensure the test suite passes.
5. Make sure your code lints.
6. If you haven't already, complete the Contributor License Agreement ("CLA").
### Contributor License Agreement ("CLA")
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.
Complete your CLA here: <https://developers.facebook.com/opensource/cla>
## Bugs
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.
### Known Issues
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.
### Reporting New Issues
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:
* A description. What did you expect to happen and what actually happened? Why do you think that was wrong?
* 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.
* What version does this reproduce on? What version did it last work on?
* [Stacktrace or GTFO][stacktrace-or-gtfo]. In all honesty, full stacktraces with line numbers make a happy developer.
* Anything else you find relevant.
### Security Bugs
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.
## Style Guide
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:
* Most importantly, match the existing code style as much as possible.
* Try to keep lines under 100 characters, if possible.
## License
By contributing to Parse Android Parse LiveQuery, you agree that your contributions will be licensed under its license.
[google-group]: https://groups.google.com/forum/#!forum/parse-developers
[stack-overflow]: http://stackoverflow.com/tags/parse.com
[bug-reports]: https://www.parse.com/help#report
[rest-api]: https://www.parse.com/docs/rest/guide
[network-debugging-tool]: https://github.com/ParsePlatform/ParseInterceptors-Android/wiki
[parse-api-console]: http://blog.parse.com/announcements/introducing-the-parse-api-console/
[stacktrace-or-gtfo]: http://i.imgur.com/jacoj.jpg
[tests-dir]: /Parse/src/test/java/com/parse

View File

@ -0,0 +1,34 @@
BSD License
For Parse LiveQueryClient for Android software
Copyright (c) 2015-present, Parse, LLC. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name Parse nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-----
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.

View File

@ -0,0 +1,37 @@
Additional Grant of Patent Rights Version 2
"Software" means the Parse Android LiveQuery Client software distributed by Parse, LLC.
Parse, LLC. ("Parse") hereby grants to each recipient of the Software
("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable
(subject to the termination provision below) license under any Necessary
Claims, to make, have made, use, sell, offer to sell, import, and otherwise
transfer the Software. For avoidance of doubt, no license is granted under
Parses rights in any patent claims that are infringed by (i) modifications
to the Software made by you or any third party or (ii) the Software in
combination with any software or other technology.
The license granted hereunder will terminate, automatically and without notice,
if you (or any of your subsidiaries, corporate affiliates or agents) initiate
directly or indirectly, or take a direct financial interest in, any Patent
Assertion: (i) against Parse or any of its subsidiaries or corporate
affiliates, (ii) against any party if such Patent Assertion arises in whole or
in part from any software, technology, product or service of Parse or any of
its subsidiaries or corporate affiliates, or (iii) against any party relating
to the Software. Notwithstanding the foregoing, if Parse or any of its
subsidiaries or corporate affiliates files a lawsuit alleging patent
infringement against you in the first instance, and you respond by filing a
patent infringement counterclaim in that lawsuit against that party that is
unrelated to the Software, the license granted hereunder will not terminate
under section (i) of this paragraph due to such counterclaim.
A "Necessary Claim" is a claim of a patent owned by Parse that is
necessarily infringed by the Software standing alone.
A "Patent Assertion" is any lawsuit or other action alleging direct, indirect,
or contributory infringement or inducement to infringe any patent, including a
cross-claim or counterclaim.
-----
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.

View File

@ -0,0 +1,46 @@
apply plugin: 'com.android.library'
apply plugin: 'com.github.kt3k.coveralls'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.8.1'
}
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
//buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName project.version
consumerProguardFiles 'release-proguard.pro'
}
lintOptions {
abortOnError false
}
buildTypes {
debug {
testCoverageEnabled = true
}
}
}
dependencies {
//compile 'com.parse:parse-android:1.14.1'
compile "com.squareup.okhttp3:okhttp:$okhttpVersion"
compile 'com.parse.bolts:bolts-tasks:1.4.0'
testCompile 'org.robolectric:robolectric:3.3.1'
testCompile 'org.skyscreamer:jsonassert:1.5.0'
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
implementation project(':Parse')
}

View File

@ -0,0 +1,29 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/opt/android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Keep source file names, line numbers, and Parse class/method names for easier debugging
-keepattributes SourceFile,LineNumberTable
-keepnames class com.parse.** { *; }
# Required for Parse
-keepattributes *Annotation*
-keepattributes Signature
-dontwarn android.net.SSLCertificateSocketFactory
-dontwarn android.app.Notification
-dontwarn com.squareup.**
-dontwarn okio.**

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015-present, Parse, LLC.
~ All rights reserved.
~
~ This source code is licensed 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.
-->
<manifest package="com.parse.livequery">
<application />
</manifest>

View File

@ -0,0 +1,10 @@
package com.parse;
import org.json.JSONException;
import org.json.JSONObject;
/* package */ abstract class ClientOperation {
abstract JSONObject getJSONObjectRepresentation() throws JSONException;
}

View File

@ -0,0 +1,24 @@
package com.parse;
import org.json.JSONException;
import org.json.JSONObject;
/* package */ class ConnectClientOperation extends ClientOperation {
private final String applicationId;
private final String sessionToken;
/* package */ ConnectClientOperation(String applicationId, String sessionToken) {
this.applicationId = applicationId;
this.sessionToken = sessionToken;
}
@Override
/* package */ JSONObject getJSONObjectRepresentation() throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "connect");
jsonObject.put("applicationId", applicationId);
jsonObject.put("sessionToken", sessionToken);
return jsonObject;
}
}

View File

@ -0,0 +1,101 @@
package com.parse;
import java.util.Locale;
public abstract class LiveQueryException extends Exception {
private LiveQueryException() {
super();
}
private LiveQueryException(String detailMessage) {
super(detailMessage);
}
private LiveQueryException(String detailMessage, Throwable cause) {
super(detailMessage, cause);
}
private LiveQueryException(Throwable cause) {
super(cause);
}
/**
* An error that is reported when any other unknown {@link RuntimeException} occurs unexpectedly.
*/
public static class UnknownException extends LiveQueryException {
/* package */ UnknownException(String detailMessage, RuntimeException cause) {
super(detailMessage, cause);
}
}
/**
* An error that is reported when the server returns a response that cannot be parsed.
*/
public static class InvalidResponseException extends LiveQueryException {
/* package */ InvalidResponseException(String response) {
super(response);
}
}
/**
* An error that is reported when the server does not accept a query we've sent to it.
*/
public static class InvalidQueryException extends LiveQueryException {
}
/**
* An error that is reported when the server returns valid JSON, but it doesn't match the format we expect.
*/
public static class InvalidJSONException extends LiveQueryException {
// JSON used for matching.
private final String json;
/// Key that was expected to match.
private final String expectedKey;
/* package */ InvalidJSONException(String json, String expectedKey) {
super(String.format(Locale.US, "Invalid JSON; expectedKey: %s, json: %s", expectedKey, json));
this.json = json;
this.expectedKey = expectedKey;
}
public String getJson() {
return json;
}
public String getExpectedKey() {
return expectedKey;
}
}
/**
* An error that is reported when the live query server encounters an internal error.
*/
public static class ServerReportedException extends LiveQueryException {
private final int code;
private final String error;
private final boolean reconnect;
public ServerReportedException(int code, String error, boolean reconnect) {
super(String.format(Locale.US, "Server reported error; code: %d, error: %s, reconnect: %b", code, error, reconnect));
this.code = code;
this.error = error;
this.reconnect = reconnect;
}
public int getCode() {
return code;
}
public String getError() {
return error;
}
public boolean isReconnect() {
return reconnect;
}
}
}

View File

@ -0,0 +1,119 @@
package com.parse;
import android.util.Log;
import java.net.URI;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
/* package */ public class OkHttp3SocketClientFactory implements WebSocketClientFactory {
OkHttpClient mClient;
public OkHttp3SocketClientFactory(OkHttpClient client) {
mClient = client;
}
public OkHttp3SocketClientFactory() {
mClient = new OkHttpClient();
}
@Override
public WebSocketClient createInstance(WebSocketClient.WebSocketClientCallback webSocketClientCallback, URI hostUrl) {
return new OkHttp3WebSocketClient(mClient, webSocketClientCallback, hostUrl);
}
static class OkHttp3WebSocketClient implements WebSocketClient {
private static final String LOG_TAG = "OkHttpWebSocketClient";
private final WebSocketClientCallback webSocketClientCallback;
private WebSocket webSocket;
private State state = State.NONE;
private final OkHttpClient client;
private final String url;
private final int STATUS_CODE = 1000;
private final String CLOSING_MSG = "User invoked close";
private final WebSocketListener handler = new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
setState(State.CONNECTED);
webSocketClientCallback.onOpen();
}
@Override
public void onMessage(WebSocket webSocket, String text) {
webSocketClientCallback.onMessage(text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
Log.w(LOG_TAG, String.format(Locale.US,
"Socket got into inconsistent state and received %s instead.",
bytes.toString()));
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
setState(State.DISCONNECTED);
webSocketClientCallback.onClose();
}
@Override
public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) {
webSocketClientCallback.onError(t);
}
};
private OkHttp3WebSocketClient(OkHttpClient okHttpClient,
WebSocketClientCallback webSocketClientCallback, URI hostUrl) {
client = okHttpClient;
this.webSocketClientCallback = webSocketClientCallback;
url = hostUrl.toString();
}
@Override
public synchronized void open() {
if (State.NONE == state) {
// OkHttp3 connects as soon as the socket is created so do it here.
Request request = new Request.Builder()
.url(url)
.build();
webSocket = client.newWebSocket(request, handler);
setState(State.CONNECTING);
}
}
@Override
public synchronized void close() {
setState(State.DISCONNECTING);
webSocket.close(STATUS_CODE, CLOSING_MSG);
}
@Override
public void send(String message) {
if (state == State.CONNECTED) {
webSocket.send(message);
}
}
@Override
public State getState() {
return state;
}
private synchronized void setState(State newState) {
this.state = newState;
this.webSocketClientCallback.stateChanged();
}
}
}

View File

@ -0,0 +1,47 @@
package com.parse;
import java.net.URI;
import java.util.concurrent.Executor;
public interface ParseLiveQueryClient {
<T extends ParseObject> SubscriptionHandling<T> subscribe(ParseQuery<T> query);
<T extends ParseObject> void unsubscribe(final ParseQuery<T> query);
<T extends ParseObject> void unsubscribe(final ParseQuery<T> query, final SubscriptionHandling<T> subscriptionHandling);
void connectIfNeeded();
void reconnect();
void disconnect();
void registerListener(ParseLiveQueryClientCallbacks listener);
void unregisterListener(ParseLiveQueryClientCallbacks listener);
class Factory {
public static ParseLiveQueryClient getClient() {
return new ParseLiveQueryClientImpl();
}
public static ParseLiveQueryClient getClient(WebSocketClientFactory webSocketClientFactory) {
return new ParseLiveQueryClientImpl(webSocketClientFactory);
}
public static ParseLiveQueryClient getClient(URI uri) {
return new ParseLiveQueryClientImpl(uri);
}
public static ParseLiveQueryClient getClient(URI uri, WebSocketClientFactory webSocketClientFactory) {
return new ParseLiveQueryClientImpl(uri, webSocketClientFactory);
}
/* package */
static ParseLiveQueryClient getClient(URI uri, WebSocketClientFactory webSocketClientFactory, Executor taskExecutor) {
return new ParseLiveQueryClientImpl(uri, webSocketClientFactory, taskExecutor);
}
}
}

View File

@ -0,0 +1,11 @@
package com.parse;
public interface ParseLiveQueryClientCallbacks {
void onLiveQueryClientConnected(ParseLiveQueryClient client);
void onLiveQueryClientDisconnected(ParseLiveQueryClient client, boolean userInitiated);
void onLiveQueryError(ParseLiveQueryClient client, LiveQueryException reason);
void onSocketError(ParseLiveQueryClient client, Throwable reason);
}

View File

@ -0,0 +1,435 @@
package com.parse;
import android.util.Log;
import android.util.SparseArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import bolts.Continuation;
import bolts.Task;
import okhttp3.OkHttpClient;
import static com.parse.Parse.checkInit;
/* package */ class ParseLiveQueryClientImpl implements ParseLiveQueryClient {
private static final String LOG_TAG = "ParseLiveQueryClient";
private final Executor taskExecutor;
private final String applicationId;
private final String clientKey;
private final SparseArray<Subscription<? extends ParseObject>> subscriptions = new SparseArray<>();
private final URI uri;
private final WebSocketClientFactory webSocketClientFactory;
private final WebSocketClient.WebSocketClientCallback webSocketClientCallback;
private final List<ParseLiveQueryClientCallbacks> mCallbacks = new ArrayList<>();
private WebSocketClient webSocketClient;
private int requestIdCount = 1;
private boolean userInitiatedDisconnect = false;
private boolean hasReceivedConnected = false;
/* package */ ParseLiveQueryClientImpl() {
this(getDefaultUri());
}
/* package */ ParseLiveQueryClientImpl(URI uri) {
this(uri, new OkHttp3SocketClientFactory(new OkHttpClient()), Task.BACKGROUND_EXECUTOR);
}
/* package */ ParseLiveQueryClientImpl(URI uri, WebSocketClientFactory webSocketClientFactory) {
this(uri, webSocketClientFactory, Task.BACKGROUND_EXECUTOR);
}
/* package */ ParseLiveQueryClientImpl(WebSocketClientFactory webSocketClientFactory) {
this(getDefaultUri(), webSocketClientFactory, Task.BACKGROUND_EXECUTOR);
}
/* package */ ParseLiveQueryClientImpl(URI uri, WebSocketClientFactory webSocketClientFactory, Executor taskExecutor) {
checkInit();
this.uri = uri;
this.applicationId = ParsePlugins.get().applicationId();
this.clientKey = ParsePlugins.get().clientKey();
this.webSocketClientFactory = webSocketClientFactory;
this.taskExecutor = taskExecutor;
this.webSocketClientCallback = getWebSocketClientCallback();
}
private static URI getDefaultUri() {
URL serverUrl = ParseRESTCommand.server;
if (serverUrl == null) return null;
String url = serverUrl.toString();
if (serverUrl.getProtocol().equals("https")) {
url = url.replaceFirst("https", "wss");
} else {
url = url.replaceFirst("http", "ws");
}
try {
return new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
@Override
public <T extends ParseObject> SubscriptionHandling<T> subscribe(ParseQuery<T> query) {
int requestId = requestIdGenerator();
Subscription<T> subscription = new Subscription<>(requestId, query);
subscriptions.append(requestId, subscription);
if (isConnected()) {
sendSubscription(subscription);
} else if (userInitiatedDisconnect) {
Log.w(LOG_TAG, "Warning: The client was explicitly disconnected! You must explicitly call .reconnect() in order to process your subscriptions.");
} else {
connectIfNeeded();
}
return subscription;
}
public void connectIfNeeded() {
switch (getWebSocketState()) {
case CONNECTED:
// nothing to do
break;
case CONNECTING:
// just wait for it to finish connecting
break;
case NONE:
case DISCONNECTING:
case DISCONNECTED:
reconnect();
break;
default:
break;
}
}
@Override
public <T extends ParseObject> void unsubscribe(final ParseQuery<T> query) {
if (query != null) {
for (int i = 0; i < subscriptions.size(); i++) {
Subscription subscription = subscriptions.valueAt(i);
if (query.equals(subscription.getQuery())) {
sendUnsubscription(subscription);
}
}
}
}
@Override
public <T extends ParseObject> void unsubscribe(final ParseQuery<T> query, final SubscriptionHandling<T> subscriptionHandling) {
if (query != null && subscriptionHandling != null) {
for (int i = 0; i < subscriptions.size(); i++) {
Subscription subscription = subscriptions.valueAt(i);
if (query.equals(subscription.getQuery()) && subscriptionHandling.equals(subscription)) {
sendUnsubscription(subscription);
}
}
}
}
@Override
public void reconnect() {
if (webSocketClient != null) {
webSocketClient.close();
}
userInitiatedDisconnect = false;
hasReceivedConnected = false;
webSocketClient = webSocketClientFactory.createInstance(webSocketClientCallback, uri);
webSocketClient.open();
}
@Override
public void disconnect() {
if (webSocketClient != null) {
webSocketClient.close();
webSocketClient = null;
}
userInitiatedDisconnect = true;
hasReceivedConnected = false;
}
@Override
public void registerListener(ParseLiveQueryClientCallbacks listener) {
mCallbacks.add(listener);
}
@Override
public void unregisterListener(ParseLiveQueryClientCallbacks listener) {
mCallbacks.remove(listener);
}
// Private methods
private synchronized int requestIdGenerator() {
return requestIdCount++;
}
private WebSocketClient.State getWebSocketState() {
WebSocketClient.State state = webSocketClient == null ? null : webSocketClient.getState();
return state == null ? WebSocketClient.State.NONE : state;
}
private boolean isConnected() {
return hasReceivedConnected && inAnyState(WebSocketClient.State.CONNECTED);
}
private boolean inAnyState(WebSocketClient.State... states) {
return Arrays.asList(states).contains(getWebSocketState());
}
private Task<Void> handleOperationAsync(final String message) {
return Task.call(new Callable<Void>() {
public Void call() throws Exception {
parseMessage(message);
return null;
}
}, taskExecutor);
}
private Task<Void> sendOperationAsync(final ClientOperation clientOperation) {
return Task.call(new Callable<Void>() {
public Void call() throws Exception {
JSONObject jsonEncoded = clientOperation.getJSONObjectRepresentation();
String jsonString = jsonEncoded.toString();
if (Parse.getLogLevel() <= Parse.LOG_LEVEL_DEBUG) {
Log.d(LOG_TAG, "Sending over websocket: " + jsonString);
}
webSocketClient.send(jsonString);
return null;
}
}, taskExecutor);
}
private void parseMessage(String message) throws LiveQueryException {
try {
JSONObject jsonObject = new JSONObject(message);
String rawOperation = jsonObject.getString("op");
switch (rawOperation) {
case "connected":
hasReceivedConnected = true;
dispatchConnected();
Log.v(LOG_TAG, "Connected, sending pending subscription");
for (int i = 0; i < subscriptions.size(); i++) {
sendSubscription(subscriptions.valueAt(i));
}
break;
case "redirect":
String url = jsonObject.getString("url");
// TODO: Handle redirect.
Log.d(LOG_TAG, "Redirect is not yet handled");
break;
case "subscribed":
handleSubscribedEvent(jsonObject);
break;
case "unsubscribed":
handleUnsubscribedEvent(jsonObject);
break;
case "enter":
handleObjectEvent(Subscription.Event.ENTER, jsonObject);
break;
case "leave":
handleObjectEvent(Subscription.Event.LEAVE, jsonObject);
break;
case "update":
handleObjectEvent(Subscription.Event.UPDATE, jsonObject);
break;
case "create":
handleObjectEvent(Subscription.Event.CREATE, jsonObject);
break;
case "delete":
handleObjectEvent(Subscription.Event.DELETE, jsonObject);
break;
case "error":
handleErrorEvent(jsonObject);
break;
default:
throw new LiveQueryException.InvalidResponseException(message);
}
} catch (JSONException e) {
throw new LiveQueryException.InvalidResponseException(message);
}
}
private void dispatchConnected() {
for (ParseLiveQueryClientCallbacks callback : mCallbacks) {
callback.onLiveQueryClientConnected(this);
}
}
private void dispatchDisconnected() {
for (ParseLiveQueryClientCallbacks callback : mCallbacks) {
callback.onLiveQueryClientDisconnected(this, userInitiatedDisconnect);
}
}
private void dispatchServerError(LiveQueryException exc) {
for (ParseLiveQueryClientCallbacks callback : mCallbacks) {
callback.onLiveQueryError(this, exc);
}
}
private void dispatchSocketError(Throwable reason) {
userInitiatedDisconnect = false;
for (ParseLiveQueryClientCallbacks callback : mCallbacks) {
callback.onSocketError(this, reason);
}
dispatchDisconnected();
}
private <T extends ParseObject> void handleSubscribedEvent(JSONObject jsonObject) throws JSONException {
final int requestId = jsonObject.getInt("requestId");
final Subscription<T> subscription = subscriptionForRequestId(requestId);
if (subscription != null) {
subscription.didSubscribe(subscription.getQuery());
}
}
private <T extends ParseObject> void handleUnsubscribedEvent(JSONObject jsonObject) throws JSONException {
final int requestId = jsonObject.getInt("requestId");
final Subscription<T> subscription = subscriptionForRequestId(requestId);
if (subscription != null) {
subscription.didUnsubscribe(subscription.getQuery());
subscriptions.remove(requestId);
}
}
private <T extends ParseObject> void handleObjectEvent(Subscription.Event event, JSONObject jsonObject) throws JSONException {
final int requestId = jsonObject.getInt("requestId");
final Subscription<T> subscription = subscriptionForRequestId(requestId);
if (subscription != null) {
T object = ParseObject.fromJSON(jsonObject.getJSONObject("object"), subscription.getQueryState().className(), ParseDecoder.get(), subscription.getQueryState().selectedKeys());
subscription.didReceive(event, subscription.getQuery(), object);
}
}
private <T extends ParseObject> void handleErrorEvent(JSONObject jsonObject) throws JSONException {
int requestId = jsonObject.getInt("requestId");
int code = jsonObject.getInt("code");
String error = jsonObject.getString("error");
Boolean reconnect = jsonObject.getBoolean("reconnect");
final Subscription<T> subscription = subscriptionForRequestId(requestId);
LiveQueryException exc = new LiveQueryException.ServerReportedException(code, error, reconnect);
if (subscription != null) {
subscription.didEncounter(exc, subscription.getQuery());
}
dispatchServerError(exc);
}
private <T extends ParseObject> Subscription<T> subscriptionForRequestId(int requestId) {
//noinspection unchecked
return (Subscription<T>) subscriptions.get(requestId);
}
private <T extends ParseObject> void sendSubscription(final Subscription<T> subscription) {
ParseUser.getCurrentSessionTokenAsync().onSuccess(new Continuation<String, Void>() {
@Override
public Void then(Task<String> task) throws Exception {
String sessionToken = task.getResult();
SubscribeClientOperation<T> op = new SubscribeClientOperation<>(subscription.getRequestId(), subscription.getQueryState(), sessionToken);
// dispatch errors
sendOperationAsync(op).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) {
Exception error = task.getError();
if (error != null) {
if (error instanceof RuntimeException) {
subscription.didEncounter(new LiveQueryException.UnknownException(
"Error when subscribing", (RuntimeException) error), subscription.getQuery());
}
}
return null;
}
});
return null;
}
});
}
private void sendUnsubscription(Subscription subscription) {
sendOperationAsync(new UnsubscribeClientOperation(subscription.getRequestId()));
}
private WebSocketClient.WebSocketClientCallback getWebSocketClientCallback() {
return new WebSocketClient.WebSocketClientCallback() {
@Override
public void onOpen() {
hasReceivedConnected = false;
Log.v(LOG_TAG, "Socket opened");
ParseUser.getCurrentSessionTokenAsync().onSuccessTask(new Continuation<String, Task<Void>>() {
@Override
public Task<Void> then(Task<String> task) throws Exception {
String sessionToken = task.getResult();
return sendOperationAsync(new ConnectClientOperation(applicationId, sessionToken));
}
}).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) {
Exception error = task.getError();
if (error != null) {
Log.e(LOG_TAG, "Error when connection client", error);
}
return null;
}
});
}
@Override
public void onMessage(String message) {
Log.v(LOG_TAG, "Socket onMessage " + message);
handleOperationAsync(message).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) {
Exception error = task.getError();
if (error != null) {
Log.e(LOG_TAG, "Error handling message", error);
}
return null;
}
});
}
@Override
public void onClose() {
Log.v(LOG_TAG, "Socket onClose");
hasReceivedConnected = false;
dispatchDisconnected();
}
@Override
public void onError(Throwable exception) {
Log.e(LOG_TAG, "Socket onError", exception);
hasReceivedConnected = false;
dispatchSocketError(exception);
}
@Override
public void stateChanged() {
Log.v(LOG_TAG, "Socket stateChanged");
}
};
}
}

View File

@ -0,0 +1,38 @@
package com.parse;
import org.json.JSONException;
import org.json.JSONObject;
/* package */ class SubscribeClientOperation<T extends ParseObject> extends ClientOperation {
private final int requestId;
private final ParseQuery.State<T> state;
private final String sessionToken;
/* package */ SubscribeClientOperation(int requestId, ParseQuery.State<T> state, String sessionToken) {
this.requestId = requestId;
this.state = state;
this.sessionToken = sessionToken;
}
@Override
/* package */ JSONObject getJSONObjectRepresentation() throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "subscribe");
jsonObject.put("requestId", requestId);
jsonObject.put("sessionToken", sessionToken);
JSONObject queryJsonObject = new JSONObject();
queryJsonObject.put("className", state.className());
// TODO: add support for fields
// https://github.com/ParsePlatform/parse-server/issues/3671
PointerEncoder pointerEncoder = PointerEncoder.get();
queryJsonObject.put("where", pointerEncoder.encode(state.constraints()));
jsonObject.put("query", queryJsonObject);
return jsonObject;
}
}

View File

@ -0,0 +1,120 @@
package com.parse;
import java.util.ArrayList;
import java.util.List;
/* package */ class Subscription<T extends ParseObject> implements SubscriptionHandling<T> {
private final List<HandleEventsCallback<T>> handleEventsCallbacks = new ArrayList<>();
private final List<HandleErrorCallback<T>> handleErrorCallbacks = new ArrayList<>();
private final List<HandleSubscribeCallback<T>> handleSubscribeCallbacks = new ArrayList<>();
private final List<HandleUnsubscribeCallback<T>> handleUnsubscribeCallbacks = new ArrayList<>();
private final int requestId;
private final ParseQuery<T> query;
private final ParseQuery.State<T> state;
/* package */ Subscription(int requestId, ParseQuery<T> query) {
this.requestId = requestId;
this.query = query;
this.state = query.getBuilder().build();
}
@Override
public Subscription<T> handleEvents(HandleEventsCallback<T> callback) {
handleEventsCallbacks.add(callback);
return this;
}
@Override
public Subscription<T> handleEvent(final Event event, final HandleEventCallback<T> callback) {
return handleEvents(new HandleEventsCallback<T>() {
@Override
public void onEvents(ParseQuery<T> query, Event callbackEvent, T object) {
if (callbackEvent == event) {
callback.onEvent(query, object);
}
}
});
}
@Override
public Subscription<T> handleError(HandleErrorCallback<T> callback) {
handleErrorCallbacks.add(callback);
return this;
}
@Override
public Subscription<T> handleSubscribe(HandleSubscribeCallback<T> callback) {
handleSubscribeCallbacks.add(callback);
return this;
}
@Override
public Subscription<T> handleUnsubscribe(HandleUnsubscribeCallback<T> callback) {
handleUnsubscribeCallbacks.add(callback);
return this;
}
@Override
public int getRequestId() {
return requestId;
}
/* package */ ParseQuery<T> getQuery() {
return query;
}
/* package */ ParseQuery.State<T> getQueryState() {
return state;
}
/**
* Tells the handler that an event has been received from the live query server.
*
* @param event The event that has been received from the server.
* @param query The query that the event occurred on.
*/
/* package */ void didReceive(Event event, ParseQuery<T> query, T object) {
for (HandleEventsCallback<T> handleEventsCallback : handleEventsCallbacks) {
handleEventsCallback.onEvents(query, event, object);
}
}
/**
* Tells the handler that an error has been received from the live query server.
*
* @param error The error that the server has encountered.
* @param query The query that the error occurred on.
*/
/* package */ void didEncounter(LiveQueryException error, ParseQuery<T> query) {
for (HandleErrorCallback<T> handleErrorCallback : handleErrorCallbacks) {
handleErrorCallback.onError(query, error);
}
}
/**
* Tells the handler that a query has been successfully registered with the server.
* - note: This may be invoked multiple times if the client disconnects/reconnects.
*
* @param query The query that has been subscribed.
*/
/* package */ void didSubscribe(ParseQuery<T> query) {
for (HandleSubscribeCallback<T> handleSubscribeCallback : handleSubscribeCallbacks) {
handleSubscribeCallback.onSubscribe(query);
}
}
/**
* Tells the handler that a query has been successfully deregistered from the server.
* - note: This is not called unless `unregister()` is explicitly called.
*
* @param query The query that has been unsubscribed.
*/
/* package */ void didUnsubscribe(ParseQuery<T> query) {
for (HandleUnsubscribeCallback<T> handleUnsubscribeCallback : handleUnsubscribeCallbacks) {
handleUnsubscribeCallback.onUnsubscribe(query);
}
}
}

View File

@ -0,0 +1,72 @@
package com.parse;
public interface SubscriptionHandling<T extends ParseObject> {
/**
* Register a callback for when an event occurs.
*
* @param callback The callback to register.
* @return The same SubscriptionHandling, for easy chaining.
*/
SubscriptionHandling<T> handleEvents(Subscription.HandleEventsCallback<T> callback);
/**
* Register a callback for when an event occurs.
*
* @param event The event type to handle. You should pass one of the enum cases in Event
* @param callback The callback to register.
* @return The same SubscriptionHandling, for easy chaining.
*/
SubscriptionHandling<T> handleEvent(Subscription.Event event, Subscription.HandleEventCallback<T> callback);
/**
* Register a callback for when an event occurs.
*
* @param callback The callback to register.
* @return The same SubscriptionHandling, for easy chaining.
*/
SubscriptionHandling<T> handleError(Subscription.HandleErrorCallback<T> callback);
/**
* Register a callback for when a client succesfully subscribes to a query.
*
* @param callback The callback to register.
* @return The same SubscriptionHandling, for easy chaining.
*/
SubscriptionHandling<T> handleSubscribe(Subscription.HandleSubscribeCallback<T> callback);
/**
* Register a callback for when a query has been unsubscribed.
*
* @param callback The callback to register.
* @return The same SubscriptionHandling, for easy chaining.
*/
SubscriptionHandling<T> handleUnsubscribe(Subscription.HandleUnsubscribeCallback<T> callback);
int getRequestId();
interface HandleEventsCallback<T extends ParseObject> {
void onEvents(ParseQuery<T> query, Subscription.Event event, T object);
}
interface HandleEventCallback<T extends ParseObject> {
void onEvent(ParseQuery<T> query, T object);
}
interface HandleErrorCallback<T extends ParseObject> {
void onError(ParseQuery<T> query, LiveQueryException exception);
}
interface HandleSubscribeCallback<T extends ParseObject> {
void onSubscribe(ParseQuery<T> query);
}
interface HandleUnsubscribeCallback<T extends ParseObject> {
void onUnsubscribe(ParseQuery<T> query);
}
enum Event {
CREATE, ENTER, UPDATE, LEAVE, DELETE
}
}

View File

@ -0,0 +1,21 @@
package com.parse;
import org.json.JSONException;
import org.json.JSONObject;
/* package */ class UnsubscribeClientOperation extends ClientOperation {
private final int requestId;
/* package */ UnsubscribeClientOperation(int requestId) {
this.requestId = requestId;
}
@Override
/* package */ JSONObject getJSONObjectRepresentation() throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "unsubscribe");
jsonObject.put("requestId", requestId);
return jsonObject;
}
}

View File

@ -0,0 +1,27 @@
package com.parse;
/* package */ interface WebSocketClient {
void open();
void close();
void send(String message);
State getState();
interface WebSocketClientCallback {
void onOpen();
void onMessage(String message);
void onClose();
void onError(Throwable exception);
void stateChanged();
}
enum State {NONE, CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED}
}

View File

@ -0,0 +1,9 @@
package com.parse;
import java.net.URI;
/* package */ interface WebSocketClientFactory {
WebSocketClient createInstance(WebSocketClient.WebSocketClientCallback webSocketClientCallback, URI hostUrl);
}

View File

@ -0,0 +1,10 @@
package com.parse;
import java.util.concurrent.Executor;
class ImmediateExecutor implements Executor {
@Override
public void execute(Runnable runnable) {
runnable.run();
}
}

View File

@ -0,0 +1,609 @@
package com.parse;
import org.assertj.core.api.Assertions;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.Transcript;
import java.io.IOException;
import java.net.URI;
import bolts.Task;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.mockito.AdditionalMatchers.and;
import static org.mockito.AdditionalMatchers.not;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.parse.livequery.BuildConfig;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class TestParseLiveQueryClient {
private WebSocketClient webSocketClient;
private WebSocketClient.WebSocketClientCallback webSocketClientCallback;
private ParseLiveQueryClient parseLiveQueryClient;
private ParseUser mockUser;
@Before
public void setUp() throws Exception {
ParsePlugins.initialize("1234", "1234");
// Register a mock currentUserController to make getCurrentUser work
mockUser = mock(ParseUser.class);
ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
when(currentUserController.getAsync(anyBoolean())).thenAnswer(new Answer<Task<ParseUser>>() {
@Override
public Task<ParseUser> answer(InvocationOnMock invocation) throws Throwable {
return Task.forResult(mockUser);
}
});
when(currentUserController.getCurrentSessionTokenAsync()).thenAnswer(new Answer<Task<String>>() {
@Override
public Task<String> answer(InvocationOnMock invocation) throws Throwable {
return Task.forResult(mockUser.getSessionToken());
}
});
ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(new URI(""), new WebSocketClientFactory() {
@Override
public WebSocketClient createInstance(WebSocketClient.WebSocketClientCallback webSocketClientCallback, URI hostUrl) {
TestParseLiveQueryClient.this.webSocketClientCallback = webSocketClientCallback;
webSocketClient = mock(WebSocketClient.class);
return webSocketClient;
}
}, new ImmediateExecutor());
reconnect();
}
@After
public void tearDown() throws Exception {
ParseCorePlugins.getInstance().reset();
ParsePlugins.reset();
}
@Test
public void testSubscribeAfterSocketConnectBeforeConnectedOp() throws Exception {
// Bug: https://github.com/parse-community/ParseLiveQuery-Android/issues/46
ParseQuery<ParseObject> queryA = ParseQuery.getQuery("objA");
ParseQuery<ParseObject> queryB = ParseQuery.getQuery("objB");
clearConnection();
// This will trigger connectIfNeeded(), which calls reconnect()
SubscriptionHandling<ParseObject> subA = parseLiveQueryClient.subscribe(queryA);
verify(webSocketClient, times(1)).open();
verify(webSocketClient, never()).send(anyString());
// Now the socket is open
webSocketClientCallback.onOpen();
when(webSocketClient.getState()).thenReturn(WebSocketClient.State.CONNECTED);
// and we send op=connect
verify(webSocketClient, times(1)).send(contains("\"op\":\"connect\""));
// Now if we subscribe to queryB, we SHOULD NOT send the subscribe yet, until we get op=connected
SubscriptionHandling<ParseObject> subB = parseLiveQueryClient.subscribe(queryB);
verify(webSocketClient, never()).send(contains("\"op\":\"subscribe\""));
// on op=connected, _then_ we should send both subscriptions
webSocketClientCallback.onMessage(createConnectedMessage().toString());
verify(webSocketClient, times(2)).send(contains("\"op\":\"subscribe\""));
}
@Test
public void testSubscribeWhenSubscribedToCallback() throws Exception {
SubscriptionHandling.HandleSubscribeCallback<ParseObject> subscribeMockCallback = mock(SubscriptionHandling.HandleSubscribeCallback.class);
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
createSubscription(parseQuery, subscribeMockCallback);
verify(subscribeMockCallback, times(1)).onSubscribe(parseQuery);
}
@Test
public void testUnsubscribeWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
parseLiveQueryClient.unsubscribe(parseQuery);
verify(webSocketClient, times(1)).send(any(String.class));
SubscriptionHandling.HandleUnsubscribeCallback<ParseObject> unsubscribeMockCallback = mock(
SubscriptionHandling.HandleUnsubscribeCallback.class);
subscriptionHandling.handleUnsubscribe(unsubscribeMockCallback);
webSocketClientCallback.onMessage(createUnsubscribedMessage(subscriptionHandling.getRequestId()).toString());
verify(unsubscribeMockCallback, times(1)).onUnsubscribe(parseQuery);
}
@Test
public void testErrorWhileSubscribing() throws Exception {
ParseQuery.State state = mock(ParseQuery.State.class);
when(state.constraints()).thenThrow(new RuntimeException("forced error"));
ParseQuery.State.Builder builder = mock(ParseQuery.State.Builder.class);
when(builder.build()).thenReturn(state);
ParseQuery query = mock(ParseQuery.class);
when(query.getBuilder()).thenReturn(builder);
SubscriptionHandling handling = parseLiveQueryClient.subscribe(query);
SubscriptionHandling.HandleErrorCallback<ParseObject> errorMockCallback = mock(SubscriptionHandling.HandleErrorCallback.class);
handling.handleError(errorMockCallback);
// Trigger a re-subscribe
webSocketClientCallback.onMessage(createConnectedMessage().toString());
// This will never get a chance to call op=subscribe, because an exception was thrown
verify(webSocketClient, never()).send(anyString());
ArgumentCaptor<LiveQueryException> errorCaptor = ArgumentCaptor.forClass(LiveQueryException.class);
verify(errorMockCallback, times(1)).onError(eq(query), errorCaptor.capture());
assertEquals("Error when subscribing", errorCaptor.getValue().getMessage());
assertNotNull(errorCaptor.getValue().getCause());
}
@Test
public void testErrorWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleErrorCallback<ParseObject> errorMockCallback = mock(SubscriptionHandling.HandleErrorCallback.class);
subscriptionHandling.handleError(errorMockCallback);
webSocketClientCallback.onMessage(createErrorMessage(subscriptionHandling.getRequestId()).toString());
ArgumentCaptor<LiveQueryException> errorCaptor = ArgumentCaptor.forClass(LiveQueryException.class);
verify(errorMockCallback, times(1)).onError(eq(parseQuery), errorCaptor.capture());
LiveQueryException genericError = errorCaptor.getValue();
assertTrue(genericError instanceof LiveQueryException.ServerReportedException);
LiveQueryException.ServerReportedException serverError = (LiveQueryException.ServerReportedException) genericError;
assertEquals(serverError.getError(), "testError");
assertEquals(serverError.getCode(), 1);
assertEquals(serverError.isReconnect(), true);
}
@Test
public void testHeterogeneousSubscriptions() throws Exception {
ParseObject.registerSubclass(MockClassA.class);
ParseObject.registerSubclass(MockClassB.class);
ParseQuery<MockClassA> query1 = ParseQuery.getQuery(MockClassA.class);
ParseQuery<MockClassB> query2 = ParseQuery.getQuery(MockClassB.class);
SubscriptionHandling<MockClassA> handle1 = parseLiveQueryClient.subscribe(query1);
SubscriptionHandling<MockClassB> handle2 = parseLiveQueryClient.subscribe(query2);
handle1.handleError(new SubscriptionHandling.HandleErrorCallback<MockClassA>() {
@Override
public void onError(ParseQuery<MockClassA> query, LiveQueryException exception) {
throw new RuntimeException(exception);
}
});
handle2.handleError(new SubscriptionHandling.HandleErrorCallback<MockClassB>() {
@Override
public void onError(ParseQuery<MockClassB> query, LiveQueryException exception) {
throw new RuntimeException(exception);
}
});
SubscriptionHandling.HandleEventCallback<MockClassA> eventMockCallback1 = mock(SubscriptionHandling.HandleEventCallback.class);
SubscriptionHandling.HandleEventCallback<MockClassB> eventMockCallback2 = mock(SubscriptionHandling.HandleEventCallback.class);
handle1.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback1);
handle2.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback2);
ParseObject parseObject1 = new MockClassA();
parseObject1.setObjectId("testId1");
ParseObject parseObject2 = new MockClassB();
parseObject2.setObjectId("testId2");
webSocketClientCallback.onMessage(createObjectCreateMessage(handle1.getRequestId(), parseObject1).toString());
webSocketClientCallback.onMessage(createObjectCreateMessage(handle2.getRequestId(), parseObject2).toString());
validateSameObject((SubscriptionHandling.HandleEventCallback) eventMockCallback1, (ParseQuery) query1, parseObject1);
validateSameObject((SubscriptionHandling.HandleEventCallback) eventMockCallback2, (ParseQuery) query2, parseObject2);
}
@Test
public void testCreateEventWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectCreateMessage(subscriptionHandling.getRequestId(), parseObject).toString());
validateSameObject(eventMockCallback, parseQuery, parseObject);
}
@Test
public void testEnterEventWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.ENTER, eventMockCallback);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectEnterMessage(subscriptionHandling.getRequestId(), parseObject).toString());
validateSameObject(eventMockCallback, parseQuery, parseObject);
}
@Test
public void testUpdateEventWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.UPDATE, eventMockCallback);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectUpdateMessage(subscriptionHandling.getRequestId(), parseObject).toString());
validateSameObject(eventMockCallback, parseQuery, parseObject);
}
@Test
public void testLeaveEventWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.LEAVE, eventMockCallback);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectLeaveMessage(subscriptionHandling.getRequestId(), parseObject).toString());
validateSameObject(eventMockCallback, parseQuery, parseObject);
}
@Test
public void testDeleteEventWhenSubscribedToCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.DELETE, eventMockCallback);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectDeleteMessage(subscriptionHandling.getRequestId(), parseObject).toString());
validateSameObject(eventMockCallback, parseQuery, parseObject);
}
@Test
public void testCreateEventWhenSubscribedToAnyCallback() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventsCallback<ParseObject> eventsMockCallback = mock(SubscriptionHandling.HandleEventsCallback.class);
subscriptionHandling.handleEvents(eventsMockCallback);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectCreateMessage(subscriptionHandling.getRequestId(), parseObject).toString());
ArgumentCaptor<ParseObject> objectCaptor = ArgumentCaptor.forClass(ParseObject.class);
verify(eventsMockCallback, times(1)).onEvents(eq(parseQuery), eq(SubscriptionHandling.Event.CREATE), objectCaptor.capture());
ParseObject newParseObject = objectCaptor.getValue();
assertEquals(parseObject.getObjectId(), newParseObject.getObjectId());
}
@Test
public void testSubscriptionStoppedAfterUnsubscribe() throws Exception {
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
SubscriptionHandling<ParseObject> subscriptionHandling = createSubscription(parseQuery,
mock(SubscriptionHandling.HandleSubscribeCallback.class));
SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback = mock(SubscriptionHandling.HandleEventCallback.class);
subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, eventMockCallback);
SubscriptionHandling.HandleUnsubscribeCallback<ParseObject> unsubscribeMockCallback = mock(
SubscriptionHandling.HandleUnsubscribeCallback.class);
subscriptionHandling.handleUnsubscribe(unsubscribeMockCallback);
parseLiveQueryClient.unsubscribe(parseQuery);
verify(webSocketClient, times(1)).send(any(String.class));
webSocketClientCallback.onMessage(createUnsubscribedMessage(subscriptionHandling.getRequestId()).toString());
verify(unsubscribeMockCallback, times(1)).onUnsubscribe(parseQuery);
ParseObject parseObject = new ParseObject("Test");
parseObject.setObjectId("testId");
webSocketClientCallback.onMessage(createObjectCreateMessage(subscriptionHandling.getRequestId(), parseObject).toString());
ArgumentCaptor<ParseObject> objectCaptor = ArgumentCaptor.forClass(ParseObject.class);
verify(eventMockCallback, times(0)).onEvent(eq(parseQuery), objectCaptor.capture());
}
@Test
public void testSubscriptionReplayedAfterReconnect() throws Exception {
SubscriptionHandling.HandleSubscribeCallback<ParseObject> subscribeMockCallback = mock(SubscriptionHandling.HandleSubscribeCallback.class);
ParseQuery<ParseObject> parseQuery = new ParseQuery<>("test");
createSubscription(parseQuery, subscribeMockCallback);
parseLiveQueryClient.disconnect();
reconnect();
verify(webSocketClient, times(2)).send(any(String.class));
}
@Test
public void testSessionTokenSentOnConnect() {
when(mockUser.getSessionToken()).thenReturn("the token");
parseLiveQueryClient.reconnect();
webSocketClientCallback.onOpen();
verify(webSocketClient, times(1)).send(contains("\"sessionToken\":\"the token\""));
}
@Test
public void testEmptySessionTokenOnConnect() {
parseLiveQueryClient.reconnect();
webSocketClientCallback.onOpen();
verify(webSocketClient, times(1)).send(not(contains("\"sessionToken\":")));
}
@Test
public void testSessionTokenSentOnSubscribe() {
when(mockUser.getSessionToken()).thenReturn("the token");
when(webSocketClient.getState()).thenReturn(WebSocketClient.State.CONNECTED);
parseLiveQueryClient.subscribe(ParseQuery.getQuery("Test"));
verify(webSocketClient, times(1)).send(and(
contains("\"op\":\"subscribe\""),
contains("\"sessionToken\":\"the token\"")));
}
@Test
public void testEmptySessionTokenOnSubscribe() {
when(mockUser.getSessionToken()).thenReturn("the token");
when(webSocketClient.getState()).thenReturn(WebSocketClient.State.CONNECTED);
parseLiveQueryClient.subscribe(ParseQuery.getQuery("Test"));
verify(webSocketClient, times(1)).send(contains("\"op\":\"connect\""));
verify(webSocketClient, times(1)).send(and(
contains("\"op\":\"subscribe\""),
contains("\"sessionToken\":\"the token\"")));
}
@Test
public void testCallbackNotifiedOnUnexpectedDisconnect() throws Exception {
LoggingCallbacks callbacks = new LoggingCallbacks();
parseLiveQueryClient.registerListener(callbacks);
callbacks.transcript.assertNoEventsSoFar();
// Unexpected close from the server:
webSocketClientCallback.onClose();
callbacks.transcript.assertEventsSoFar("onLiveQueryClientDisconnected: false");
}
@Test
public void testCallbackNotifiedOnExpectedDisconnect() throws Exception {
LoggingCallbacks callbacks = new LoggingCallbacks();
parseLiveQueryClient.registerListener(callbacks);
callbacks.transcript.assertNoEventsSoFar();
parseLiveQueryClient.disconnect();
verify(webSocketClient, times(1)).close();
callbacks.transcript.assertNoEventsSoFar();
// the client is a mock, so it won't actually invoke the callback automatically
webSocketClientCallback.onClose();
callbacks.transcript.assertEventsSoFar("onLiveQueryClientDisconnected: true");
}
@Test
public void testCallbackNotifiedOnConnect() throws Exception {
LoggingCallbacks callbacks = new LoggingCallbacks();
parseLiveQueryClient.registerListener(callbacks);
callbacks.transcript.assertNoEventsSoFar();
reconnect();
callbacks.transcript.assertEventsSoFar("onLiveQueryClientConnected");
}
@Test
public void testCallbackNotifiedOnSocketError() throws Exception {
LoggingCallbacks callbacks = new LoggingCallbacks();
parseLiveQueryClient.registerListener(callbacks);
callbacks.transcript.assertNoEventsSoFar();
webSocketClientCallback.onError(new IOException("bad things happened"));
callbacks.transcript.assertEventsSoFar("onSocketError: java.io.IOException: bad things happened",
"onLiveQueryClientDisconnected: false");
}
@Test
public void testCallbackNotifiedOnServerError() throws Exception {
LoggingCallbacks callbacks = new LoggingCallbacks();
parseLiveQueryClient.registerListener(callbacks);
callbacks.transcript.assertNoEventsSoFar();
webSocketClientCallback.onMessage(createErrorMessage(1).toString());
callbacks.transcript.assertEventsSoFar("onLiveQueryError: com.parse.LiveQueryException$ServerReportedException: Server reported error; code: 1, error: testError, reconnect: true");
}
private SubscriptionHandling<ParseObject> createSubscription(ParseQuery<ParseObject> parseQuery,
SubscriptionHandling.HandleSubscribeCallback<ParseObject> subscribeMockCallback) throws Exception {
SubscriptionHandling<ParseObject> subscriptionHandling = parseLiveQueryClient.subscribe(parseQuery).handleSubscribe(subscribeMockCallback);
webSocketClientCallback.onMessage(createSubscribedMessage(subscriptionHandling.getRequestId()).toString());
return subscriptionHandling;
}
private void validateSameObject(SubscriptionHandling.HandleEventCallback<ParseObject> eventMockCallback,
ParseQuery<ParseObject> parseQuery,
ParseObject originalParseObject) {
ArgumentCaptor<ParseObject> objectCaptor = ArgumentCaptor.forClass(ParseObject.class);
verify(eventMockCallback, times(1)).onEvent(eq(parseQuery), objectCaptor.capture());
ParseObject newParseObject = objectCaptor.getValue();
assertEquals(originalParseObject.getClassName(), newParseObject.getClassName());
assertEquals(originalParseObject.getObjectId(), newParseObject.getObjectId());
}
private void clearConnection() {
webSocketClient = null;
webSocketClientCallback = null;
}
private void reconnect() {
parseLiveQueryClient.reconnect();
webSocketClientCallback.onOpen();
try {
webSocketClientCallback.onMessage(createConnectedMessage().toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private static JSONObject createConnectedMessage() throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "connected");
return jsonObject;
}
private static JSONObject createSubscribedMessage(int requestId) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "subscribed");
jsonObject.put("clientId", 1);
jsonObject.put("requestId", requestId);
return jsonObject;
}
private static JSONObject createUnsubscribedMessage(int requestId) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "unsubscribed");
jsonObject.put("requestId", requestId);
return jsonObject;
}
private static JSONObject createErrorMessage(int requestId) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "error");
jsonObject.put("requestId", requestId);
jsonObject.put("code", 1);
jsonObject.put("error", "testError");
jsonObject.put("reconnect", true);
return jsonObject;
}
private static JSONObject createObjectCreateMessage(int requestId, ParseObject parseObject) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "create");
jsonObject.put("requestId", requestId);
jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject));
return jsonObject;
}
private static JSONObject createObjectEnterMessage(int requestId, ParseObject parseObject) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "enter");
jsonObject.put("requestId", requestId);
jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject));
return jsonObject;
}
private static JSONObject createObjectUpdateMessage(int requestId, ParseObject parseObject) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "update");
jsonObject.put("requestId", requestId);
jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject));
return jsonObject;
}
private static JSONObject createObjectLeaveMessage(int requestId, ParseObject parseObject) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "leave");
jsonObject.put("requestId", requestId);
jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject));
return jsonObject;
}
private static JSONObject createObjectDeleteMessage(int requestId, ParseObject parseObject) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("op", "delete");
jsonObject.put("requestId", requestId);
jsonObject.put("object", PointerEncoder.get().encodeRelatedObject(parseObject));
return jsonObject;
}
private static class LoggingCallbacks implements ParseLiveQueryClientCallbacks {
final Transcript transcript = new Transcript();
@Override
public void onLiveQueryClientConnected(ParseLiveQueryClient client) {
transcript.add("onLiveQueryClientConnected");
}
@Override
public void onLiveQueryClientDisconnected(ParseLiveQueryClient client, boolean userInitiated) {
transcript.add("onLiveQueryClientDisconnected: " + userInitiated);
}
@Override
public void onLiveQueryError(ParseLiveQueryClient client, LiveQueryException reason) {
transcript.add("onLiveQueryError: " + reason);
}
@Override
public void onSocketError(ParseLiveQueryClient client, Throwable reason) {
transcript.add("onSocketError: " + reason);
}
}
@ParseClassName("MockA")
static class MockClassA extends ParseObject {
}
@ParseClassName("MockB")
static class MockClassB extends ParseObject {
}
}

View File

@ -0,0 +1,131 @@
# Parse LiveQuery Client for Android
[![Build Status][build-status-svg]][build-status-link]
[![Coverage Status][coverage-status-svg]][coverage-status-link]
[![Maven Central][maven-svg]][maven-link]
[![License][license-svg]][license-link]
`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.
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.
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.
## Setup Server
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.
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).
## Setup Client
Download [the latest JAR][latest] or define in Gradle:
```groovy
dependencies {
compile 'com.parse:parse-livequery-android:1.0.4'
}
```
Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap].
## Use Client
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:
```java
// Parse.initialize should be called first
ParseLiveQueryClient parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient();
```
### Creating Live Queries
Live querying depends on creating a subscription to a `ParseQuery`:
```java
ParseQuery<Message> parseQuery = ParseQuery.getQuery(Message.class);
SubscriptionHandling<ParseObject> subscriptionHandling = parseLiveQueryClient.subscribe(parseQuery)
```
Once you've subscribed to a query, you can `handle` events on them, like so:
```java
subscriptionHandling.handleEvents(new SubscriptionHandling.HandleEventsCallback<ParseObject>() {
@Override
public void onEvents(ParseQuery<ParseObject> query, SubscriptionHandling.Event event, ParseObject object) {
// HANDLING all events
}
})
```
You can also handle a single type of event, if that's all you're interested in:
```java
subscriptionHandling.handleEvent(SubscriptionHandling.Event.CREATE, new SubscriptionHandling.HandleEventCallback<ParseObject>() {
@Override
public void onEvent(ParseQuery<ParseObject> query, ParseObject object) {
// HANDLING create event
}
})
```
Handling errors is and other events is similar, take a look at the `SubscriptionHandling` class for more information.
## Advanced Usage
If you wish to pass in your own OkHttpClient instance for troubleshooting or custom configs, you can instantiate the client as follows:
```java
ParseLiveQueryClient parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(new OkHttp3SocketClientFactory(new OkHttpClient()));
```
The URL is determined by the Parse initialization, but you can override by specifying a `URI` object:
```java
ParseLiveQueryClient parseLiveQueryClient = ParseLiveQueryClient.Factory.getClient(new URI("wss://myparseinstance.com"));
```
Note: The expected protocol for URI is `ws` instead of `http`, like in this example: `URI("ws://192.168.0.1:1337/1")`.
## Build commands
Everything can done through the supplied gradle wrapper:
### Compile a JAR
```
./gradlew clean jarRelease
```
Outputs can be found in `ParseLiveQuery/build/libs/`
### Run the Tests
```
./gradlew clean testDebug
```
Results can be found in `ParseLiveQuery/build/reports/`
### Get Code Coverage Reports
```
./gradlew clean jacocoTestReport
```
Results can be found in `ParseLiveQuery/build/reports/`
## How Do I Contribute?
We want to make contributing to this project as easy and transparent as possible. Please refer to the [Contribution Guidelines](CONTRIBUTING.md).
-----
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.
[parse.com]: https://www.parse.com/products/android
[guide]: https://www.parse.com/docs/android/guide
[blog]: https://blog.parse.com/
[latest]: https://search.maven.org/remote_content?g=com.parse&a=parse-livequery-android&v=LATEST
[snap]: https://oss.sonatype.org/content/repositories/snapshots/
[build-status-svg]: https://img.shields.io/travis/parse-community/ParseLiveQuery-Android/master.svg
[build-status-link]: https://travis-ci.org/parse-community/ParseLiveQuery-Android/branches
[coverage-status-svg]: https://img.shields.io/codecov/c/github/parse-community/ParseLiveQuery-Android/master.svg
[coverage-status-link]: https://codecov.io/github/parse-community/ParseLiveQuery-Android?branch=master
[maven-svg]: https://maven-badges.herokuapp.com/maven-central/com.parse/parse-livequery-android/badge.svg?style=flat
[maven-link]: https://maven-badges.herokuapp.com/maven-central/com.parse/parse-livequery-android
[license-svg]: https://img.shields.io/badge/license-BSD-lightgrey.svg
[license-link]: https://github.com/parse-community/ParseLiveQuery-Android/blob/master/LICENSE

View File

@ -0,0 +1,218 @@
This project contains portions of third party software provided under the following terms:
Apache Commons IO
Copyright 2002-2014 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
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.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-----
Guava
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-----
Android Open Source Project
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@ -0,0 +1,27 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
}
}
plugins {
id "com.jfrog.bintray" version "1.7.3"
}
allprojects {
repositories {
jcenter()
}
}
ext {
compileSdkVersion = 25
buildToolsVersion = "25.0.2"
minSdkVersion = 9
targetSdkVersion = 25
}

View File

@ -0,0 +1,6 @@
#Thu Mar 23 00:03:48 PDT 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

164
ExternalLibs/ParseLiveQuery-Android/gradlew vendored Executable file
View File

@ -0,0 +1,164 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,19 @@
#!/bin/bash
# Publishes SNAPSHOTs
REPO_SLUG=parse-community/ParseLiveQuery-Android
BRANCH=master
set -e
if [ "$TRAVIS_REPO_SLUG" != "$REPO_SLUG" ]; then
echo "Skipping publishing SNAPSHOT: wrong repository. Expected '$REPO_SLUG' but was '$TRAVIS_REPO_SLUG'"
elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
echo "Skipping publishing SNAPSHOT: was PR"
elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then
echo "Skipping publishing SNAPSHOT: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'"
else
echo "Publishing SNAPSHOT..."
./gradlew uploadArchives
echo "SNAPSHOT published!"
fi

View File

@ -0,0 +1 @@
include ':ParseLiveQuery'