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

The following examples show how to use com.google.android.gms.tasks.Tasks#await() . 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: Util.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Nullable
public static String getCurrentAuthToken(@Nullable InternalAuthProvider authProvider) {
  try {
    String token = null;

    if (authProvider != null) {
      Task<GetTokenResult> pendingResult = authProvider.getAccessToken(false);
      GetTokenResult result =
          Tasks.await(pendingResult, MAXIMUM_TOKEN_WAIT_TIME_MS, TimeUnit.MILLISECONDS);
      token = result.getToken();
    }

    if (!TextUtils.isEmpty(token)) {
      return token;
    } else {
      Log.w(TAG, "no auth token for request");
    }
  } catch (ExecutionException | InterruptedException | TimeoutException e) {
    Log.e(TAG, "error getting token " + e);
  }
  return null;
}
 
Example 2
Source File: ConfigCacheClientTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void put_secondFileWriteFails_keepsFirstContainerInCache() throws Exception {
  when(mockStorageClient.write(configContainer2)).thenThrow(IO_EXCEPTION);

  Tasks.await(cacheClient.put(configContainer));
  Preconditions.checkArgument(
      cacheClient.getCachedContainerTask().getResult().equals(configContainer));

  Task<ConfigContainer> failedPutTask = cacheClient.put(configContainer2);
  assertThrows(ExecutionException.class, () -> Tasks.await(failedPutTask));

  verifyFileWrites(configContainer, configContainer2);

  assertThat(failedPutTask.getException()).isInstanceOf(IOException.class);
  assertThat(cacheClient.getCachedContainerTask().getResult()).isEqualTo(configContainer);
}
 
Example 3
Source File: IntegrationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void pagedListFiles() throws ExecutionException, InterruptedException {
  Task<ListResult> listTask = getReference().list(2);
  ListResult listResult = Tasks.await(listTask);

  assertThat(listResult.getItems())
      .containsExactly(getReference("download.dat"), getReference("metadata.dat"));
  assertThat(listResult.getPrefixes()).isEmpty();
  assertThat(listResult.getPageToken()).isNotEmpty();

  listTask = getReference().list(2, listResult.getPageToken());
  listResult = Tasks.await(listTask);

  assertThat(listResult.getItems()).isEmpty();
  assertThat(listResult.getPrefixes()).containsExactly(getReference("prefix"));
  assertThat(listResult.getPageToken()).isNull();
}
 
Example 4
Source File: AccountTransferService.java    From account-transfer-api with Apache License 2.0 6 votes vote down vote up
private void importAccount() {
    // Handle to client object
    AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);

    // Make RetrieveData api call to get the transferred over data.
    Task<byte[]> transferTask = client.retrieveData(ACCOUNT_TYPE);
    try {
        byte[] transferBytes = Tasks.await(transferTask, TIMEOUT_API, TIME_UNIT);
        AccountTransferUtil.importAccounts(transferBytes, this);
    } catch (ExecutionException | InterruptedException | TimeoutException | JSONException e) {
        Log.e(TAG, "Exception while calling importAccounts()", e);
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
        return;
    }
    client.notifyCompletion(
            ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);

}
 
Example 5
Source File: IntegrationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void uploadBytesThenGetDownloadUrl() throws ExecutionException, InterruptedException {
  byte[] data = new byte[] {1, 2, 3};
  StorageReference reference = getReference("upload.dat");

  Uri downloadUrl =
      Tasks.await(
          reference
              .putBytes(data)
              .onSuccessTask(
                  taskSnapshot -> {
                    assertThat(taskSnapshot.getBytesTransferred()).isEqualTo(3);
                    assertThat(taskSnapshot.getTotalByteCount()).isEqualTo(3);

                    return reference.getDownloadUrl();
                  }));

  assertThat(downloadUrl.toString()).startsWith("https://firebasestorage.googleapis.com/");
}
 
Example 6
Source File: AccountTransferService.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
private void importAccount() {
    // Handle to client object
    AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);

    // Make RetrieveData api call to get the transferred over data.
    Task<byte[]> transferTask = client.retrieveData(ACCOUNT_TYPE);
    try {
        byte[] transferBytes = Tasks.await(transferTask, TIMEOUT_API, TIME_UNIT);
        AccountTransferUtil.importAccounts(transferBytes, this);
    } catch (ExecutionException | InterruptedException | TimeoutException | JSONException e) {
        Log.e(TAG, "Exception while calling importAccounts()", e);
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
        return;
    }
    client.notifyCompletion(
            ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);

}
 
Example 7
Source File: AccountTransferService.java    From account-transfer-api with Apache License 2.0 6 votes vote down vote up
private void exportAccount() {
    Log.d(TAG, "exportAccount()");
    byte[] transferBytes = AccountTransferUtil.getTransferBytes(this);
    AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);
    if (transferBytes == null) {
        Log.d(TAG, "Nothing to export");
        // Notifying is important.
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);
        return;
    }

    // Send the data over to the other device.
    Task<Void> exportTask = client.sendData(ACCOUNT_TYPE, transferBytes);
    try {
        Tasks.await(exportTask, TIMEOUT_API, TIME_UNIT);
    } catch (ExecutionException | InterruptedException | TimeoutException e) {
        Log.e(TAG, "Exception while calling exportAccounts()", e);
        // Notifying is important.
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
        return;
    }
}
 
Example 8
Source File: AccountTransferService.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
private void exportAccount() {
    Log.d(TAG, "exportAccount()");
    byte[] transferBytes = AccountTransferUtil.getTransferBytes(this);
    AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);
    if (transferBytes == null) {
        Log.d(TAG, "Nothing to export");
        // Notifying is important.
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);
        return;
    }

    // Send the data over to the other device.
    Task<Void> exportTask = client.sendData(ACCOUNT_TYPE, transferBytes);
    try {
        Tasks.await(exportTask, TIMEOUT_API, TIME_UNIT);
    } catch (ExecutionException | InterruptedException | TimeoutException e) {
        Log.e(TAG, "Exception while calling exportAccounts()", e);
        // Notifying is important.
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
        return;
    }
}
 
Example 9
Source File: IntegrationTestUtil.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static <T> T waitFor(Task<T> task, long timeoutMS) {
  try {
    return Tasks.await(task, timeoutMS, TimeUnit.MILLISECONDS);
  } catch (TimeoutException | ExecutionException | InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 
Example 10
Source File: IntegrationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws ExecutionException, InterruptedException {
  if (storageClient == null) {
    FirebaseApp app = FirebaseApp.initializeApp(InstrumentationRegistry.getContext());
    storageClient = FirebaseStorage.getInstance(app);

    Tasks.await(getReference("metadata.dat").putBytes(new byte[0]));
    Tasks.await(getReference("download.dat").putBytes(new byte[LARGE_FILE_SIZE_BYTES]));
    Tasks.await(getReference("prefix/empty.dat").putBytes(new byte[0]));
    Tasks.await(getReference(unicodePrefix + "/empty.dat").putBytes(new byte[0]));
  }
}
 
Example 11
Source File: IntegrationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void downloadFile() throws ExecutionException, InterruptedException, IOException {
  File tempFile = new File(Environment.getExternalStorageDirectory(), "download.dat");

  FileDownloadTask.TaskSnapshot fileTask =
      Tasks.await(getReference("download.dat").getFile(tempFile));

  assertThat(tempFile.exists()).isTrue();
  assertThat(tempFile.length()).isEqualTo(LARGE_FILE_SIZE_BYTES);
  assertThat(fileTask.getBytesTransferred()).isEqualTo(LARGE_FILE_SIZE_BYTES);
}
 
Example 12
Source File: RestaurantUtil.java    From firestore-android-arch-components with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private static List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
 
Example 13
Source File: FirebaseRemoteConfigIntegrationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void setDefaultsAsync_goodXml_setsDefaults() throws Exception {
  ConfigContainer goodDefaultsXmlContainer = newDefaultsContainer(DEFAULTS_MAP);
  cachePutReturnsConfig(mockDefaultsCache, goodDefaultsXmlContainer);

  Task<Void> task = frc.setDefaultsAsync(getResourceId("frc_good_defaults"));
  Tasks.await(task);

  // Assert defaults were set correctly.
  ArgumentCaptor<ConfigContainer> captor = ArgumentCaptor.forClass(ConfigContainer.class);
  verify(mockDefaultsCache).put(captor.capture());
  assertThat(captor.getValue()).isEqualTo(goodDefaultsXmlContainer);
}
 
Example 14
Source File: ConfigCacheClientTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void get_hasCachedValue_returnsCache() throws Exception {
  Tasks.await(cacheClient.put(configContainer));
  Preconditions.checkArgument(
      cacheClient.getCachedContainerTask().getResult().equals(configContainer));

  ConfigContainer getContainer = Tasks.await(cacheClient.get());

  verify(mockStorageClient, never()).read();
  assertThat(getContainer).isEqualTo(configContainer);
}
 
Example 15
Source File: ConfigCacheClientTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void get_hasFailedCacheValue_readsFileAndSetsCache() throws Exception {
  when(mockStorageClient.read()).thenThrow(IO_EXCEPTION);
  Task<ConfigContainer> getTask = cacheClient.get();
  assertThrows(ExecutionException.class, () -> Tasks.await(getTask));
  Preconditions.checkArgument(getTask.getException() instanceof IOException);

  doReturn(configContainer).when(mockStorageClient).read();

  ConfigContainer getContainer = Tasks.await(cacheClient.get());

  assertThat(getContainer).isEqualTo(configContainer);
}
 
Example 16
Source File: IntegrationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void listAllFiles() throws ExecutionException, InterruptedException {
  Task<ListResult> listTask = getReference().listAll();
  ListResult listResult = Tasks.await(listTask);

  assertThat(listResult.getPrefixes()).containsExactly(getReference("prefix"));
  assertThat(listResult.getItems())
      .containsExactly(getReference("metadata.dat"), getReference("download.dat"));
  assertThat(listResult.getPageToken()).isNull();
}
 
Example 17
Source File: FirebaseInAppMessagingFlowableTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void whenImpressed_filtersCampaignToRequestUpstream()
    throws ExecutionException, InterruptedException, TimeoutException {
  VanillaCampaignPayload otherCampaign =
      VanillaCampaignPayload.newBuilder(vanillaCampaign.build())
          .setCampaignId("otherCampaignId")
          .setCampaignName(CAMPAIGN_NAME_STRING)
          .build();
  ThickContent otherContent =
      ThickContent.newBuilder(thickContent)
          .setContent(BANNER_MESSAGE_PROTO)
          .clearVanillaPayload()
          .setIsTestCampaign(IS_NOT_TEST_MESSAGE)
          .clearTriggeringConditions()
          .addTriggeringConditions(
              TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName("event2")))
          .setVanillaPayload(otherCampaign)
          .build();
  FetchEligibleCampaignsResponse response =
      FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
          .addMessages(otherContent)
          .build();

  InAppMessagingSdkServingImplBase impl =
      new InAppMessagingSdkServingImplBase() {
        @Override
        public void fetchEligibleCampaigns(
            FetchEligibleCampaignsRequest request,
            StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
          // Fail hard if impression not present
          CampaignImpression firstImpression = request.getAlreadySeenCampaignsList().get(0);
          assertThat(firstImpression).isNotNull();
          assertThat(firstImpression.getCampaignId())
              .isEqualTo(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId());

          responseObserver.onNext(response);
          responseObserver.onCompleted();
        }
      };
  grpcServerRule.getServiceRegistry().addService(impl);

  Task<Void> logImpressionTask =
      displayCallbacksFactory
          .generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
          .impressionDetected();
  Tasks.await(logImpressionTask, 1000, TimeUnit.MILLISECONDS);
  analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
  analyticsConnector.invokeListenerOnEvent("event2");

  waitUntilNotified(subscriber);
}
 
Example 18
Source File: CrashlyticsControllerTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private static <T> T await(Task<T> task) throws Exception {
  return Tasks.await(task, 5, TimeUnit.SECONDS);
}
 
Example 19
Source File: DefaultSettingsControllerTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private <T> T await(Task<T> task) throws Exception {
  return Tasks.await(task, 10, TimeUnit.SECONDS);
}
 
Example 20
Source File: FirebaseSegmentation.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Clear custom installation id of the {@link FirebaseApp} on Firebase segmentation backend and
 * client side cache.
 *
 * <pre>
 *     The workflow is:
 *                  get Firebase instance id and token
 *                      |                      |
 *                      |    update cache with cache status PENDING_CLEAR
 *                      |                      |
 *                    send http request to backend
 *                                  |
 *                   on success: delete cache entry
 *                                  |
 *                               return
 * </pre>
 */
@WorkerThread
private Void clearCustomInstallationId() throws SetCustomInstallationIdException {
  String fid;
  InstallationTokenResult installationTokenResult;
  try {
    fid = Tasks.await(firebaseInstallationsApi.getId());
    // No need to force refresh token.
    installationTokenResult = Tasks.await(firebaseInstallationsApi.getToken(false));
  } catch (ExecutionException | InterruptedException e) {
    throw new SetCustomInstallationIdException(
        Status.CLIENT_ERROR, "Failed to get Firebase installation ID and token");
  }

  boolean firstUpdateCacheResult =
      localCache.insertOrUpdateCacheEntry(
          CustomInstallationIdCacheEntryValue.create(
              "", fid, CustomInstallationIdCache.CacheStatus.PENDING_CLEAR));

  if (!firstUpdateCacheResult) {
    throw new SetCustomInstallationIdException(
        Status.CLIENT_ERROR, "Failed to update client side cache");
  }

  Code backendRequestResult =
      backendServiceClient.clearCustomInstallationId(
          Utils.getProjectNumberFromAppId(firebaseApp.getOptions().getApplicationId()),
          firebaseApp.getOptions().getApiKey(),
          fid,
          installationTokenResult.getToken());

  boolean finalUpdateCacheResult;
  switch (backendRequestResult) {
    case OK:
      finalUpdateCacheResult = localCache.clear();
      break;
    case UNAUTHORIZED:
      throw new SetCustomInstallationIdException(
          Status.CLIENT_ERROR, "Instance id token is invalid.");
    case HTTP_CLIENT_ERROR:
      throw new SetCustomInstallationIdException(Status.CLIENT_ERROR, "Http client error(4xx)");
    case NETWORK_ERROR:
    case SERVER_ERROR:
    default:
      // These are considered retryable errors, so not to clean up the cache.
      throw new SetCustomInstallationIdException(Status.BACKEND_ERROR);
  }

  if (finalUpdateCacheResult) {
    return null;
  } else {
    throw new SetCustomInstallationIdException(
        Status.CLIENT_ERROR, "Failed to update client side cache");
  }
}