public Task<Integer> pendingCountAsync() { final TaskCompletionSource<Integer> tcs = new TaskCompletionSource<>(); taskQueue.enqueue(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> toAwait) { return pendingCountAsync(toAwait).continueWithTask(new Continuation<Integer, Task<Void>>() { @Override public Task<Void> then(Task<Integer> task) { int count = task.getResult(); tcs.setResult(count); return Task.forResult(null); } }); } }); return tcs.getTask(); }
@Override public Task<JSONObject> then(Task<JSONObject> task) { synchronized (taskQueueSyncLock) { pendingEventuallyTasks.remove(uuid); uuidToOperationSet.remove(uuid); uuidToEventuallyPin.remove(uuid); } Exception error = task.getError(); if (error != null) { tcs.trySetError(error); } else if (task.isCancelled()) { tcs.trySetCancelled(); } else { tcs.trySetResult(task.getResult()); } return tcs.getTask(); } });
@Override public void resume() { // Reset waitForConnectionAsync. if (isConnected()) { connectionTaskCompletionSource.trySetResult(null); connectionTaskCompletionSource = new TaskCompletionSource<>(); connectionTaskCompletionSource.trySetResult(null); } else { connectionTaskCompletionSource = new TaskCompletionSource<>(); } populateQueueAsync(); }
@Test public void testGetAsyncWithNoInstallationRaceCondition() throws ParseException { // Mock installationId InstallationId installationId = mock(InstallationId.class); when(installationId.get()).thenReturn("testInstallationId"); //noinspection unchecked ParseObjectStore<ParseInstallation> store = mock(ParseObjectStore.class); TaskCompletionSource<ParseInstallation> tcs = new TaskCompletionSource(); when(store.getAsync()).thenReturn(tcs.getTask()); // Create test controller CachedCurrentInstallationController controller = new CachedCurrentInstallationController(store, installationId); Task<ParseInstallation> taskA = controller.getAsync(); Task<ParseInstallation> taskB = controller.getAsync(); tcs.setResult(null); ParseInstallation installationA = ParseTaskUtils.wait(taskA); ParseInstallation installationB = ParseTaskUtils.wait(taskB); verify(store, times(1)).getAsync(); assertSame(controller.currentInstallation, installationA); assertSame(controller.currentInstallation, installationB); // Make sure device info is updated assertEquals("testInstallationId", installationA.getInstallationId()); assertEquals("android", installationA.get(KEY_DEVICE_TYPE)); }
final T object, final ParseSQLiteDatabase db) { final TaskCompletionSource<T> tcs = new TaskCompletionSource<>(); Task<String> uuidTask; fetchedObjects.put(object, (Task<ParseObject>) tcs.getTask()); tcs.setError(new IllegalStateException("This object must have already been " + "fetched from the local datastore, but isn't marked as fetched.")); synchronized (lock) { return tcs.getTask();
private Task<T> getFirstAsync(final State<T> state) { final TaskCompletionSource<Void> tcs = new TaskCompletionSource<>(); return perform(new Callable<Task<T>>() { @Override public Task<T> call() { return getUserAsync(state).onSuccessTask(new Continuation<ParseUser, Task<T>>() { @Override public Task<T> then(Task<ParseUser> task) { final ParseUser user = task.getResult(); return getFirstAsync(state, user, tcs.getTask()); } }); } }, tcs); }
@Test public void testMultipleQueriesWithInflightChanges() throws ParseException { Parse.enableLocalDatastore(null); TestQueryController controller = new TestQueryController(); TaskCompletionSource<Void> tcs = new TaskCompletionSource<>(); controller.await(tcs.getTask()); ParseQuery<ParseObject> query = ParseQuery.getQuery("TestObject"); query.setUser(new ParseUser()); ParseCorePlugins.getInstance().registerQueryController(controller); List<Task<Void>> tasks = Arrays.asList( query.fromNetwork().findInBackground().makeVoid(), query.fromLocalDatastore().findInBackground().makeVoid(), query.setLimit(10).findInBackground().makeVoid(), query.whereEqualTo("key", "value").countInBackground().makeVoid()); assertTrue(query.isRunning()); tcs.trySetResult(null); ParseTaskUtils.wait(Task.whenAll(tasks)); assertFalse(query.isRunning()); }
@Override public Task<Integer> readRssiAsync() { TaskCompletionSource<Integer> source= new TaskCompletionSource<>(); source.trySetError(new UnsupportedOperationException("Reading rssi not supported in JUnit tests")); return source.getTask(); }
@Override public Void then(Task<Void> task) { // This will signal that the UUID does represent a row in the database. tcs.setResult(newUUID); return null; } });
tcs = tcss.get(i); if (task.isFaulted()) { tcs.setError(task.getError()); } else { tcs.setCancelled(); tcs.setError(new IllegalStateException( "Batch command result count expected: " + batchSize + " but was: " + resultLength)); tcs.setResult(success); } else if (result.has("error")) { JSONObject error = result.getJSONObject("error"); tcs.setError(new ParseException(error.getInt("code"), error.getString("error")));
private Task<Void> waitForConnectionAsync() { synchronized (connectionLock) { return connectionTaskCompletionSource.getTask(); } }
@Override public void pause() { synchronized (connectionLock) { // Error out tasks waiting on waitForConnectionAsync. connectionTaskCompletionSource.trySetError(new PauseException()); connectionTaskCompletionSource = new TaskCompletionSource<>(); connectionTaskCompletionSource.trySetError(new PauseException()); } synchronized (taskQueueSyncLock) { for (String key : pendingEventuallyTasks.keySet()) { // Error out tasks waiting on waitForOperationSetAndEventuallyPin. pendingEventuallyTasks.get(key).trySetError(new PauseException()); } pendingEventuallyTasks.clear(); uuidToOperationSet.clear(); uuidToEventuallyPin.clear(); } try { ParseTaskUtils.wait(whenAll(Arrays.asList(taskQueue, operationSetTaskQueue))); } catch (ParseException e) { throw new IllegalStateException(e); } }
@Override public Task<JSONObject> then(Task<JSONObject> task) { String localId = command.getLocalId(); Exception error = task.getError(); if (error != null) { if (error instanceof ParseException && ((ParseException) error).getCode() == ParseException.CONNECTION_FAILED) { // do nothing } else { if (tcs != null) { tcs.setError(error); } } return task; } JSONObject json = task.getResult(); if (tcs != null) { tcs.setResult(json); } else if (localId != null) { // If this command created a new objectId, add it to the map. String objectId = json.optString("objectId", null); if (objectId != null) { ParseCorePlugins.getInstance() .getLocalIdManager().setObjectId(localId, objectId); } } return task; } });
@Override public void done(List<T> results, ParseException e) { boolean isCancelled = ct != null && ct.isCancellationRequested(); if (!isCancelled && e == null) { onPage(query, page, results); } boolean isCacheThenNetwork = false; try { ParseQuery.CachePolicy policy = getQuery().getCachePolicy(); isCacheThenNetwork = policy == ParseQuery.CachePolicy.CACHE_THEN_NETWORK; } catch (IllegalStateException ex) { // do nothing, LDS is enabled and we can't use CACHE_THEN_NETWORK } if (!isCacheThenNetwork || callbacks.incrementAndGet() >= 2) { if (isCancelled) { tcs.trySetCancelled(); } else { tcs.trySetResult(results); } } callback.done(results, e); } });
@Override public Task<TResult> then(Task<TResult> task) { tcs.trySetResult(null); // release currentTasks.remove(tcs); return task; } });
/** * Cancels the operations for this {@code ParseFile} if they are still in the task queue. However, * if a network request has already been started for an operation, the network request will not * be canceled. */ //TODO (grantland): Deprecate and replace with CancellationToken public void cancel() { Set<TaskCompletionSource<?>> tasks = new HashSet<>(currentTasks); for (TaskCompletionSource<?> tcs : tasks) { tcs.trySetCancelled(); } currentTasks.removeAll(tasks); }
@Override public void run() { tcs.trySetError(new ParseException(ParseException.TIMEOUT, "Location fetch timed out.")); manager.removeUpdates(listener); } }, timeout, TimeUnit.MILLISECONDS));
@Override public Void then(final Task<T> task) { if (task.isCancelled() && !reportCancellation) { tcs.setCancelled(); return null; } ParseExecutors.main().execute(new Runnable() { @Override public void run() { try { Exception error = task.getError(); if (error != null && !(error instanceof ParseException)) { error = new ParseException(error); } callback.done(task.getResult(), (ParseException) error); } finally { if (task.isCancelled()) { tcs.setCancelled(); } else if (task.isFaulted()) { tcs.setError(task.getError()); } else { tcs.setResult(task.getResult()); } } } }); return null; } });
@Override public void disconnected() { rollbackTimestamps.putAll(lastTimestamp); TaskCompletionSource<Void> taskSource = downloadTask.getAndSet(null); if (taskSource != null) { taskSource.setError(new RuntimeException("Lost connection while downloading log data")); } }