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

The following examples show how to use com.google.android.gms.tasks.Tasks#forResult() . 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: CrashlyticsController.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private Task<Void> logAnalyticsAppExceptionEvent(long timestamp) {
  if (firebaseCrashExists()) {
    Logger.getLogger().d("Skipping logging Crashlytics event to Firebase, FirebaseCrash exists");
    return Tasks.forResult(null);
  }
  final ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
  return Tasks.call(
      executor,
      new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          final Bundle params = new Bundle();
          params.putInt(FIREBASE_CRASH_TYPE, FIREBASE_CRASH_TYPE_FATAL);
          params.putLong(FIREBASE_TIMESTAMP, timestamp);

          analyticsEventLogger.logEvent(FIREBASE_APPLICATION_EXCEPTION, params);

          return null;
        }
      });
}
 
Example 2
Source File: MainActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the folder view after the given task completes.
 *
 * @return Task which resolves after the view has been initialized
 */
private Task<Void> initializeFolderView() {
    Task<DriveFolder> folderTask;
    if (mNavigationPath.isEmpty()) {
        folderTask = mDriveResourceClient.getRootFolder();
    } else {
        folderTask = Tasks.forResult(mNavigationPath.peek().asDriveFolder());
    }
    Task<Void> initFolderTask = folderTask.continueWith(task -> {
        DriveId id = task.getResult().getDriveId();
        if (mNavigationPath.isEmpty()) {
            mNavigationPath.push(id);
        }
        return null;
    });
    return updateUiAfterTask(initFolderTask);
}
 
Example 3
Source File: CallTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstanceId() throws InterruptedException, ExecutionException {
  // Override the normal token provider to simulate FirebaseAuth being logged in.
  FirebaseFunctions functions =
      new FirebaseFunctions(
          app.getApplicationContext(),
          app.getOptions().getProjectId(),
          "us-central1",
          () -> {
            HttpsCallableContext context = new HttpsCallableContext(null, "iid");
            return Tasks.forResult(context);
          },
          NO_EMULATOR);

  HttpsCallableReference function = functions.getHttpsCallable("instanceIdTest");
  Task<HttpsCallableResult> result = function.call(new HashMap<>());
  Object actual = Tasks.await(result).getData();

  assertEquals(new HashMap<>(), actual);
}
 
Example 4
Source File: CallTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testToken() throws InterruptedException, ExecutionException {
  // Override the normal token provider to simulate FirebaseAuth being logged in.
  FirebaseFunctions functions =
      new FirebaseFunctions(
          app.getApplicationContext(),
          app.getOptions().getProjectId(),
          "us-central1",
          () -> {
            HttpsCallableContext context = new HttpsCallableContext("token", null);
            return Tasks.forResult(context);
          },
          NO_EMULATOR);

  HttpsCallableReference function = functions.getHttpsCallable("tokenTest");
  Task<HttpsCallableResult> result = function.call(new HashMap<>());
  Object actual = Tasks.await(result).getData();

  assertEquals(new HashMap<>(), actual);
}
 
Example 5
Source File: AutoMLImageLabelerProcessor.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Override
protected Task<List<FirebaseVisionImageLabel>> detectInImage(final FirebaseVisionImage image) {
  if (modelDownloadingTask == null) {
    // No download task means only the locally bundled model is used. Model can be used directly.
    return detector.processImage(image);
  } else if (!modelDownloadingTask.isComplete()) {
    if (mode == Mode.LIVE_PREVIEW) {
      Log.i(TAG, "Model download is in progress. Skip detecting image.");
      return Tasks.forResult(Collections.<FirebaseVisionImageLabel>emptyList());
    } else {
      Log.i(TAG, "Model download is in progress. Waiting...");
      return modelDownloadingTask.continueWithTask(new Continuation<Void, Task<List<FirebaseVisionImageLabel>>>() {
        @Override
        public Task<List<FirebaseVisionImageLabel>> then(@NonNull Task<Void> task) {
          return processImageOnDownloadComplete(image);
        }
      });
    }
  } else {
    return processImageOnDownloadComplete(image);
  }
}
 
Example 6
Source File: FirebaseInstallations.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a globally unique identifier of this Firebase app installation. This is a url-safe
 * base64 string of a 128-bit integer.
 */
@NonNull
@Override
public Task<String> getId() {
  preConditionChecks();
  return Tasks.forResult(doGetId());
}
 
Example 7
Source File: SessionReportingCoordinator.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Send all finalized reports.
 *
 * @param reportSendCompleteExecutor executor on which to run report cleanup after each report is
 *     sent.
 * @param dataTransportState used to determine whether to send the report before cleaning it up.
 */
Task<Void> sendReports(
    @NonNull Executor reportSendCompleteExecutor,
    @NonNull DataTransportState dataTransportState) {
  if (dataTransportState == DataTransportState.NONE) {
    Logger.getLogger().d("Send via DataTransport disabled. Removing DataTransport reports.");
    reportPersistence.deleteAllReports();
    return Tasks.forResult(null);
  }
  final List<CrashlyticsReportWithSessionId> reportsToSend =
      reportPersistence.loadFinalizedReports();
  final List<Task<Boolean>> sendTasks = new ArrayList<>();
  for (CrashlyticsReportWithSessionId reportToSend : reportsToSend) {
    if (reportToSend.getReport().getType() == CrashlyticsReport.Type.NATIVE
        && dataTransportState != DataTransportState.ALL) {
      Logger.getLogger()
          .d("Send native reports via DataTransport disabled. Removing DataTransport reports.");
      reportPersistence.deleteFinalizedReport(reportToSend.getSessionId());
      continue;
    }

    sendTasks.add(
        reportsSender
            .sendReport(reportToSend)
            .continueWith(reportSendCompleteExecutor, this::onReportSendComplete));
  }
  return Tasks.whenAll(sendTasks);
}
 
Example 8
Source File: CrashlyticsController.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private Task<Boolean> waitForReportAction() {
  if (dataCollectionArbiter.isAutomaticDataCollectionEnabled()) {
    Logger.getLogger().d("Automatic data collection is enabled. Allowing upload.");
    unsentReportsAvailable.trySetResult(false);
    return Tasks.forResult(true);
  }

  Logger.getLogger().d("Automatic data collection is disabled.");
  Logger.getLogger().d("Notifying that unsent reports are available.");
  unsentReportsAvailable.trySetResult(true);

  // If data collection gets enabled while we are waiting for an action, go ahead and send the
  // reports, and any subsequent explicit response will be ignored.
  final Task<Boolean> collectionEnabled =
      dataCollectionArbiter
          .waitForAutomaticDataCollectionEnabled()
          .onSuccessTask(
              new SuccessContinuation<Void, Boolean>() {
                @NonNull
                @Override
                public Task<Boolean> then(@Nullable Void aVoid) throws Exception {
                  return Tasks.forResult(true);
                }
              });

  Logger.getLogger().d("Waiting for send/deleteUnsentReports to be called.");
  // Wait for either the processReports callback to be called, or data collection to be enabled.
  return Utils.race(collectionEnabled, reportActionProvided.getTask());
}
 
Example 9
Source File: CrashlyticsController.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
Task<Boolean> checkForUnsentReports() {
  // Make sure checkForUnsentReports only gets called once. It really doesn't make sense to call
  // it multiple times, since reports only get packaged up at two possible times: 1) at start-up,
  // and 2) when there's a fatal crash. So no new reports will become available while the app is
  // running.
  if (!checkForUnsentReportsCalled.compareAndSet(false, true)) {
    Logger.getLogger().d("checkForUnsentReports should only be called once per execution.");
    return Tasks.forResult(false);
  }
  return unsentReportsAvailable.getTask();
}
 
Example 10
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 11
Source File: FirebaseDynamicLinksImpl.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Task<PendingDynamicLinkData> getDynamicLink(@NonNull final Intent intent) {
  Task<PendingDynamicLinkData> result =
      googleApi.doWrite(new GetDynamicLinkImpl(analytics, intent.getDataString()));
  PendingDynamicLinkData pendingDynamicLinkData = getPendingDynamicLinkData(intent);
  if (pendingDynamicLinkData != null) {
    // DynamicLinkData included in the Intent, return it immediately and allow the Task to run in
    // the background to do logging and mark the FDL as returned.
    result = Tasks.forResult(pendingDynamicLinkData);
  }
  return result;
}
 
Example 12
Source File: FirebaseRemoteConfig.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Asynchronously sets the defaults cache to the given default values, and persists the values to
 * disk.
 *
 * @return A task with result {@code null} on failure.
 */
private Task<Void> setDefaultsWithStringsMapAsync(Map<String, String> defaultsStringMap) {
  ConfigContainer defaultConfigs = null;
  try {
    defaultConfigs = ConfigContainer.newBuilder().replaceConfigsWith(defaultsStringMap).build();
  } catch (JSONException e) {
    Log.e(TAG, "The provided defaults map could not be processed.", e);
    return Tasks.forResult(null);
  }

  Task<ConfigContainer> putTask = defaultConfigsCache.put(defaultConfigs);
  // Convert Task type to Void.
  return putTask.onSuccessTask((unusedContainer) -> Tasks.forResult(null));
}
 
Example 13
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 14
Source File: TranslateViewModel.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
public Task<String> translate() {
    final String text = sourceText.getValue();
    final Language source = sourceLang.getValue();
    final Language target = targetLang.getValue();
    if (source == null || target == null || text == null || text.isEmpty()) {
        return Tasks.forResult("");
    }
    int sourceLangCode =
            FirebaseTranslateLanguage.languageForLanguageCode(source.getCode());
    int targetLangCode =
            FirebaseTranslateLanguage.languageForLanguageCode(target.getCode());
    FirebaseTranslatorOptions options = new FirebaseTranslatorOptions.Builder()
            .setSourceLanguage(sourceLangCode)
            .setTargetLanguage(targetLangCode)
            .build();
    final FirebaseTranslator translator =
            FirebaseNaturalLanguage.getInstance().getTranslator(options);
    return translator.downloadModelIfNeeded().continueWithTask(
            new Continuation<Void, Task<String>>() {
        @Override
        public Task<String> then(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                return translator.translate(text);
            } else {
                Exception e = task.getException();
                if (e == null) {
                    e = new Exception(getApplication().getString(R.string.unknown_error));
                }
                return Tasks.forException(e);
            }
        }
    });
}
 
Example 15
Source File: MainActivity.java    From snippets-android with Apache License 2.0 4 votes vote down vote up
public Task<String> doSomething(AuthResult authResult) {
    // [START_EXCLUDE]
    return Tasks.forResult("Hello, World!");
    // [END_EXCLUDE]
}
 
Example 16
Source File: AutoContinueTask.java    From FirebaseUI-Android with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
        @NonNull Continuation<TResult, Task<TContinuationResult>> continuation) {
    return (Task<TContinuationResult>) Tasks.forResult(mContinuationResult);
}
 
Example 17
Source File: ConfigCacheClient.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/** Sets {@link #cachedContainerTask} to a {@link Task} containing {@code configContainer}. */
private synchronized void updateInMemoryConfigContainer(ConfigContainer configContainer) {
  cachedContainerTask = Tasks.forResult(configContainer);
}
 
Example 18
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 19
Source File: CrashlyticsController.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
Task<Void> submitAllReports(float delay, Task<AppSettingsData> appSettingsDataTask) {
  if (!reportManager.areReportsAvailable()) {
    // Just notify the user that there are no reports and stop.
    Logger.getLogger().d("No reports are available.");
    unsentReportsAvailable.trySetResult(false);
    return Tasks.forResult(null);
  }
  Logger.getLogger().d("Unsent reports are available.");

  return waitForReportAction()
      .onSuccessTask(
          new SuccessContinuation<Boolean, Void>() {
            @NonNull
            @Override
            public Task<Void> then(@Nullable Boolean send) throws Exception {

              return backgroundWorker.submitTask(
                  new Callable<Task<Void>>() {
                    @Override
                    public Task<Void> call() throws Exception {
                      List<Report> reports = reportManager.findReports();

                      if (!send) {
                        Logger.getLogger().d("Reports are being deleted.");
                        deleteFiles(listAppExceptionMarkerFiles());
                        reportManager.deleteReports(reports);
                        reportingCoordinator.removeAllReports();
                        unsentReportsHandled.trySetResult(null);
                        return Tasks.forResult(null);
                      }

                      Logger.getLogger().d("Reports are being sent.");

                      // waitForReportAction guarantees we got user permission.
                      boolean dataCollectionToken = send;

                      // Signal to the settings fetch and onboarding that we have explicit
                      // permission.
                      dataCollectionArbiter.grantDataCollectionPermission(dataCollectionToken);

                      Executor executor = backgroundWorker.getExecutor();

                      return appSettingsDataTask.onSuccessTask(
                          executor,
                          new SuccessContinuation<AppSettingsData, Void>() {
                            @NonNull
                            @Override
                            public Task<Void> then(@Nullable AppSettingsData appSettingsData)
                                throws Exception {
                              if (appSettingsData == null) {
                                Logger.getLogger()
                                    .w(
                                        "Received null app settings, cannot send reports during app startup.");
                                return Tasks.forResult(null);
                              }
                              // Append the most recent org ID to each report file, even if it
                              // was already appended during the crash time upload. This way
                              // we'll always have the most recent value available attached.
                              for (Report report : reports) {
                                if (report.getType() == Report.Type.JAVA) {
                                  appendOrganizationIdToSessionFile(
                                      appSettingsData.organizationId, report.getFile());
                                }
                              }
                              logAnalyticsAppExceptionEvents();
                              ReportUploader uploader =
                                  reportUploaderProvider.createReportUploader(appSettingsData);
                              uploader.uploadReportsAsync(reports, dataCollectionToken, delay);
                              reportingCoordinator.sendReports(
                                  executor, DataTransportState.getState(appSettingsData));
                              unsentReportsHandled.trySetResult(null);

                              return Tasks.forResult(null);
                            }
                          });
                    }
                  });
            }
          });
}
 
Example 20
Source File: SettingsController.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Kicks off loading settings either from the cache or the network.
 *
 * @return a task that is resolved when loading is completely finished.
 */
public Task<Void> loadSettingsData(SettingsCacheBehavior cacheBehavior, Executor executor) {
  // TODO: Refactor this so that it doesn't do the cache lookup twice when settings are
  // expired.

  // We need to bypass the cache if this is the first time a new build has run so the
  // backend will know about it.
  if (!buildInstanceIdentifierChanged()) {
    final SettingsData cachedSettings = getCachedSettingsData(cacheBehavior);
    if (cachedSettings != null) {
      settings.set(cachedSettings);
      appSettingsData.get().trySetResult(cachedSettings.getAppSettingsData());
      return Tasks.forResult(null);
    }
  }

  // SKIP_CACHE doesn't actually skip the cache completely; it just skips the first lookup, since
  // we are doing the cache lookup again here with IGNORE_CACHE_EXPIRATION.
  // This has been true in production for some time, though, so no rush to "fix" it.

  // The cached settings are too old, so if there are expired settings, use those for now.
  final SettingsData expiredSettings =
      getCachedSettingsData(SettingsCacheBehavior.IGNORE_CACHE_EXPIRATION);
  if (expiredSettings != null) {
    settings.set(expiredSettings);
    appSettingsData.get().trySetResult(expiredSettings.getAppSettingsData());
  }

  // Kick off fetching fresh settings.
  return dataCollectionArbiter
      .waitForDataCollectionPermission()
      .onSuccessTask(
          executor,
          new SuccessContinuation<Void, Void>() {
            @NonNull
            @Override
            public Task<Void> then(@Nullable Void aVoid) throws Exception {
              // Waited for data collection permission, so this is safe.
              final boolean dataCollectionToken = true;
              final JSONObject settingsJson =
                  settingsSpiCall.invoke(settingsRequest, dataCollectionToken);

              if (settingsJson != null) {
                final SettingsData fetchedSettings =
                    settingsJsonParser.parseSettingsJson(settingsJson);
                cachedSettingsIo.writeCachedSettings(
                    fetchedSettings.getExpiresAtMillis(), settingsJson);
                logSettings(settingsJson, "Loaded settings: ");

                setStoredBuildInstanceIdentifier(settingsRequest.instanceId);

                // Update the regular settings.
                settings.set(fetchedSettings);

                // Signal the app settings on any Tasks that already exist, and then replace the
                // task so
                // that any new callers get the new app settings instead of any old ones.
                appSettingsData.get().trySetResult(fetchedSettings.getAppSettingsData());
                TaskCompletionSource<AppSettingsData> fetchedAppSettings =
                    new TaskCompletionSource<>();
                fetchedAppSettings.trySetResult(fetchedSettings.getAppSettingsData());
                appSettingsData.set(fetchedAppSettings);
              }

              return Tasks.forResult(null);
            }
          });
}