Java Code Examples for com.google.android.gms.tasks.Tasks#forException()

The following examples show how to use com.google.android.gms.tasks.Tasks#forException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Transaction.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Takes a set of keys and asynchronously attempts to fetch all the documents from the backend,
 * ignoring any local changes.
 */
public Task<List<MaybeDocument>> lookup(List<DocumentKey> keys) {
  ensureCommitNotCalled();

  if (mutations.size() != 0) {
    return Tasks.forException(
        new FirebaseFirestoreException(
            "Firestore transactions require all reads to be executed before all writes.",
            Code.INVALID_ARGUMENT));
  }
  return datastore
      .lookup(keys)
      .continueWithTask(
          Executors.DIRECT_EXECUTOR,
          task -> {
            if (task.isSuccessful()) {
              for (MaybeDocument doc : task.getResult()) {
                recordVersion(doc);
              }
            }
            return task;
          });
}
 
Example 2
Source File: SessionReportingCoordinatorTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void onReportSend_successfulReportsAreDeleted() {
  final String sessionId1 = "sessionId1";
  final String sessionId2 = "sessionId2";

  final List<CrashlyticsReportWithSessionId> finalizedReports = new ArrayList<>();
  final CrashlyticsReportWithSessionId mockReport1 = mockReportWithSessionId(sessionId1);
  final CrashlyticsReportWithSessionId mockReport2 = mockReportWithSessionId(sessionId2);
  finalizedReports.add(mockReport1);
  finalizedReports.add(mockReport2);

  when(reportPersistence.loadFinalizedReports()).thenReturn(finalizedReports);

  final Task<CrashlyticsReportWithSessionId> successfulTask = Tasks.forResult(mockReport1);
  final Task<CrashlyticsReportWithSessionId> failedTask =
      Tasks.forException(new Exception("fail"));

  when(reportSender.sendReport(mockReport1)).thenReturn(successfulTask);
  when(reportSender.sendReport(mockReport2)).thenReturn(failedTask);

  reportManager.sendReports(Runnable::run, DataTransportState.ALL);

  verify(reportSender).sendReport(mockReport1);
  verify(reportSender).sendReport(mockReport2);

  verify(reportPersistence).deleteFinalizedReport(sessionId1);
  verify(reportPersistence, never()).deleteFinalizedReport(sessionId2);
}
 
Example 3
Source File: ConfigFetchHandler.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches configs from the FRC backend. If there are any updates, writes the configs to the
 * {@code fetchedConfigsCache}.
 */
private Task<FetchResponse> fetchFromBackendAndCacheResponse(
    String installationId, String installationToken, Date fetchTime) {
  try {
    FetchResponse fetchResponse = fetchFromBackend(installationId, installationToken, fetchTime);
    if (fetchResponse.getStatus() != Status.BACKEND_UPDATES_FETCHED) {
      return Tasks.forResult(fetchResponse);
    }
    return fetchedConfigsCache
        .put(fetchResponse.getFetchedConfigs())
        .onSuccessTask(executor, (putContainer) -> Tasks.forResult(fetchResponse));
  } catch (FirebaseRemoteConfigException frce) {
    return Tasks.forException(frce);
  }
}
 
Example 4
Source File: Transaction.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public Task<Void> commit() {
  ensureCommitNotCalled();

  if (lastWriteError != null) {
    return Tasks.forException(lastWriteError);
  }

  HashSet<DocumentKey> unwritten = new HashSet<>(readVersions.keySet());
  // For each mutation, note that the doc was written.
  for (Mutation mutation : mutations) {
    unwritten.remove(mutation.getKey());
  }
  // For each document that was read but not written to, we want to perform a `verify` operation.
  for (DocumentKey key : unwritten) {
    mutations.add(new VerifyMutation(key, precondition(key)));
  }
  committed = true;
  return datastore
      .commit(mutations)
      .continueWithTask(
          Executors.DIRECT_EXECUTOR,
          task -> {
            if (task.isSuccessful()) {
              return Tasks.forResult(null);
            } else {
              return Tasks.forException(task.getException());
            }
          });
}
 
Example 5
Source File: ChatViewModel.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private Task<List<SmartReplySuggestion>> generateReplies(List<Message> messages,
                                                         boolean isEmulatingRemoteUser) {
    Message lastMessage = messages.get(messages.size() - 1);

    // If the last message in the chat thread is not sent by the "other" user, don't generate
    // smart replies.
    if (lastMessage.isLocalUser && !isEmulatingRemoteUser || !lastMessage.isLocalUser && isEmulatingRemoteUser) {
        return Tasks.forException(new Exception("Not running smart reply!"));
    }

    List<FirebaseTextMessage> chatHistory = new ArrayList<>();
    for (Message message : messages) {
        if (message.isLocalUser && !isEmulatingRemoteUser || !message.isLocalUser && isEmulatingRemoteUser) {
            chatHistory.add(FirebaseTextMessage.createForLocalUser(message.text,
                    message.timestamp));
        } else {
            chatHistory.add(FirebaseTextMessage.createForRemoteUser(message.text,
                    message.timestamp, REMOTE_USER_ID));
        }
    }

    return FirebaseNaturalLanguage.getInstance().getSmartReply().suggestReplies(chatHistory)
            .continueWith(new Continuation<SmartReplySuggestionResult, List<SmartReplySuggestion>>() {
                @Override
                public List<SmartReplySuggestion> then(@NonNull Task<SmartReplySuggestionResult> task) {
                    return task.getResult().getSuggestions();
                }
            });
}
 
Example 6
Source File: AutoMLImageLabelerProcessor.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private Task<List<FirebaseVisionImageLabel>> processImageOnDownloadComplete(
    FirebaseVisionImage image) {
  if (modelDownloadingTask.isSuccessful()) {
    return detector.processImage(image);
  } else {
    String downloadingError = "Error downloading remote model.";
    Log.e(TAG, downloadingError, modelDownloadingTask.getException());
    Toast.makeText(context, downloadingError, Toast.LENGTH_SHORT).show();
    return Tasks.forException(
        new Exception("Failed to download remote model.", modelDownloadingTask.getException()));
  }
}
 
Example 7
Source File: AutoCompleteTask.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWith(
        @NonNull Continuation<TResult, TContinuationResult> continuation) {
    try {
        return Tasks.forResult(continuation.then(this));
    } catch (Exception e) {
        return Tasks.forException(unwrap(e));
    }
}
 
Example 8
Source File: AutoCompleteTask.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
        @NonNull Continuation<TResult, Task<TContinuationResult>> continuation) {
    try {
        return continuation.then(this);
    } catch (Exception e) {
        return Tasks.forException(unwrap(e));
    }
}
 
Example 9
Source File: CrashlyticsCore.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/** Performs background initialization synchronously on the calling thread. */
private Task<Void> doBackgroundInitialization(SettingsDataProvider settingsProvider) {
  // create the marker for this run
  markInitializationStarted();

  controller.cleanInvalidTempFiles();

  try {
    breadcrumbSource.registerBreadcrumbHandler(this::log);

    final Settings settingsData = settingsProvider.getSettings();

    if (!settingsData.getFeaturesData().collectReports) {
      Logger.getLogger().d("Collection of crash reports disabled in Crashlytics settings.");
      // TODO: This isn't actually an error condition, so figure out the right way to
      // handle this case.
      return Tasks.forException(
          new RuntimeException("Collection of crash reports disabled in Crashlytics settings."));
    }

    if (!controller.finalizeSessions(settingsData.getSessionData().maxCustomExceptionEvents)) {
      Logger.getLogger().d("Could not finalize previous sessions.");
    }

    // TODO: Move this call out of this method, so that the return value merely indicates
    // initialization is complete. Callers that want to know when report sending is complete can
    // handle that as a separate call.
    return controller.submitAllReports(
        CLS_DEFAULT_PROCESS_DELAY, settingsProvider.getAppSettings());
  } catch (Exception e) {
    Logger.getLogger()
        .e("Crashlytics encountered a problem during asynchronous initialization.", e);
    return Tasks.forException(e);
  } finally {
    // The only thing that compels us to leave the marker and start synchronously next time
    // is not executing all the way through this method. That would indicate that we perhaps
    // didn't get our settings and have a chance to send reports. This situation is usually
    // caused by the Main thread crashing shortly after the synchronous portion of our
    // start-up completes.
    //
    // Internal exceptions on start-up or other problems aren't likely to be fixed by
    // starting synchronously next time, so don't bother slowing down the host app for that.
    markInitializationComplete();
  }
}
 
Example 10
Source File: ConfigFetchHandler.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches from the backend if the fetched configs cache has expired and the client is not
 * currently throttled.
 *
 * <p>If a fetch request is made to the backend, updates the last fetch status, last successful
 * fetch time and {@link BackoffMetadata} in {@link ConfigMetadataClient}.
 */
private Task<FetchResponse> fetchIfCacheExpiredAndNotThrottled(
    Task<ConfigContainer> cachedFetchConfigsTask, long minimumFetchIntervalInSeconds) {
  Date currentTime = new Date(clock.currentTimeMillis());
  if (cachedFetchConfigsTask.isSuccessful()
      && areCachedFetchConfigsValid(minimumFetchIntervalInSeconds, currentTime)) {
    // Keep the cached fetch values if the cache has not expired yet.
    return Tasks.forResult(FetchResponse.forLocalStorageUsed(currentTime));
  }

  Task<FetchResponse> fetchResponseTask;

  Date backoffEndTime = getBackoffEndTimeInMillis(currentTime);
  if (backoffEndTime != null) {
    // TODO(issues/260): Provide a way for users to check for throttled status so exceptions
    // aren't the only way for users to determine if they're throttled.
    fetchResponseTask =
        Tasks.forException(
            new FirebaseRemoteConfigFetchThrottledException(
                createThrottledMessage(backoffEndTime.getTime() - currentTime.getTime()),
                backoffEndTime.getTime()));
  } else {
    Task<String> installationIdTask = firebaseInstallations.getId();
    Task<InstallationTokenResult> installationAuthTokenTask =
        firebaseInstallations.getToken(false);
    fetchResponseTask =
        Tasks.whenAllComplete(installationIdTask, installationAuthTokenTask)
            .continueWithTask(
                executor,
                (completedInstallationsTasks) -> {
                  if (!installationIdTask.isSuccessful()) {
                    return Tasks.forException(
                        new FirebaseRemoteConfigClientException(
                            "Firebase Installations failed to get installation ID for fetch.",
                            installationIdTask.getException()));
                  }

                  if (!installationAuthTokenTask.isSuccessful()) {
                    return Tasks.forException(
                        new FirebaseRemoteConfigClientException(
                            "Firebase Installations failed to get installation auth token for fetch.",
                            installationAuthTokenTask.getException()));
                  }

                  String installationId = installationIdTask.getResult();
                  String installationToken = installationAuthTokenTask.getResult().getToken();
                  return fetchFromBackendAndCacheResponse(
                      installationId, installationToken, currentTime);
                });
  }

  return fetchResponseTask.continueWithTask(
      executor,
      (completedFetchTask) -> {
        updateLastFetchStatusAndTime(completedFetchTask, currentTime);
        return completedFetchTask;
      });
}
 
Example 11
Source File: RestaurantDetailActivity.java    From friendlyeats-android with Apache License 2.0 4 votes vote down vote up
private Task<Void> addRating(final DocumentReference restaurantRef, final Rating rating) {
    // TODO(developer): Implement
    return Tasks.forException(new Exception("not yet implemented"));
}