bolts.Task.forError()方法的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(15.8k)|赞(0)|评价(0)|浏览(116)

本文整理了Java中bolts.Task.forError()方法的一些代码示例,展示了Task.forError()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Task.forError()方法的具体详情如下:
包路径:bolts.Task
类名称:Task
方法名:forError

Task.forError介绍

[英]Creates a faulted task with the given error.
[中]创建具有给定错误的错误任务。

代码示例

代码示例来源:origin: parse-community/Parse-SDK-Android

@Override
  public Task<Boolean> matchesAsync(T object, ParseSQLiteDatabase db) {
    Object objectValue;
    try {
      objectValue = getValue(object, key);
    } catch (ParseException e) {
      return Task.forError(e);
    }
    return Task.forResult(matchesEqualConstraint(queryConstraintValue, objectValue));
  }
});

代码示例来源:origin: parse-community/Parse-SDK-Android

@Override
  public Task<Boolean> matchesAsync(T object, ParseSQLiteDatabase db) {
    try {
      Object value = getValue(object, key);
      return Task.forResult(matchesStatelessConstraint(operator, constraint, value,
          allKeyConstraints));
    } catch (ParseException e) {
      return Task.forError(e);
    }
  }
};

代码示例来源:origin: parse-community/Parse-SDK-Android

/**
 * Wraps the runnable operation and keeps it in sync with the given tcs, so we know how many
 * operations are running (currentTasks.size()) and can cancel them.
 */
private <TResult> Task<TResult> perform(Callable<Task<TResult>> runnable, final TaskCompletionSource<?> tcs) {
  currentTasks.add(tcs);
  Task<TResult> task;
  try {
    task = runnable.call();
  } catch (Exception e) {
    task = Task.forError(e);
  }
  return task.continueWithTask(new Continuation<TResult, Task<TResult>>() {
    @Override
    public Task<TResult> then(Task<TResult> task) {
      tcs.trySetResult(null); // release
      currentTasks.remove(tcs);
      return task;
    }
  });
}

代码示例来源:origin: parse-community/Parse-SDK-Android

content = new String(ParseIOUtils.toByteArray(responseStream));
} catch (IOException e) {
  return Task.forError(e);
} finally {
  ParseIOUtils.closeQuietly(responseStream);
      return Task.forError(newPermanentException(json.optInt("code"), json.optString("error")));
    } else if (statusCode >= 500) { // 5XX
      return Task.forError(newTemporaryException(json.optInt("code"), json.optString("error")));
    return Task.forError(newTemporaryException("bad json response", e));
return Task.forError(newPermanentException(ParseException.OTHER_CAUSE, content));

代码示例来源:origin: parse-community/Parse-SDK-Android

/**
   * /batch is the only endpoint that doesn't return a JSONObject... It returns a JSONArray, but
   * let's wrap that with a JSONObject {@code { "results": &lt;original response%gt; }}.
   */
  @Override
  protected Task<JSONObject> onResponseAsync(ParseHttpResponse response,
                        ProgressCallback downloadProgressCallback) {
    InputStream responseStream = null;
    String content;
    try {
      responseStream = response.getContent();
      content = new String(ParseIOUtils.toByteArray(responseStream));
    } catch (IOException e) {
      return Task.forError(e);
    } finally {
      ParseIOUtils.closeQuietly(responseStream);
    }

    JSONObject json;
    try {
      JSONArray results = new JSONArray(content);
      json = new JSONObject();
      json.put(KEY_RESULTS, results);
    } catch (JSONException e) {
      return Task.forError(newTemporaryException("bad json response", e));
    }

    return Task.forResult(json);
  }
}

代码示例来源:origin: parse-community/Parse-SDK-Android

private ParseConfigController mockParseConfigControllerWithException(Exception exception) {
  ParseConfigController controller = mock(ParseConfigController.class);
  when(controller.getAsync(anyString()))
      .thenReturn(Task.<ParseConfig>forError(exception));
  return controller;
}

代码示例来源:origin: parse-community/Parse-SDK-Android

private ParseCurrentConfigController mockParseCurrentConfigControllerWithException(
      Exception exception) {
    ParseCurrentConfigController controller = mock(ParseCurrentConfigController.class);
    when(controller.getCurrentConfigAsync())
        .thenReturn(Task.<ParseConfig>forError(exception));
    return controller;
  }
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testGetAsyncWithCurrentUserReadFromDiskFailure() throws Exception {
  ParseObjectStore<ParseUser> store =
      (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class);
  when(store.getAsync()).thenReturn(Task.<ParseUser>forError(new RuntimeException("failure")));
  CachedCurrentUserController controller =
      new CachedCurrentUserController(store);
  ParseUser currentUser = ParseTaskUtils.wait(controller.getAsync(false));
  assertNull(currentUser);
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testDeleteAsyncFailure() throws Exception {
  OfflineStore lds = mock(OfflineStore.class);
  when(lds.unpinAllObjectsAsync(anyString()))
      .thenReturn(Task.<Void>forError(new RuntimeException("failure")));
  Parse.setLocalDatastore(lds);
  @SuppressWarnings("unchecked")
  ParseObjectStore<ParseUser> legacy = mock(ParseObjectStore.class);
  when(legacy.deleteAsync()).thenReturn(Task.<Void>forResult(null));
  OfflineObjectStore<ParseUser> store =
      new OfflineObjectStore<>(ParseUser.class, PIN_NAME, legacy);
  thrown.expect(RuntimeException.class);
  ParseTaskUtils.wait(store.deleteAsync());
  verify(legacy, times(1)).deleteAsync();
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
  public void testFailingFindAllPinned() throws Exception {
    OfflineStore offlineStore = mock(OfflineStore.class);
    Parse.setLocalDatastore(offlineStore);
    when(offlineStore.findFromPinAsync(eq(EventuallyPin.PIN_NAME),
        any(ParseQuery.State.class),
        any(ParseUser.class)))
        .thenReturn(Task.forError(new SQLiteException()));

    ParsePlugins plugins = mock(ParsePlugins.class);
    ParsePlugins.set(plugins);
    when(plugins.restClient()).thenReturn(ParseHttpClient.createClient(null));

    thrown.expect(SQLiteException.class);

    ParseTaskUtils.wait(EventuallyPin.findAllPinned());
  }
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testLogOutAsyncWithDeleteInDiskCurrentUserFailure() throws Exception {
  ParseObjectStore<ParseUser> store =
      (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class);
  when(store.getAsync()).thenReturn(Task.<ParseUser>forResult(null));
  when(store.deleteAsync()).thenReturn(Task.<Void>forError(new RuntimeException("failure")));
  CachedCurrentUserController controller =
      new CachedCurrentUserController(store);
  ParseTaskUtils.wait(controller.logOutAsync());
  // Make sure controller state is correct
  assertNull(controller.currentUser);
  assertFalse(controller.currentUserMatchesDisk);
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testSubscribeInBackgroundFail() throws Exception {
  ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
  ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
  when(controller.subscribeInBackground(anyString())).thenReturn(Task.<Void>forError(exception));
  ParseCorePlugins.getInstance().registerPushChannelsController(controller);
  Task<Void> pushTask = ParsePush.subscribeInBackground("test");
  pushTask.waitForCompletion();
  verify(controller, times(1)).subscribeInBackground("test");
  assertTrue(pushTask.isFaulted());
  assertSame(exception, pushTask.getError());
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testUnsubscribeInBackgroundFail() throws Exception {
  ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
  ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
  when(controller.unsubscribeInBackground(anyString()))
      .thenReturn(Task.<Void>forError(exception));
  ParseCorePlugins.getInstance().registerPushChannelsController(controller);
  Task<Void> pushTask = ParsePush.unsubscribeInBackground("test");
  pushTask.waitForCompletion();
  verify(controller, times(1)).unsubscribeInBackground("test");
  assertTrue(pushTask.isFaulted());
  assertSame(exception, pushTask.getError());
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testMissingRequiredFieldWhenSaveAsync() throws Exception {
  String sessionToken = "sessionToken";
  Task<Void> toAwait = Task.forResult(null);
  ParseCurrentInstallationController controller = mockCurrentInstallationController();
  ParseObjectController objController = mock(ParseObjectController.class);
  // mock return task when Installation was deleted on the server
  Task<ParseObject.State> taskError = Task.forError(new ParseException(ParseException.MISSING_REQUIRED_FIELD_ERROR, ""));
  // mock return task when Installation was re-saved to the server
  Task<ParseObject.State> task = Task.forResult(null);
  when(objController.saveAsync(
      any(ParseObject.State.class),
      any(ParseOperationSet.class),
      eq(sessionToken),
      any(ParseDecoder.class)))
      .thenReturn(taskError)
      .thenReturn(task);
  ParseCorePlugins.getInstance()
      .registerObjectController(objController);
  ParseInstallation installation = ParseInstallation.getCurrentInstallation();
  assertNotNull(installation);
  installation.put("key", "value");
  ParseTaskUtils.wait(installation.saveAsync(sessionToken, toAwait));
  verify(controller).getAsync();
  verify(objController, times(2)).saveAsync(
      any(ParseObject.State.class),
      any(ParseOperationSet.class),
      eq(sessionToken),
      any(ParseDecoder.class));
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testLoginWithAsyncWithLinkedLazyUseAndResolveLazinessFailure() throws Exception {
  // Register a mock currentUserController to make getCurrentUser work
  ParseUser currentUser = new ParseUser();
  Map<String, String> oldAnonymousAuthData = new HashMap<>();
  oldAnonymousAuthData.put("oldKey", "oldToken");
  currentUser.putAuthData(ParseAnonymousUtils.AUTH_TYPE, oldAnonymousAuthData);
  ParseUser partialMockCurrentUser = spy(currentUser);
  when(partialMockCurrentUser.getSessionToken()).thenReturn("oldSessionToken");
  doReturn(Task.<ParseUser>forError(new Exception()))
      .when(partialMockCurrentUser)
      .resolveLazinessAsync(Matchers.<Task<Void>>any());
  ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
  when(currentUserController.getAsync(false)).thenReturn(Task.forResult(partialMockCurrentUser));
  ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
  String authType = "facebook";
  Map<String, String> authData = new HashMap<>();
  authData.put("token", "123");
  Task<ParseUser> loginTask = ParseUser.logInWithInBackground(authType, authData);
  loginTask.waitForCompletion();
  // Make sure we try to resolveLaziness
  verify(partialMockCurrentUser, times(1)).resolveLazinessAsync(Matchers.<Task<Void>>any());
  // Make sure we do not save new authData
  assertNull(partialMockCurrentUser.getAuthData().get("facebook"));
  // Make sure we restore anonymity after resolve laziness failure
  assertEquals(oldAnonymousAuthData, partialMockCurrentUser.getAuthData()
      .get(ParseAnonymousUtils.AUTH_TYPE));
  // Make sure task fails
  assertTrue(loginTask.isFaulted());
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testSubscribeInBackgroundWithCallbackFail() throws Exception {
  ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
  final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
  when(controller.subscribeInBackground(anyString())).thenReturn(Task.<Void>forError(exception));
  ParseCorePlugins.getInstance().registerPushChannelsController(controller);
  ParsePush push = new ParsePush();
  final Semaphore done = new Semaphore(0);
  final Capture<Exception> exceptionCapture = new Capture<>();
  ParsePush.subscribeInBackground("test", new SaveCallback() {
    @Override
    public void done(ParseException e) {
      exceptionCapture.set(e);
      done.release();
    }
  });
  assertSame(exception, exceptionCapture.get());
  assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
  verify(controller, times(1)).subscribeInBackground("test");
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testUnsubscribeInBackgroundWithCallbackFail() throws Exception {
  ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
  final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
  when(controller.unsubscribeInBackground(anyString()))
      .thenReturn(Task.<Void>forError(exception));
  ParseCorePlugins.getInstance().registerPushChannelsController(controller);
  ParsePush push = new ParsePush();
  final Semaphore done = new Semaphore(0);
  final Capture<Exception> exceptionCapture = new Capture<>();
  ParsePush.unsubscribeInBackground("test", new SaveCallback() {
    @Override
    public void done(ParseException e) {
      exceptionCapture.set(e);
      done.release();
    }
  });
  assertSame(exception, exceptionCapture.get());
  assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
  verify(controller, times(1)).unsubscribeInBackground("test");
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testSetAsyncWithPersistFailure() throws Exception {
  // Mock currentUser in memory
  ParseUser oldCurrentUser = mock(ParseUser.class);
  when(oldCurrentUser.logOutAsync(anyBoolean())).thenReturn(Task.<Void>forResult(null));
  ParseUser currentUser = new ParseUser();
  ParseObjectStore<ParseUser> store =
      (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class);
  when(store.setAsync(currentUser))
      .thenReturn(Task.<Void>forError(new RuntimeException("failure")));
  CachedCurrentUserController controller =
      new CachedCurrentUserController(store);
  controller.currentUser = oldCurrentUser;
  ParseTaskUtils.wait(controller.setAsync(currentUser));
  // Make sure oldCurrentUser logout
  verify(oldCurrentUser, times(1)).logOutAsync(false);
  // Verify we tried to persist
  verify(store, times(1)).setAsync(currentUser);
  // TODO(mengyan): Find a way to verify user.synchronizeAllAuthData() is called
  // Verify newUser is currentUser
  assertTrue(currentUser.isCurrentUser());
  // Make sure in memory currentUser is up to date
  assertSame(currentUser, controller.currentUser);
  // Make sure in currentUserMatchesDisk since we can not write to disk
  assertFalse(controller.currentUserMatchesDisk);
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testGetAsyncWithCurrentUserReadFromDiskFailureAndLazyLogin() throws Exception {
  ParseObjectStore<ParseUser> store =
      (ParseObjectStore<ParseUser>) mock(ParseObjectStore.class);
  when(store.getAsync()).thenReturn(Task.<ParseUser>forError(new RuntimeException("failure")));
  CachedCurrentUserController controller =
      new CachedCurrentUserController(store);
  ParseUser currentUser = ParseTaskUtils.wait(controller.getAsync(true));
  // We need to make sure the user is created by lazy login
  assertTrue(currentUser.isLazy());
  assertTrue(currentUser.isCurrentUser());
  assertSame(controller.currentUser, currentUser);
  assertFalse(controller.currentUserMatchesDisk);
  // We do not test the lazy login auth data here, it is covered in lazyLogin() unit test
}

代码示例来源:origin: parse-community/Parse-SDK-Android

@Test
public void testSignUpAsyncWithNoCurrentUserAndSignUpFailure() {
  // Register a mock currentUserController to make getCurrentUser work
  ParseCurrentUserController currentUserController = mock(ParseCurrentUserController.class);
  when(currentUserController.getAsync(anyBoolean()))
      .thenReturn(Task.<ParseUser>forResult(null));
  ParseCorePlugins.getInstance().registerCurrentUserController(currentUserController);
  // Register a mock userController to make logIn work
  ParseUserController userController = mock(ParseUserController.class);
  ParseException signUpException = new ParseException(ParseException.OTHER_CAUSE, "test");
  when(userController.signUpAsync(
      any(ParseUser.State.class), any(ParseOperationSet.class), anyString()))
      .thenReturn(Task.<ParseUser.State>forError(signUpException));
  ParseCorePlugins.getInstance().registerUserController(userController);
  ParseUser user = new ParseUser();
  user.put("key", "value");
  user.setUsername("userName");
  user.setPassword("password");
  Task<Void> signUpTask = user.signUpAsync(Task.<Void>forResult(null));
  // Make sure we sign up the user
  verify(userController, times(1)).signUpAsync(
      any(ParseUser.State.class), any(ParseOperationSet.class), anyString());
  // Make sure user's data is correct
  assertEquals("value", user.getString("key"));
  // Make sure we never set the current user
  verify(currentUserController, never()).setAsync(user);
  // Make sure task is failed
  assertTrue(signUpTask.isFaulted());
  assertSame(signUpException, signUpTask.getError());
}

相关文章