Search in sources :

Example 6 with Task

use of bolts.Task in project Parse-SDK-Android by ParsePlatform.

the class ParsePinningEventuallyQueue method process.

/**
   * Invokes the eventually operation.
   */
private Task<JSONObject> process(final EventuallyPin eventuallyPin, final ParseOperationSet operationSet) {
    return waitForConnectionAsync().onSuccessTask(new Continuation<Void, Task<JSONObject>>() {

        @Override
        public Task<JSONObject> then(Task<Void> task) throws Exception {
            final int type = eventuallyPin.getType();
            final ParseObject object = eventuallyPin.getObject();
            String sessionToken = eventuallyPin.getSessionToken();
            Task<JSONObject> executeTask;
            if (type == EventuallyPin.TYPE_SAVE) {
                executeTask = object.saveAsync(httpClient, operationSet, sessionToken);
            } else if (type == EventuallyPin.TYPE_DELETE) {
                executeTask = object.deleteAsync(sessionToken).cast();
            } else {
                // else if (type == EventuallyPin.TYPE_COMMAND) {
                ParseRESTCommand command = eventuallyPin.getCommand();
                if (command == null) {
                    executeTask = Task.forResult(null);
                    notifyTestHelper(TestHelper.COMMAND_OLD_FORMAT_DISCARDED);
                } else {
                    executeTask = command.executeAsync(httpClient);
                }
            }
            return executeTask.continueWithTask(new Continuation<JSONObject, Task<JSONObject>>() {

                @Override
                public Task<JSONObject> then(final Task<JSONObject> executeTask) throws Exception {
                    Exception error = executeTask.getError();
                    if (error != null) {
                        if (error instanceof ParseException && ((ParseException) error).getCode() == ParseException.CONNECTION_FAILED) {
                            // We did our retry logic in ParseRequest, so just mark as not connected
                            // and move on.
                            setConnected(false);
                            notifyTestHelper(TestHelper.NETWORK_DOWN);
                            return process(eventuallyPin, operationSet);
                        }
                    }
                    // since this EventuallyPin is still in eventuallyPinUUIDQueue.
                    return eventuallyPin.unpinInBackground(EventuallyPin.PIN_NAME).continueWithTask(new Continuation<Void, Task<Void>>() {

                        @Override
                        public Task<Void> then(Task<Void> task) throws Exception {
                            JSONObject result = executeTask.getResult();
                            if (type == EventuallyPin.TYPE_SAVE) {
                                return object.handleSaveEventuallyResultAsync(result, operationSet);
                            } else if (type == EventuallyPin.TYPE_DELETE) {
                                if (executeTask.isFaulted()) {
                                    return task;
                                } else {
                                    return object.handleDeleteEventuallyResultAsync();
                                }
                            } else {
                                // else if (type == EventuallyPin.TYPE_COMMAND) {
                                return task;
                            }
                        }
                    }).continueWithTask(new Continuation<Void, Task<JSONObject>>() {

                        @Override
                        public Task<JSONObject> then(Task<Void> task) throws Exception {
                            return executeTask;
                        }
                    });
                }
            });
        }
    });
}
Also used : Task(bolts.Task) Continuation(bolts.Continuation) JSONObject(org.json.JSONObject)

Example 7 with Task

use of bolts.Task in project Parse-SDK-Android by ParsePlatform.

the class NetworkObjectControllerTest method testDeleteAllAsync.

//endregion
//region testDeleteAsync
@Test
public void testDeleteAllAsync() throws Exception {
    // Make individual responses
    JSONObject objectResponse = new JSONObject();
    objectResponse.put("success", new JSONObject());
    JSONObject objectResponseAgain = new JSONObject();
    JSONObject objectDeleteResultAgain = new JSONObject();
    objectDeleteResultAgain.put("code", 101);
    objectDeleteResultAgain.put("error", "Error");
    objectResponseAgain.put("error", objectDeleteResultAgain);
    // Make batch response
    JSONArray mockResponse = new JSONArray();
    mockResponse.put(objectResponse);
    mockResponse.put(objectResponseAgain);
    // Make mock response
    byte[] contentBytes = mockResponse.toString().getBytes();
    ParseHttpResponse response = new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(contentBytes)).setStatusCode(200).setTotalSize(contentBytes.length).setContentType("application/json").build();
    // Mock http client
    ParseHttpClient client = mock(ParseHttpClient.class);
    when(client.execute(any(ParseHttpRequest.class))).thenReturn(response);
    // Make test state, operations and decoder
    List<ParseObject.State> states = new ArrayList<>();
    // Make test state
    ParseObject.State state = new ParseObject.State.Builder("Test").objectId("testObjectId").build();
    states.add(state);
    ParseObject.State stateAgain = new ParseObject.State.Builder("Test").objectId("testObjectIdAgain").build();
    states.add(stateAgain);
    // Test
    NetworkObjectController controller = new NetworkObjectController(client);
    List<Task<Void>> deleteTaskList = controller.deleteAllAsync(states, "sessionToken");
    Task.whenAll(deleteTaskList).waitForCompletion();
    // Verify success result
    assertFalse(deleteTaskList.get(0).isFaulted());
    // Verify error result
    assertTrue(deleteTaskList.get(1).isFaulted());
    assertTrue(deleteTaskList.get(1).getError() instanceof ParseException);
    ParseException parseException = (ParseException) deleteTaskList.get(1).getError();
    assertEquals(101, parseException.getCode());
    assertEquals("Error", parseException.getMessage());
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) Task(bolts.Task) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 8 with Task

use of bolts.Task in project Parse-SDK-Android by ParsePlatform.

the class NetworkObjectControllerTest method testSaveAllAsync.

//endregion
//region testSaveAllAsync
@Test
public void testSaveAllAsync() throws Exception {
    // Make individual responses
    JSONObject objectSaveResult = new JSONObject();
    String createAtStr = "2015-08-09T22:15:13.460Z";
    long createAtLong = ParseDateFormat.getInstance().parse(createAtStr).getTime();
    String updateAtStr = "2015-08-09T22:15:13.497Z";
    long updateAtLong = ParseDateFormat.getInstance().parse(updateAtStr).getTime();
    objectSaveResult.put("createdAt", createAtStr);
    objectSaveResult.put("objectId", "testObjectId");
    objectSaveResult.put("updatedAt", updateAtStr);
    JSONObject objectResponse = new JSONObject();
    objectResponse.put("success", objectSaveResult);
    JSONObject objectResponseAgain = new JSONObject();
    JSONObject objectSaveResultAgain = new JSONObject();
    objectSaveResultAgain.put("code", 101);
    objectSaveResultAgain.put("error", "Error");
    objectResponseAgain.put("error", objectSaveResultAgain);
    // Make batch response
    JSONArray mockResponse = new JSONArray();
    mockResponse.put(objectResponse);
    mockResponse.put(objectResponseAgain);
    // Make mock response
    byte[] contentBytes = mockResponse.toString().getBytes();
    ParseHttpResponse response = new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(contentBytes)).setStatusCode(200).setTotalSize(contentBytes.length).setContentType("application/json").build();
    // Mock http client
    ParseHttpClient client = mock(ParseHttpClient.class);
    when(client.execute(any(ParseHttpRequest.class))).thenReturn(response);
    // Make test state, operations and decoder
    List<ParseObject.State> states = new ArrayList<>();
    List<ParseOperationSet> operationsList = new ArrayList<>();
    List<ParseDecoder> decoders = new ArrayList<>();
    ParseObject object = new ParseObject("Test");
    object.put("key", "value");
    states.add(object.getState());
    operationsList.add(object.startSave());
    decoders.add(ParseDecoder.get());
    ParseObject objectAgain = new ParseObject("Test");
    object.put("keyAgain", "valueAgain");
    states.add(objectAgain.getState());
    operationsList.add(objectAgain.startSave());
    decoders.add(ParseDecoder.get());
    // Test
    NetworkObjectController controller = new NetworkObjectController(client);
    List<Task<ParseObject.State>> saveTaskList = controller.saveAllAsync(states, operationsList, "sessionToken", decoders);
    Task.whenAll(saveTaskList).waitForCompletion();
    // Verify newState
    ParseObject.State newState = saveTaskList.get(0).getResult();
    assertEquals(createAtLong, newState.createdAt());
    assertEquals(updateAtLong, newState.updatedAt());
    assertEquals("testObjectId", newState.objectId());
    assertFalse(newState.isComplete());
    // Verify exception
    assertTrue(saveTaskList.get(1).isFaulted());
    assertTrue(saveTaskList.get(1).getError() instanceof ParseException);
    ParseException parseException = (ParseException) saveTaskList.get(1).getError();
    assertEquals(101, parseException.getCode());
    assertEquals("Error", parseException.getMessage());
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) Task(bolts.Task) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 9 with Task

use of bolts.Task in project Parse-SDK-Android by ParsePlatform.

the class ParseObject method saveEventually.

/**
   * Saves this object to the server at some unspecified time in the future, even if Parse is
   * currently inaccessible. Use this when you may not have a solid network connection, and don't
   * need to know when the save completes. If there is some problem with the object such that it
   * can't be saved, it will be silently discarded. Objects saved with this method will be stored
   * locally in an on-disk cache until they can be delivered to Parse. They will be sent immediately
   * if possible. Otherwise, they will be sent the next time a network connection is available.
   * Objects saved this way will persist even after the app is closed, in which case they will be
   * sent the next time the app is opened. If more than 10MB of data is waiting to be sent,
   * subsequent calls to {@code #saveEventually()} or {@link #deleteEventually()}  will cause old
   * saves to be silently  discarded until the connection can be re-established, and the queued
   * objects can be saved.
   *
   * @return A {@link bolts.Task} that is resolved when the save completes.
   */
public final Task<Void> saveEventually() {
    if (!isDirty()) {
        Parse.getEventuallyQueue().fakeObjectUpdate();
        return Task.forResult(null);
    }
    final ParseOperationSet operationSet;
    final ParseRESTCommand command;
    final Task<JSONObject> runEventuallyTask;
    synchronized (mutex) {
        updateBeforeSave();
        try {
            validateSaveEventually();
        } catch (ParseException e) {
            return Task.forError(e);
        }
        // TODO(klimt): Once we allow multiple saves on an object, this
        // should be collecting dirty children from the estimate based on
        // whatever data is going to be sent by this saveEventually, which
        // won't necessarily be the current estimatedData. We should resolve
        // this when the multiple save code is added.
        List<ParseObject> unsavedChildren = new ArrayList<>();
        collectDirtyChildren(estimatedData, unsavedChildren, null);
        String localId = null;
        if (getObjectId() == null) {
            localId = getOrCreateLocalId();
        }
        operationSet = startSave();
        operationSet.setIsSaveEventually(true);
        //TODO (grantland): Convert to async
        final String sessionToken = ParseUser.getCurrentSessionToken();
        try {
            // See [1]
            command = currentSaveEventuallyCommand(operationSet, PointerOrLocalIdEncoder.get(), sessionToken);
            // TODO: Make this logic make sense once we have deepSaveEventually
            command.setLocalId(localId);
            // Mark the command with a UUID so that we can match it up later.
            command.setOperationSetUUID(operationSet.getUUID());
            // Ensure local ids are retained before saveEventually-ing children
            command.retainLocalIds();
            for (ParseObject object : unsavedChildren) {
                object.saveEventually();
            }
        } catch (ParseException exception) {
            throw new IllegalStateException("Unable to saveEventually.", exception);
        }
    }
    // We cannot modify the taskQueue inside synchronized (mutex).
    ParseEventuallyQueue cache = Parse.getEventuallyQueue();
    runEventuallyTask = cache.enqueueEventuallyAsync(command, ParseObject.this);
    enqueueSaveEventuallyOperationAsync(operationSet);
    // Release the extra retained local ids.
    command.releaseLocalIds();
    Task<Void> handleSaveResultTask;
    if (Parse.isLocalDatastoreEnabled()) {
        // ParsePinningEventuallyQueue calls handleSaveEventuallyResultAsync directly.
        handleSaveResultTask = runEventuallyTask.makeVoid();
    } else {
        handleSaveResultTask = runEventuallyTask.onSuccessTask(new Continuation<JSONObject, Task<Void>>() {

            @Override
            public Task<Void> then(Task<JSONObject> task) throws Exception {
                JSONObject json = task.getResult();
                return handleSaveEventuallyResultAsync(json, operationSet);
            }
        });
    }
    return handleSaveResultTask;
}
Also used : Continuation(bolts.Continuation) Task(bolts.Task) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject)

Example 10 with Task

use of bolts.Task in project Parse-SDK-Android by ParsePlatform.

the class ParseCloudTest method testCallFunctionAsync.

//endregion
//region testCallFunctions
@Test
public void testCallFunctionAsync() throws Exception {
    ParseCloudCodeController controller = mockParseCloudCodeControllerWithResponse("result");
    ParseCorePlugins.getInstance().registerCloudCodeController(controller);
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("key1", Arrays.asList(1, 2, 3));
    parameters.put("key2", "value1");
    Task cloudCodeTask = ParseCloud.callFunctionInBackground("name", parameters);
    ParseTaskUtils.wait(cloudCodeTask);
    verify(controller, times(1)).callFunctionInBackground(eq("name"), eq(parameters), isNull(String.class));
    assertTrue(cloudCodeTask.isCompleted());
    assertNull(cloudCodeTask.getError());
    assertThat(cloudCodeTask.getResult(), instanceOf(String.class));
    assertEquals("result", cloudCodeTask.getResult());
}
Also used : Task(bolts.Task) HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.junit.Test)

Aggregations

Task (bolts.Task)46 JSONObject (org.json.JSONObject)27 Continuation (bolts.Continuation)23 JSONException (org.json.JSONException)20 ArrayList (java.util.ArrayList)15 JSONArray (org.json.JSONArray)14 RCLog (chat.rocket.android.log.RCLog)11 TaskCompletionSource (bolts.TaskCompletionSource)10 List (java.util.List)8 Context (android.content.Context)7 Uri (android.net.Uri)7 RealmHelper (chat.rocket.persistence.realm.RealmHelper)7 CancellationException (java.util.concurrent.CancellationException)7 TextUtils (android.text.TextUtils)6 SyncState (chat.rocket.core.SyncState)6 IOException (java.io.IOException)6 NonNull (android.support.annotation.NonNull)5 Nullable (android.support.annotation.Nullable)5 AggregateException (bolts.AggregateException)5 AppLink (bolts.AppLink)5