Search in sources :

Example 1 with Task

use of com.parse.boltsinternal.Task in project Parse-SDK-Android by ParsePlatform.

the class OfflineQueryLogic method createOrMatcher.

/**
 * Handles $or queries.
 */
private <T extends ParseObject> ConstraintMatcher<T> createOrMatcher(ParseUser user, ArrayList<QueryConstraints> queries) {
    // Make a list of all the matchers to OR together.
    final ArrayList<ConstraintMatcher<T>> matchers = new ArrayList<>();
    for (QueryConstraints constraints : queries) {
        ConstraintMatcher<T> matcher = createMatcher(user, constraints);
        matchers.add(matcher);
    }
    /*
         * Now OR together the constraints for each query.
         */
    return new ConstraintMatcher<T>(user) {

        @Override
        public Task<Boolean> matchesAsync(final T object, final ParseSQLiteDatabase db) {
            Task<Boolean> task = Task.forResult(false);
            for (final ConstraintMatcher<T> matcher : matchers) {
                task = task.onSuccessTask(task1 -> {
                    if (task1.getResult()) {
                        return task1;
                    }
                    return matcher.matchesAsync(object, db);
                });
            }
            return task;
        }
    };
}
Also used : Date(java.util.Date) Collection(java.util.Collection) RelationConstraint(com.parse.ParseQuery.RelationConstraint) Set(java.util.Set) HashMap(java.util.HashMap) KeyConstraints(com.parse.ParseQuery.KeyConstraints) ArrayList(java.util.ArrayList) List(java.util.List) JSONException(org.json.JSONException) QueryConstraints(com.parse.ParseQuery.QueryConstraints) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) Pattern(java.util.regex.Pattern) Task(com.parse.boltsinternal.Task) Collections(java.util.Collections) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) QueryConstraints(com.parse.ParseQuery.QueryConstraints)

Example 2 with Task

use of com.parse.boltsinternal.Task in project Parse-SDK-Android by ParsePlatform.

the class OfflineQueryLogic method fetchIncludeAsync.

/**
 * Makes sure that the object specified by path, relative to container, is fetched.
 */
private static Task<Void> fetchIncludeAsync(final OfflineStore store, final Object container, final String path, final ParseSQLiteDatabase db) {
    // If there's no object to include, that's fine.
    if (container == null) {
        return Task.forResult(null);
    }
    // If the container is a list or array, fetch all the sub-items.
    if (container instanceof Collection) {
        Collection<?> collection = (Collection<?>) container;
        // We do the fetches in series because it makes it easier to fail on the first error.
        Task<Void> task = Task.forResult(null);
        for (final Object item : collection) {
            task = task.onSuccessTask(task1 -> fetchIncludeAsync(store, item, path, db));
        }
        return task;
    } else if (container instanceof JSONArray) {
        final JSONArray array = (JSONArray) container;
        // We do the fetches in series because it makes it easier to fail on the first error.
        Task<Void> task = Task.forResult(null);
        for (int i = 0; i < array.length(); ++i) {
            final int index = i;
            task = task.onSuccessTask(task12 -> fetchIncludeAsync(store, array.get(index), path, db));
        }
        return task;
    }
    // If we've reached the end of the path, then actually do the fetch.
    if (path == null) {
        if (JSONObject.NULL.equals(container)) {
            // throwing an exception.
            return Task.forResult(null);
        } else if (container instanceof ParseObject) {
            ParseObject object = (ParseObject) container;
            return store.fetchLocallyAsync(object, db).makeVoid();
        } else {
            return Task.forError(new ParseException(ParseException.INVALID_NESTED_KEY, "include is invalid for non-ParseObjects"));
        }
    }
    // Descend into the container and try again.
    String[] parts = path.split("\\.", 2);
    final String key = parts[0];
    final String rest = (parts.length > 1 ? parts[1] : null);
    // Make sure the container is fetched.
    return Task.<Void>forResult(null).continueWithTask(task -> {
        if (container instanceof ParseObject) {
            // Make sure this object is fetched before descending into it.
            return fetchIncludeAsync(store, container, null, db).onSuccess(task13 -> ((ParseObject) container).get(key));
        } else if (container instanceof Map) {
            return Task.forResult(((Map) container).get(key));
        } else if (container instanceof JSONObject) {
            return Task.forResult(((JSONObject) container).opt(key));
        } else if (JSONObject.NULL.equals(container)) {
            // throwing an exception.
            return null;
        } else {
            return Task.forError(new IllegalStateException("include is invalid"));
        }
    }).onSuccessTask(task -> fetchIncludeAsync(store, task.getResult(), rest, db));
}
Also used : Date(java.util.Date) Collection(java.util.Collection) RelationConstraint(com.parse.ParseQuery.RelationConstraint) Set(java.util.Set) HashMap(java.util.HashMap) KeyConstraints(com.parse.ParseQuery.KeyConstraints) ArrayList(java.util.ArrayList) List(java.util.List) JSONException(org.json.JSONException) QueryConstraints(com.parse.ParseQuery.QueryConstraints) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) Pattern(java.util.regex.Pattern) Task(com.parse.boltsinternal.Task) Collections(java.util.Collections) JSONArray(org.json.JSONArray) Task(com.parse.boltsinternal.Task) JSONArray(org.json.JSONArray) JSONObject(org.json.JSONObject) Collection(java.util.Collection) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with Task

use of com.parse.boltsinternal.Task in project Parse-SDK-Android by ParsePlatform.

the class ParseFileTest method testTaskQueuedMethods.

// endregion
@Test
public void testTaskQueuedMethods() throws Exception {
    ParseFile.State state = new ParseFile.State.Builder().build();
    File cachedFile = temporaryFolder.newFile("temp");
    ParseFileController controller = mock(ParseFileController.class);
    when(controller.saveAsync(any(ParseFile.State.class), any(byte[].class), nullable(String.class), nullable(ProgressCallback.class), nullable(Task.class))).thenReturn(Task.forResult(state));
    when(controller.saveAsync(any(ParseFile.State.class), nullable(File.class), nullable(String.class), nullable(ProgressCallback.class), nullable(Task.class))).thenReturn(Task.forResult(state));
    when(controller.fetchAsync(any(ParseFile.State.class), nullable(String.class), nullable(ProgressCallback.class), nullable(Task.class))).thenReturn(Task.forResult(cachedFile));
    ParseCorePlugins.getInstance().registerFileController(controller);
    ParseFile file = new ParseFile(state);
    TaskQueueTestHelper queueHelper = new TaskQueueTestHelper(file.taskQueue);
    queueHelper.enqueue();
    Task<Void> saveTaskA = file.saveAsync(null, null, null);
    queueHelper.enqueue();
    Task<byte[]> getDataTaskA = file.getDataInBackground();
    queueHelper.enqueue();
    Task<Void> saveTaskB = file.saveAsync(null, null, null);
    queueHelper.enqueue();
    Task<byte[]> getDataTaskB = file.getDataInBackground();
    Thread.sleep(50);
    assertFalse(saveTaskA.isCompleted());
    queueHelper.dequeue();
    ParseTaskUtils.wait(saveTaskA);
    Thread.sleep(50);
    assertFalse(getDataTaskA.isCompleted());
    queueHelper.dequeue();
    ParseTaskUtils.wait(getDataTaskA);
    Thread.sleep(50);
    assertFalse(saveTaskB.isCompleted());
    queueHelper.dequeue();
    ParseTaskUtils.wait(saveTaskB);
    Thread.sleep(50);
    assertFalse(getDataTaskB.isCompleted());
    queueHelper.dequeue();
    ParseTaskUtils.wait(getDataTaskB);
}
Also used : Task(com.parse.boltsinternal.Task) File(java.io.File) Test(org.junit.Test)

Example 4 with Task

use of com.parse.boltsinternal.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(com.parse.boltsinternal.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 5 with Task

use of com.parse.boltsinternal.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(com.parse.boltsinternal.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)

Aggregations

Task (com.parse.boltsinternal.Task)24 ArrayList (java.util.ArrayList)15 JSONObject (org.json.JSONObject)15 Continuation (com.parse.boltsinternal.Continuation)11 TaskCompletionSource (com.parse.boltsinternal.TaskCompletionSource)11 HashMap (java.util.HashMap)11 List (java.util.List)11 JSONException (org.json.JSONException)11 Map (java.util.Map)9 Capture (com.parse.boltsinternal.Capture)8 ContentValues (android.content.ContentValues)7 Context (android.content.Context)7 Cursor (android.database.Cursor)7 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)7 Test (org.junit.Test)7 Arrays (java.util.Arrays)6 Set (java.util.Set)6 JSONArray (org.json.JSONArray)6 TextUtils (android.text.TextUtils)5 Pair (android.util.Pair)5