com.google.android.gms.tasks.Tasks Java Examples

The following examples show how to use com.google.android.gms.tasks.Tasks. 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: FirebaseMultiQuery.java    From white-label-event-app with Apache License 2.0 7 votes vote down vote up
public Task<Map<DatabaseReference, DataSnapshot>> start() {
    // Create a Task<DataSnapshot> to trigger in response to each database listener.
    //
    final ArrayList<Task<DataSnapshot>> tasks = new ArrayList<>(refs.size());
    for (final DatabaseReference ref : refs) {
        final TaskCompletionSource<DataSnapshot> source = new TaskCompletionSource<>();
        final ValueEventListener listener = new MyValueEventListener(ref, source);
        ref.addListenerForSingleValueEvent(listener);
        listeners.put(ref, listener);
        tasks.add(source.getTask());
    }

    // Return a single Task that triggers when all queries are complete.  It contains
    // a map of all original DatabaseReferences originally given here to their resulting
    // DataSnapshot.
    //
    return Tasks.whenAll(tasks).continueWith(new Continuation<Void, Map<DatabaseReference, DataSnapshot>>() {
        @Override
        public Map<DatabaseReference, DataSnapshot> then(@NonNull Task<Void> task) throws Exception {
            task.getResult();
            return new HashMap<>(snaps);
        }
    });
}
 
Example #2
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 #3
Source File: SearchEngine.java    From mlkit-material-android with Apache License 2.0 6 votes vote down vote up
public void search(DetectedObject object, SearchResultListener listener) {
  // Crops the object image out of the full image is expensive, so do it off the UI thread.
  Tasks.call(requestCreationExecutor, () -> createRequest(object))
      .addOnSuccessListener(productRequest -> searchRequestQueue.add(productRequest.setTag(TAG)))
      .addOnFailureListener(
          e -> {
            Log.e(TAG, "Failed to create product search request!", e);
            // Remove the below dummy code after your own product search backed hooked up.
            List<Product> productList = new ArrayList<>();
            for (int i = 0; i < 8; i++) {
              productList.add(
                  new Product(/* imageUrl= */ "", "Product title " + i, "Product subtitle " + i));
            }
            listener.onSearchCompleted(object, productList);
          });
}
 
Example #4
Source File: FirebaseRemoteConfigTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void fetchAndActivate_fileWriteFails_doesNotClearFetchedAndReturnsFalse() {
  loadFetchHandlerWithResponse();
  loadCacheWithConfig(mockFetchedCache, secondFetchedContainer);
  loadCacheWithConfig(mockActivatedCache, firstFetchedContainer);

  when(mockActivatedCache.put(secondFetchedContainer))
      .thenReturn(Tasks.forException(new IOException("Should have handled disk error.")));

  Task<Boolean> task = frc.fetchAndActivate();

  assertWithMessage("fetchAndActivate() succeeded even though file write failed!")
      .that(getTaskResult(task))
      .isFalse();

  verify(mockActivatedCache).put(secondFetchedContainer);
  verify(mockFetchedCache, never()).clear();
}
 
Example #5
Source File: DriveServiceHelper.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a text file in the user's My Drive folder and returns its file ID.
 */
public Task<String> createFile() {
    return Tasks.call(mExecutor, () -> {
            File metadata = new File()
                    .setParents(Collections.singletonList("root"))
                    .setMimeType("text/plain")
                    .setName("Untitled file");

            File googleFile = mDriveService.files().create(metadata).execute();
            if (googleFile == null) {
                throw new IOException("Null result when requesting file creation.");
            }

            return googleFile.getId();
        });
}
 
Example #6
Source File: CallTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitError() {
  FirebaseFunctions functions = FirebaseFunctions.getInstance(app);

  HttpsCallableReference function = functions.getHttpsCallable("explicitErrorTest");
  Task<HttpsCallableResult> result = function.call();
  ExecutionException exe = assertThrows(ExecutionException.class, () -> Tasks.await(result));
  Throwable cause = exe.getCause();
  assertTrue(cause.toString(), cause instanceof FirebaseFunctionsException);
  FirebaseFunctionsException ffe = (FirebaseFunctionsException) cause;
  assertEquals(Code.OUT_OF_RANGE, ffe.getCode());
  assertEquals("explicit nope", ffe.getMessage());
  assertNotNull(ffe.getDetails());
  assertTrue(ffe.getDetails().getClass().getCanonicalName(), ffe.getDetails() instanceof Map);
  Map<?, ?> details = (Map<?, ?>) ffe.getDetails();
  assertEquals(10, details.get("start"));
  assertEquals(20, details.get("end"));
  assertEquals(30L, details.get("long"));
}
 
Example #7
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 #8
Source File: DriveServiceHelper.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Opens the file identified by {@code fileId} and returns a {@link Pair} of its name and
 * contents.
 */
public Task<Pair<String, String>> readFile(String fileId) {
    return Tasks.call(mExecutor, () -> {
            // Retrieve the metadata as a File object.
            File metadata = mDriveService.files().get(fileId).execute();
            String name = metadata.getName();

            // Stream the file contents to a String.
            try (InputStream is = mDriveService.files().get(fileId).executeMediaAsInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                String contents = stringBuilder.toString();

                return Pair.create(name, contents);
            }
        });
}
 
Example #9
Source File: IntegrationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void streamFile() throws ExecutionException, InterruptedException, IOException {
  TaskSnapshot streamTask = Tasks.await(getReference("download.dat").getStream());

  byte[] data = new byte[255];

  InputStream stream = streamTask.getStream();
  long totalBytesRead = 0;
  long currentBytesRead;

  while ((currentBytesRead = stream.read(data)) != -1) {
    totalBytesRead += currentBytesRead;
  }

  assertThat(totalBytesRead).isEqualTo(LARGE_FILE_SIZE_BYTES);
}
 
Example #10
Source File: SolutionCounters.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public Task<Void> createCounter(final DocumentReference ref, final int numShards) {
    // Initialize the counter document, then initialize each shard.
    return ref.set(new Counter(numShards))
            .continueWithTask(new Continuation<Void, Task<Void>>() {
                @Override
                public Task<Void> then(@NonNull Task<Void> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    List<Task<Void>> tasks = new ArrayList<>();

                    // Initialize each shard with count=0
                    for (int i = 0; i < numShards; i++) {
                        Task<Void> makeShard = ref.collection("shards")
                                .document(String.valueOf(i))
                                .set(new Shard(0));

                        tasks.add(makeShard);
                    }

                    return Tasks.whenAll(tasks);
                }
            });
}
 
Example #11
Source File: CrashlyticsController.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Send App Exception events to Firebase Analytics. FA records the event asynchronously, so this
 * method returns a Task in case the caller wants to verify that the event was recorded by FA and
 * will not be lost.
 */
private Task<Void> logAnalyticsAppExceptionEvents() {
  final List<Task<Void>> events = new ArrayList<>();

  final File[] appExceptionMarkers = listAppExceptionMarkerFiles();
  for (File markerFile : appExceptionMarkers) {
    try {
      final long timestamp =
          Long.parseLong(markerFile.getName().substring(APP_EXCEPTION_MARKER_PREFIX.length()));
      events.add(logAnalyticsAppExceptionEvent(timestamp));
    } catch (NumberFormatException nfe) {
      Logger.getLogger().d("Could not parse timestamp from file " + markerFile.getName());
    }
    markerFile.delete();
  }

  return Tasks.whenAll(events);
}
 
Example #12
Source File: DataTransportCrashlyticsReportSenderTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendReportsSuccessful() throws Exception {
  doAnswer(callbackAnswer(null)).when(mockTransport).schedule(any(), any());

  final CrashlyticsReportWithSessionId report1 = mockReportWithSessionId();
  final CrashlyticsReportWithSessionId report2 = mockReportWithSessionId();

  final Task<CrashlyticsReportWithSessionId> send1 = reportSender.sendReport(report1);
  final Task<CrashlyticsReportWithSessionId> send2 = reportSender.sendReport(report2);

  try {
    Tasks.await(send1);
    Tasks.await(send2);
  } catch (ExecutionException e) {
    // Allow this to fall through
  }

  assertTrue(send1.isSuccessful());
  assertEquals(report1, send1.getResult());
  assertTrue(send2.isSuccessful());
  assertEquals(report2, send2.getResult());
}
 
Example #13
Source File: DataTransportCrashlyticsReportSenderTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendReportsFailure() throws Exception {
  final Exception ex = new Exception("fail");
  doAnswer(callbackAnswer(ex)).when(mockTransport).schedule(any(), any());

  final CrashlyticsReportWithSessionId report1 = mockReportWithSessionId();
  final CrashlyticsReportWithSessionId report2 = mockReportWithSessionId();

  final Task<CrashlyticsReportWithSessionId> send1 = reportSender.sendReport(report1);
  final Task<CrashlyticsReportWithSessionId> send2 = reportSender.sendReport(report2);

  try {
    Tasks.await(send1);
    Tasks.await(send2);
  } catch (ExecutionException e) {
    // Allow this to fall through
  }

  assertFalse(send1.isSuccessful());
  assertEquals(ex, send1.getException());
  assertFalse(send2.isSuccessful());
  assertEquals(ex, send2.getException());
}
 
Example #14
Source File: DataTransportCrashlyticsReportSenderTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendReports_oneSuccessOneFail() throws Exception {
  final Exception ex = new Exception("fail");
  doAnswer(callbackAnswer(null))
      .doAnswer(callbackAnswer(ex))
      .when(mockTransport)
      .schedule(any(), any());

  final CrashlyticsReportWithSessionId report1 = mockReportWithSessionId();
  final CrashlyticsReportWithSessionId report2 = mockReportWithSessionId();

  final Task<CrashlyticsReportWithSessionId> send1 = reportSender.sendReport(report1);
  final Task<CrashlyticsReportWithSessionId> send2 = reportSender.sendReport(report2);

  try {
    Tasks.await(send1);
    Tasks.await(send2);
  } catch (ExecutionException e) {
    // Allow this to fall through
  }

  assertTrue(send1.isSuccessful());
  assertEquals(report1, send1.getResult());
  assertFalse(send2.isSuccessful());
  assertEquals(ex, send2.getException());
}
 
Example #15
Source File: FieldsTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testNestedFieldsCanBeUsedInQueryFilters() {
  Map<String, Object> docs =
      map("1", nestedObject(300), "2", nestedObject(100), "3", nestedObject(200));
  // inequality adds implicit sort on field
  List<Map<String, Object>> expected = Arrays.asList(nestedObject(200), nestedObject(300));
  CollectionReference collection = testCollection();
  List<Task<Void>> tasks = new ArrayList<>();
  for (Map.Entry<String, Object> entry : docs.entrySet()) {
    tasks.add(collection.document(entry.getKey()).set(entry.getValue()));
  }
  waitFor(Tasks.whenAll(tasks));
  Query query = collection.whereGreaterThanOrEqualTo("metadata.createdAt", 200);
  QuerySnapshot res = waitFor(query.get());
  assertEquals(expected, querySnapshotToValues(res));
}
 
Example #16
Source File: FirebaseRemoteConfig.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link Task} representing the initialization status of this Firebase Remote Config
 * instance.
 */
@NonNull
public Task<FirebaseRemoteConfigInfo> ensureInitialized() {
  Task<ConfigContainer> activatedConfigsTask = activatedConfigsCache.get();
  Task<ConfigContainer> defaultsConfigsTask = defaultConfigsCache.get();
  Task<ConfigContainer> fetchedConfigsTask = fetchedConfigsCache.get();
  Task<FirebaseRemoteConfigInfo> metadataTask = Tasks.call(executor, this::getInfo);
  Task<String> installationIdTask = firebaseInstallations.getId();
  Task<InstallationTokenResult> installationTokenTask = firebaseInstallations.getToken(false);

  return Tasks.whenAllComplete(
          activatedConfigsTask,
          defaultsConfigsTask,
          fetchedConfigsTask,
          metadataTask,
          installationIdTask,
          installationTokenTask)
      .continueWith(executor, (unusedListOfCompletedTasks) -> metadataTask.getResult());
}
 
Example #17
Source File: CallTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testData() throws InterruptedException, ExecutionException {
  FirebaseFunctions functions = FirebaseFunctions.getInstance(app);

  Map<String, Object> params = new HashMap<>();
  params.put("bool", true);
  params.put("int", 2);
  params.put("long", 3L);
  params.put("string", "four");
  params.put("array", Arrays.asList(5, 6));
  params.put("null", null);

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

  assertTrue(actual instanceof Map);
  Map<String, ?> map = (Map<String, ?>) actual;
  assertEquals("stub response", map.get("message"));
  assertEquals(42, map.get("code"));
  assertEquals(420L, map.get("long"));
}
 
Example #18
Source File: NumericTransformsTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleDoubleIncrements() throws ExecutionException, InterruptedException {
  writeInitialData(map("sum", 0.0D));

  Tasks.await(docRef.getFirestore().disableNetwork());

  docRef.update("sum", FieldValue.increment(0.1D));
  docRef.update("sum", FieldValue.increment(0.01D));
  docRef.update("sum", FieldValue.increment(0.001D));

  DocumentSnapshot snap = accumulator.awaitLocalEvent();
  assertEquals(0.1D, snap.getDouble("sum"), DOUBLE_EPSILON);
  snap = accumulator.awaitLocalEvent();
  assertEquals(0.11D, snap.getDouble("sum"), DOUBLE_EPSILON);
  snap = accumulator.awaitLocalEvent();
  assertEquals(0.111D, snap.getDouble("sum"), DOUBLE_EPSILON);

  Tasks.await(docRef.getFirestore().enableNetwork());

  snap = accumulator.awaitRemoteEvent();
  assertEquals(0.111D, snap.getDouble("sum"), DOUBLE_EPSILON);
}
 
Example #19
Source File: CallTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeout() {
  FirebaseFunctions functions = FirebaseFunctions.getInstance(app);

  HttpsCallableReference function =
      functions.getHttpsCallable("timeoutTest").withTimeout(10, TimeUnit.MILLISECONDS);
  assertEquals(10, function.getTimeout());
  Task<HttpsCallableResult> result = function.call();
  ExecutionException exe = assertThrows(ExecutionException.class, () -> Tasks.await(result));
  Throwable cause = exe.getCause();
  assertTrue(cause.toString(), cause instanceof FirebaseFunctionsException);
  FirebaseFunctionsException ffe = (FirebaseFunctionsException) cause;
  assertEquals(Code.DEADLINE_EXCEEDED, ffe.getCode());
  assertEquals("DEADLINE_EXCEEDED", ffe.getMessage());
  assertNull(ffe.getDetails());
}
 
Example #20
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 #21
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 #22
Source File: FirebaseRemoteConfigTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void activateFetched_hasNoAbtExperiments_sendsEmptyListToAbt() throws Exception {
  ConfigContainer containerWithNoAbtExperiments =
      ConfigContainer.newBuilder().withFetchTime(new Date(1000L)).build();
  loadCacheWithConfig(mockFetchedCache, containerWithNoAbtExperiments);

  // When the fetched values are activated, they should be put into the activated cache.
  when(mockActivatedCache.putWithoutWaitingForDiskWrite(containerWithNoAbtExperiments))
      .thenReturn(Tasks.forResult(containerWithNoAbtExperiments));

  assertWithMessage("activateFetched() failed!").that(frc.activateFetched()).isTrue();

  verify(mockFirebaseAbt).replaceAllExperiments(ImmutableList.of());
}
 
Example #23
Source File: PinFileActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private void pinFile(final DriveFile file) {
    // [START drive_android_pin_file]
    Task<Metadata> pinFileTask = getDriveResourceClient().getMetadata(file).continueWithTask(
            task -> {
                Metadata metadata = task.getResult();
                if (!metadata.isPinnable()) {
                    showMessage(getString(R.string.file_not_pinnable));
                    return Tasks.forResult(metadata);
                }
                if (metadata.isPinned()) {
                    showMessage(getString(R.string.file_already_pinned));
                    return Tasks.forResult(metadata);
                }
                MetadataChangeSet changeSet =
                        new MetadataChangeSet.Builder().setPinned(true).build();
                return getDriveResourceClient().updateMetadata(file, changeSet);
            });
    // [END drive_android_pin_file]
    // [START drive_android_pin_file_completion]
    pinFileTask
            .addOnSuccessListener(this,
                    metadata -> {
                        showMessage(getString(R.string.metadata_updated));
                        finish();
                    })
            .addOnFailureListener(this, e -> {
                Log.e(TAG, "Unable to update metadata", e);
                showMessage(getString(R.string.update_failed));
                finish();
            });
    // [END drive_android_pin_file_completion]
}
 
Example #24
Source File: ConfigCacheClientTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void get_firstTwoFileReadsFail_readsFileAndSetsCacheThreeTimes() throws Exception {
  doThrow(IO_EXCEPTION).when(mockStorageClient).read();
  assertThrows(ExecutionException.class, () -> Tasks.await(cacheClient.get()));
  assertThrows(ExecutionException.class, () -> Tasks.await(cacheClient.get()));

  doReturn(configContainer).when(mockStorageClient).read();
  for (int getCallIndex = 0; getCallIndex < 5; getCallIndex++) {
    assertThat(Tasks.await(cacheClient.get())).isEqualTo(configContainer);
  }

  // Three file reads: 2 failures and 1 success.
  verify(mockStorageClient, times(3)).read();
}
 
Example #25
Source File: ConfigCacheClientTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void get_hasNoCachedValueAndFileReadFails_throwsIOException() throws Exception {
  when(mockStorageClient.read()).thenThrow(IO_EXCEPTION);

  Task<ConfigContainer> getTask = cacheClient.get();
  assertThrows(ExecutionException.class, () -> Tasks.await(getTask));

  assertThat(getTask.getException()).isInstanceOf(IOException.class);
}
 
Example #26
Source File: ConfigFetchHandlerTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  directExecutor = MoreExecutors.directExecutor();
  context = RuntimeEnvironment.application.getApplicationContext();
  mockClock = new MockClock(0L);
  metadataClient =
      new ConfigMetadataClient(context.getSharedPreferences("test_file", Context.MODE_PRIVATE));

  loadBackendApiClient();
  loadInstallationIdAndAuthToken();

  /*
   * Every fetch starts with a call to retrieve the cached fetch values. Return successfully in
   * the base case.
   */
  when(mockFetchedCache.get()).thenReturn(Tasks.forResult(null));

  // Assume there is no analytics SDK for most of the tests.
  fetchHandler = getNewFetchHandler(/*analyticsConnector=*/ null);

  firstFetchedContainer =
      ConfigContainer.newBuilder()
          .replaceConfigsWith(
              new JSONObject(ImmutableMap.of("string_param", "string_value", "long_param", "1L")))
          .withFetchTime(FIRST_FETCH_TIME)
          .build();

  secondFetchedContainer =
      ConfigContainer.newBuilder()
          .replaceConfigsWith(
              new JSONObject(
                  ImmutableMap.of("string_param", "string_value", "double_param", "0.1")))
          .withFetchTime(SECOND_FETCH_TIME)
          .build();
}
 
Example #27
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 #28
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 #29
Source File: CallTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingResult() {
  FirebaseFunctions functions = FirebaseFunctions.getInstance(app);

  HttpsCallableReference function = functions.getHttpsCallable("missingResultTest");
  Task<HttpsCallableResult> result = function.call(null);
  ExecutionException exe = assertThrows(ExecutionException.class, () -> Tasks.await(result));
  Throwable cause = exe.getCause();
  assertTrue(cause.toString(), cause instanceof FirebaseFunctionsException);
  FirebaseFunctionsException ffe = (FirebaseFunctionsException) cause;
  assertEquals(Code.INTERNAL, ffe.getCode());
  assertEquals("Response is missing data field.", ffe.getMessage());
  assertNull(ffe.getDetails());
}
 
Example #30
Source File: FirebaseRemoteConfig.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes all activated, fetched and defaults configs and resets all Firebase Remote Config
 * settings.
 *
 * @return {@link Task} representing the {@code clear} call.
 */
@NonNull
public Task<Void> reset() {
  // Use a Task to avoid throwing potential file I/O errors to the caller and because
  // frcMetadata's clear call is blocking.
  return Tasks.call(
      executor,
      () -> {
        activatedConfigsCache.clear();
        fetchedConfigsCache.clear();
        defaultConfigsCache.clear();
        frcMetadata.clear();
        return null;
      });
}