Search in sources :

Example 11 with Task

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

the class ParseSQLiteDatabase method queryAsync.

/**
 * Runs a SELECT query.
 *
 * @see SQLiteDatabase#query
 */
public Task<Cursor> queryAsync(final String table, final String[] select, final String where, final String[] args) {
    synchronized (currentLock) {
        Task<Cursor> task = current.onSuccess(task13 -> db.query(table, select, where, args, null, null, null), dbExecutor).onSuccess(task12 -> {
            Cursor cursor = task12.getResult();
            /* Ensure the cursor window is filled on the dbExecutor thread. We need to do this because
                                         * the cursor cannot be filled from a different thread than it was created on.
                                         */
            cursor.getCount();
            return cursor;
        }, dbExecutor);
        current = task.makeVoid();
        return task.continueWithTask(task1 -> {
            // We want to jump off the dbExecutor
            return task1;
        }, Task.BACKGROUND_EXECUTOR);
    }
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) SQLiteOpenHelper(android.database.sqlite.SQLiteOpenHelper) ContentValues(android.content.ContentValues) Task(com.parse.boltsinternal.Task) TaskCompletionSource(com.parse.boltsinternal.TaskCompletionSource) ExecutorService(java.util.concurrent.ExecutorService) Executors(java.util.concurrent.Executors) Cursor(android.database.Cursor) Cursor(android.database.Cursor)

Example 12 with Task

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

the class NetworkObjectController method saveAllAsync.

@Override
public List<Task<ParseObject.State>> saveAllAsync(List<ParseObject.State> states, List<ParseOperationSet> operationsList, String sessionToken, List<ParseDecoder> decoders) {
    int batchSize = states.size();
    List<ParseRESTObjectCommand> commands = new ArrayList<>(batchSize);
    ParseEncoder encoder = PointerEncoder.get();
    for (int i = 0; i < batchSize; i++) {
        ParseObject.State state = states.get(i);
        ParseOperationSet operations = operationsList.get(i);
        JSONObject objectJSON = coder.encode(state, operations, encoder);
        ParseRESTObjectCommand command = ParseRESTObjectCommand.saveObjectCommand(state, objectJSON, sessionToken);
        commands.add(command);
    }
    final List<Task<JSONObject>> batchTasks = ParseRESTObjectBatchCommand.executeBatch(client, commands, sessionToken);
    final List<Task<ParseObject.State>> tasks = new ArrayList<>(batchSize);
    for (int i = 0; i < batchSize; i++) {
        final ParseObject.State state = states.get(i);
        final ParseDecoder decoder = decoders.get(i);
        tasks.add(batchTasks.get(i).onSuccess(task -> {
            JSONObject result = task.getResult();
            // Copy and clear to create an new empty instance of the
            // same type as `state`
            ParseObject.State.Init<?> builder = state.newBuilder().clear();
            return coder.decode(builder, result, decoder).isComplete(false).build();
        }));
    }
    return tasks;
}
Also used : List(java.util.List) JSONObject(org.json.JSONObject) Task(com.parse.boltsinternal.Task) ArrayList(java.util.ArrayList) Task(com.parse.boltsinternal.Task) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject)

Example 13 with Task

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

the class ParseUserTest method testSaveEventuallyWhenServerError.

// region testSaveEventuallyWhenServerError
@Test
public void testSaveEventuallyWhenServerError() throws Exception {
    Shadows.shadowOf(RuntimeEnvironment.application).grantPermissions(Manifest.permission.ACCESS_NETWORK_STATE);
    Parse.Configuration configuration = new Parse.Configuration.Builder(RuntimeEnvironment.application).applicationId(BuildConfig.LIBRARY_PACKAGE_NAME).server("https://api.parse.com/1").enableLocalDataStore().build();
    ParsePlugins plugins = ParseTestUtils.mockParsePlugins(configuration);
    JSONObject mockResponse = new JSONObject();
    mockResponse.put("objectId", "objectId");
    mockResponse.put("email", "email@parse.com");
    mockResponse.put("username", "username");
    mockResponse.put("sessionToken", "r:sessionToken");
    mockResponse.put("createdAt", ParseDateFormat.getInstance().format(new Date(1000)));
    mockResponse.put("updatedAt", ParseDateFormat.getInstance().format(new Date(2000)));
    ParseHttpClient restClient = ParseTestUtils.mockParseHttpClientWithResponse(mockResponse, 200, "OK");
    when(plugins.restClient()).thenReturn(restClient);
    Parse.initialize(configuration, plugins);
    ParseUser user = ParseUser.logIn("username", "password");
    assertFalse(user.isDirty());
    user.put("field", "data");
    assertTrue(user.isDirty());
    mockResponse = new JSONObject();
    mockResponse.put("updatedAt", ParseDateFormat.getInstance().format(new Date(3000)));
    ParseTestUtils.updateMockParseHttpClientWithResponse(restClient, mockResponse, 200, "OK");
    final CountDownLatch saveCountDown1 = new CountDownLatch(1);
    final Capture<Exception> exceptionCapture = new Capture<>();
    user.saveInBackground().continueWith((Continuation<Void, Void>) task -> {
        exceptionCapture.set(task.getError());
        saveCountDown1.countDown();
        return null;
    });
    assertTrue(saveCountDown1.await(5, TimeUnit.SECONDS));
    assertNull(exceptionCapture.get());
    assertFalse(user.isDirty());
    user.put("field", "other data");
    assertTrue(user.isDirty());
    mockResponse = new JSONObject();
    mockResponse.put("error", "Save is not allowed");
    mockResponse.put("code", 141);
    ParseTestUtils.updateMockParseHttpClientWithResponse(restClient, mockResponse, 400, "Bad Request");
    final CountDownLatch saveEventuallyCountDown = new CountDownLatch(1);
    user.saveEventually().continueWith((Continuation<Void, Void>) task -> {
        exceptionCapture.set(task.getError());
        saveEventuallyCountDown.countDown();
        return null;
    });
    assertTrue(saveEventuallyCountDown.await(5, TimeUnit.SECONDS));
    assertTrue(exceptionCapture.get() instanceof ParseException);
    assertEquals(ParseException.SCRIPT_ERROR, ((ParseException) exceptionCapture.get()).getCode());
    assertEquals("Save is not allowed", exceptionCapture.get().getMessage());
    assertTrue(user.isDirty());
    // Simulate reboot
    Parse.destroy();
    Parse.initialize(configuration, plugins);
    user = ParseUser.getCurrentUser();
    assertTrue(user.isDirty());
    assertEquals("other data", user.get("field"));
    user.put("field", "another data");
    mockResponse = new JSONObject();
    mockResponse.put("updatedAt", ParseDateFormat.getInstance().format(new Date(4000)));
    ParseTestUtils.updateMockParseHttpClientWithResponse(restClient, mockResponse, 200, "OK");
    final CountDownLatch saveCountDown2 = new CountDownLatch(1);
    user.saveInBackground().continueWith((Continuation<Void, Void>) task -> {
        exceptionCapture.set(task.getError());
        saveCountDown2.countDown();
        return null;
    });
    assertTrue(saveCountDown2.await(5, TimeUnit.SECONDS));
    assertNull(exceptionCapture.get());
    assertFalse(user.isDirty());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Shadows(org.robolectric.Shadows) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ArgumentMatchers.nullable(org.mockito.ArgumentMatchers.nullable) Date(java.util.Date) Assert.assertNotSame(org.junit.Assert.assertNotSame) RunWith(org.junit.runner.RunWith) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) HashMap(java.util.HashMap) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Mockito.spy(org.mockito.Mockito.spy) Parcel(android.os.Parcel) ShadowLooper.shadowMainLooper(org.robolectric.shadows.ShadowLooper.shadowMainLooper) Assert.assertSame(org.junit.Assert.assertSame) Manifest(android.Manifest) Capture(com.parse.boltsinternal.Capture) Continuation(com.parse.boltsinternal.Continuation) JSONObject(org.json.JSONObject) ArgumentCaptor(org.mockito.ArgumentCaptor) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) After(org.junit.After) Mockito.doReturn(org.mockito.Mockito.doReturn) ExpectedException(org.junit.rules.ExpectedException) Before(org.junit.Before) PAUSED(org.robolectric.annotation.LooperMode.Mode.PAUSED) Semaphore(java.util.concurrent.Semaphore) Assert.assertTrue(org.junit.Assert.assertTrue) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) LooperMode(org.robolectric.annotation.LooperMode) Mockito.when(org.mockito.Mockito.when) RuntimeEnvironment(org.robolectric.RuntimeEnvironment) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito.never(org.mockito.Mockito.never) Assert.assertNull(org.junit.Assert.assertNull) Rule(org.junit.Rule) Assert.assertFalse(org.junit.Assert.assertFalse) Task(com.parse.boltsinternal.Task) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) CountDownLatch(java.util.concurrent.CountDownLatch) Date(java.util.Date) ExpectedException(org.junit.rules.ExpectedException) Capture(com.parse.boltsinternal.Capture) JSONObject(org.json.JSONObject) Test(org.junit.Test)

Example 14 with Task

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

the class ParseObjectTest method testParcelWhileSaving.

@Test
public void testParcelWhileSaving() throws Exception {
    mockCurrentUserController();
    TaskCompletionSource<ParseObject.State> tcs = mockObjectControllerForSave();
    // Create multiple ParseOperationSets
    List<Task<Void>> tasks = new ArrayList<>();
    ParseObject object = new ParseObject("TestObject");
    object.setObjectId("id");
    object.put("key", "value");
    object.put("number", 5);
    tasks.add(object.saveInBackground());
    object.put("key", "newValue");
    object.increment("number", 6);
    tasks.add(object.saveInBackground());
    object.increment("number", -1);
    tasks.add(object.saveInBackground());
    // Ensure Log.w is called...
    assertTrue(object.hasOutstandingOperations());
    Parcel parcel = Parcel.obtain();
    object.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    ParseObject other = ParseObject.CREATOR.createFromParcel(parcel);
    assertTrue(other.isDirty("key"));
    assertTrue(other.isDirty("number"));
    assertEquals(other.getString("key"), "newValue");
    assertEquals(other.getNumber("number"), 10);
    // By design, when LDS is off, we assume that old operations failed even if
    // they are still running on the old instance.
    assertFalse(other.hasOutstandingOperations());
    // Force finish save operations on the old instance.
    tcs.setResult(null);
    ParseTaskUtils.wait(Task.whenAll(tasks));
}
Also used : Task(com.parse.boltsinternal.Task) Parcel(android.os.Parcel) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 15 with Task

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

the class ParseTaskUtilsTest method testWaitForTaskWrapsAggregateExceptionAsParseException.

/**
 * Verifies {@link AggregateException} gets wrapped with {@link ParseException} when thrown from
 * {@link com.parse.ParseTaskUtils#wait(Task)}.
 */
@Test
public void testWaitForTaskWrapsAggregateExceptionAsParseException() {
    final Exception error = new RuntimeException("This task failed.");
    final ArrayList<Task<Void>> tasks = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        final int number = i;
        Task<Void> task = Task.callInBackground(() -> {
            Thread.sleep((long) (Math.random() * 100));
            if (number == 10 || number == 11) {
                throw error;
            }
            return null;
        });
        tasks.add(task);
    }
    try {
        ParseTaskUtils.wait(Task.whenAll(tasks));
    } catch (ParseException e) {
        assertTrue(e.getCause() instanceof AggregateException);
    }
}
Also used : Task(com.parse.boltsinternal.Task) ArrayList(java.util.ArrayList) AggregateException(com.parse.boltsinternal.AggregateException) AggregateException(com.parse.boltsinternal.AggregateException) 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