com.google.firebase.firestore.FieldValue Java Examples

The following examples show how to use com.google.firebase.firestore.FieldValue. 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: MutationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppliesLocalServerTimestampTransformsToDocuments() {
  Map<String, Object> data = map("foo", map("bar", "bar-value"), "baz", "baz-value");
  Document baseDoc = doc("collection/key", 0, data);

  Timestamp timestamp = Timestamp.now();
  Mutation transform =
      transformMutation("collection/key", map("foo.bar", FieldValue.serverTimestamp()));
  MaybeDocument transformedDoc = transform.applyToLocalView(baseDoc, baseDoc, timestamp);

  // Server timestamps aren't parsed, so we manually insert it.
  ObjectValue expectedData =
      wrapObject(map("foo", map("bar", "<server-timestamp>"), "baz", "baz-value"));
  Value fieldValue = ServerTimestamps.valueOf(timestamp, wrap("bar-value"));
  expectedData = expectedData.toBuilder().set(field("foo.bar"), fieldValue).build();

  Document expectedDoc =
      new Document(
          key("collection/key"),
          version(0),
          expectedData,
          Document.DocumentState.LOCAL_MUTATIONS);
  assertEquals(expectedDoc, transformedDoc);
}
 
Example #2
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppliesServerAckedIncrementTransformToDocuments() {
  Map<String, Object> data = map("sum", 1);
  Document baseDoc = doc("collection/key", 0, data);

  Mutation transform = transformMutation("collection/key", map("sum", FieldValue.increment(2)));
  MutationResult mutationResult =
      new MutationResult(version(1), Collections.singletonList(wrap(3L)));

  MaybeDocument transformedDoc = transform.applyToRemoteDocument(baseDoc, mutationResult);

  Map<String, Object> expectedData = map("sum", 3L);
  assertEquals(
      doc("collection/key", 1, expectedData, Document.DocumentState.COMMITTED_MUTATIONS),
      transformedDoc);
}
 
Example #3
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateArrayUnionTransform() {
  TransformMutation transform =
      transformMutation(
          "collection/key",
          map(
              "a",
              FieldValue.arrayUnion("tag"),
              "bar.baz",
              FieldValue.arrayUnion(true, map("nested", map("a", Arrays.asList(1, 2))))));
  assertEquals(2, transform.getFieldTransforms().size());

  FieldTransform first = transform.getFieldTransforms().get(0);
  assertEquals(field("a"), first.getFieldPath());
  assertEquals(
      new ArrayTransformOperation.Union(Collections.singletonList(wrap("tag"))),
      first.getOperation());

  FieldTransform second = transform.getFieldTransforms().get(1);
  assertEquals(field("bar.baz"), second.getFieldPath());
  assertEquals(
      new ArrayTransformOperation.Union(
          Arrays.asList(wrap(true), wrap(map("nested", map("a", Arrays.asList(1, 2)))))),
      second.getOperation());
}
 
Example #4
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppliesIncrementWithoutUnderflow() {
  Map<String, Object> baseDoc =
      map(
          "a",
          Long.MIN_VALUE + 1,
          "b",
          Long.MIN_VALUE + 1,
          "c",
          Long.MIN_VALUE,
          "d",
          Long.MIN_VALUE);
  Map<String, Object> transform =
      map(
          "a", FieldValue.increment(-1),
          "b", FieldValue.increment(Long.MIN_VALUE),
          "c", FieldValue.increment(-1),
          "d", FieldValue.increment(Long.MIN_VALUE));
  Map<String, Object> expected =
      map("a", Long.MIN_VALUE, "b", Long.MIN_VALUE, "c", Long.MIN_VALUE, "d", Long.MIN_VALUE);
  verifyTransform(baseDoc, transform, expected);
}
 
Example #5
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppliesIncrementWithoutOverflow() {
  Map<String, Object> baseDoc =
      map(
          "a",
          Long.MAX_VALUE - 1,
          "b",
          Long.MAX_VALUE - 1,
          "c",
          Long.MAX_VALUE,
          "d",
          Long.MAX_VALUE);
  Map<String, Object> transform =
      map(
          "a", FieldValue.increment(1),
          "b", FieldValue.increment(Long.MAX_VALUE),
          "c", FieldValue.increment(1),
          "d", FieldValue.increment(Long.MAX_VALUE));
  Map<String, Object> expected =
      map("a", Long.MAX_VALUE, "b", Long.MAX_VALUE, "c", Long.MAX_VALUE, "d", Long.MAX_VALUE);
  verifyTransform(baseDoc, transform, expected);
}
 
Example #6
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppliesServerAckedArrayTransformsToDocuments() {
  Map<String, Object> data =
      map("array1", Arrays.asList(1, 2), "array2", Arrays.asList("a", "b"));
  Document baseDoc = doc("collection/key", 0, data);
  Mutation transform =
      transformMutation(
          "collection/key",
          map("array1", FieldValue.arrayUnion(2, 3), "array2", FieldValue.arrayRemove("a", "c")));

  // Server just sends null transform results for array operations.
  MutationResult mutationResult =
      new MutationResult(version(1), Arrays.asList(wrap(null), wrap(null)));
  MaybeDocument transformedDoc = transform.applyToRemoteDocument(baseDoc, mutationResult);

  Map<String, Object> expectedData =
      map("array1", Arrays.asList(1, 2, 3), "array2", Arrays.asList("b"));
  assertEquals(
      doc("collection/key", 1, expectedData, Document.DocumentState.COMMITTED_MUTATIONS),
      transformedDoc);
}
 
Example #7
Source File: LocalStoreTestCase.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandlesPatchMutationWithTransformThenRemoteEvent() {
  Query query = Query.atPath(ResourcePath.fromString("foo"));
  allocateQuery(query);
  assertTargetId(2);

  writeMutations(
      asList(
          patchMutation("foo/bar", map()),
          transformMutation("foo/bar", map("sum", FieldValue.increment(1)))));
  assertChanged(deletedDoc("foo/bar", 0));
  assertNotContains("foo/bar");

  // Note: This test reflects the current behavior, but it may be preferable to replay the
  // mutation once we receive the first value from the remote event.

  applyRemoteEvent(addedRemoteEvent(doc("foo/bar", 1, map("sum", 1337)), asList(2), emptyList()));
  assertChanged(doc("foo/bar", 1, map("sum", 1), Document.DocumentState.LOCAL_MUTATIONS));
  assertContains(doc("foo/bar", 1, map("sum", 1), Document.DocumentState.LOCAL_MUTATIONS));
}
 
Example #8
Source File: LocalStoreTestCase.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandlesMergeMutationWithTransformThenRemoteEvent() {
  Query query = Query.atPath(ResourcePath.fromString("foo"));
  allocateQuery(query);
  assertTargetId(2);

  writeMutations(
      asList(
          patchMutation("foo/bar", map(), Collections.emptyList()),
          transformMutation("foo/bar", map("sum", FieldValue.increment(1)))));
  assertChanged(doc("foo/bar", 0, map("sum", 1), Document.DocumentState.LOCAL_MUTATIONS));
  assertContains(doc("foo/bar", 0, map("sum", 1), Document.DocumentState.LOCAL_MUTATIONS));

  applyRemoteEvent(addedRemoteEvent(doc("foo/bar", 1, map("sum", 1337)), asList(2), emptyList()));
  assertChanged(doc("foo/bar", 1, map("sum", 1), Document.DocumentState.LOCAL_MUTATIONS));
  assertContains(doc("foo/bar", 1, map("sum", 1), Document.DocumentState.LOCAL_MUTATIONS));
}
 
Example #9
Source File: EventDetailsActivity.java    From NaviBee with GNU General Public License v3.0 6 votes vote down vote up
private void quitEvent() {
    Map<String, Object> updates = new HashMap<>();
    updates.put("users." + uid, FieldValue.delete());
    db.collection("events").document(eid).update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                // TODO: Task completed successfully
                finish();
            } else {
                Snackbar.make(coordinatorLayout,
                        R.string.error_failed_to_connect_to_server,
                        Snackbar.LENGTH_SHORT).show();
            }
        }
    });
}
 
Example #10
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void updateWithServerTimestamp() {
    // [START update_with_server_timestamp]
    DocumentReference docRef = db.collection("objects").document("some-id");

    // Update the timestamp field with the value from the server
    Map<String,Object> updates = new HashMap<>();
    updates.put("timestamp", FieldValue.serverTimestamp());

    docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
        // [START_EXCLUDE]
        @Override
        public void onComplete(@NonNull Task<Void> task) {}
        // [START_EXCLUDE]
    });
    // [END update_with_server_timestamp]
}
 
Example #11
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void updateDeleteField() {
    // [START update_delete_field]
    DocumentReference docRef = db.collection("cities").document("BJ");

    // Remove the 'capital' field from the document
    Map<String,Object> updates = new HashMap<>();
    updates.put("capital", FieldValue.delete());

    docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
        // [START_EXCLUDE]
        @Override
        public void onComplete(@NonNull Task<Void> task) {}
        // [START_EXCLUDE]
    });
    // [END update_delete_field]
}
 
Example #12
Source File: MainActivity.java    From Hify with MIT License 6 votes vote down vote up
private void updateToken() {

        final String token_id = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, MODE_PRIVATE).getString("regId","");
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token_ids", FieldValue.arrayUnion(token_id));

        if(isOnline()) {

            firestore.collection("Users").document(currentuser.getUid()).update(tokenMap)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d("TOKEN", token_id);
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d("Error Token", e.getMessage());
                        }
                    });

        }
    }
 
Example #13
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformWithPartiallyOverlappingElements() {
  // Union objects that partially overlap an existing object.
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, map("a", "b", "c", "d")));
  Map<String, Object> transform =
      map("array", FieldValue.arrayUnion(map("a", "b"), map("c", "d")));
  Map<String, Object> expected =
      map("array", Arrays.asList(1, map("a", "b", "c", "d"), map("a", "b"), map("c", "d")));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #14
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayRemoveTransformToNonArrayField() {
  Map<String, Object> baseDoc = map("nonArray", 42);
  Map<String, Object> transform = map("nonArray", FieldValue.arrayRemove(1, 2));
  Map<String, Object> expected = map("nonArray", Collections.emptyList());
  verifyTransform(baseDoc, transform, expected);
}
 
Example #15
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayRemoveTransformWithNonExistingElements() {
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, 3));
  Map<String, Object> transform = map("array", FieldValue.arrayRemove(2, 4));
  Map<String, Object> expected = map("array", Arrays.asList(1, 3));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #16
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayRemoveTransformWithExistingElements() {
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, 2, 3, 4));
  Map<String, Object> transform = map("array", FieldValue.arrayRemove(1, 3));
  Map<String, Object> expected = map("array", Arrays.asList(2, 4));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #17
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayRemoveTransformToMissingField() {
  Map<String, Object> baseDoc = map();
  Map<String, Object> transform = map("missing", FieldValue.arrayRemove(1, 2));
  Map<String, Object> expected = map("missing", Collections.emptyList());
  verifyTransform(baseDoc, transform, expected);
}
 
Example #18
Source File: MainActivity.java    From Hify with MIT License 5 votes vote down vote up
public void logout() {
    performUploadTask();
    final ProgressDialog mDialog = new ProgressDialog(this);
    mDialog.setIndeterminate(true);
    mDialog.setMessage("Logging you out...");
    mDialog.setCancelable(false);
    mDialog.setCanceledOnTouchOutside(false);
    mDialog.show();

    SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, MODE_PRIVATE);

    Map<String, Object> tokenRemove = new HashMap<>();
    tokenRemove.put("token_ids", FieldValue.arrayRemove(pref.getString("regId","")));

    firestore.collection("Users").document(userId).update(tokenRemove).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            userHelper.deleteContact(1);
            mAuth.signOut();
            LoginActivity.startActivityy(MainActivity.this);
            mDialog.dismiss();
            finish();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toasty.error(MainActivity.this, "Error logging out", Toasty.LENGTH_SHORT,true).show();
            mDialog.dismiss();
            Log.e("Logout Error", e.getMessage());
        }
    });

}
 
Example #19
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayRemoveTransformWithNonPrimitiveElements() {
  // Remove nested object values (one existing, one not).
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, map("a", "b")));
  Map<String, Object> transform =
      map("array", FieldValue.arrayRemove(map("a", "b"), map("c", "d")));
  Map<String, Object> expected = map("array", Arrays.asList(1));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #20
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerTimestampBaseValue() {
  Map<String, Object> allValues = map("time", "foo");
  allValues.put("nested", new HashMap<>(allValues));
  Document baseDoc = doc("collection/key", 0, allValues);

  Map<String, Object> allTransforms = map("time", FieldValue.serverTimestamp());
  allTransforms.put("nested", new HashMap<>(allTransforms));

  // Server timestamps are idempotent and don't have base values.
  Mutation transformMutation = transformMutation("collection/key", allTransforms);
  assertNull(transformMutation.extractBaseValue(baseDoc));
}
 
Example #21
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncrementTwice() {
  Document baseDoc = doc("collection/key", 0, map("sum", "0"));

  Map<String, Object> increment = map("sum", FieldValue.increment(1));
  Mutation transformMutation = transformMutation("collection/key", increment);

  MaybeDocument mutatedDoc =
      transformMutation.applyToLocalView(baseDoc, baseDoc, Timestamp.now());
  mutatedDoc = transformMutation.applyToLocalView(mutatedDoc, baseDoc, Timestamp.now());

  assertEquals(wrap(2L), ((Document) mutatedDoc).getField(field("sum")));
}
 
Example #22
Source File: ObservationMutationConverter.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> toMap(ImmutableList<ResponseDelta> responseDeltas) {
  ImmutableMap.Builder<String, Object> map = ImmutableMap.builder();
  for (ResponseDelta delta : responseDeltas) {
    map.put(
        delta.getFieldId(),
        delta
            .getNewResponse()
            .map(ObservationMutationConverter::toObject)
            .orElse(FieldValue.delete()));
  }
  return map.build();
}
 
Example #23
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void updateDocumentArray() {
    // [START update_document_array]
    DocumentReference washingtonRef = db.collection("cities").document("DC");

    // Atomically add a new region to the "regions" array field.
    washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia"));

    // Atomically remove a region from the "regions" array field.
    washingtonRef.update("regions", FieldValue.arrayRemove("east_coast"));
    // [END update_document_array]
}
 
Example #24
Source File: DocSnippets.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void updateDocumentIncrement() {
    // [START update_document_increment]
    DocumentReference washingtonRef = db.collection("cities").document("DC");

    // Atomically increment the population of the city by 50.
    washingtonRef.update("population", FieldValue.increment(50));
    // [END update_document_increment]
}
 
Example #25
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformWithDuplicateUnionElements() {
  // Duplicate entries in your union array should only be added once.
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, 3));
  Map<String, Object> transform = map("array", FieldValue.arrayUnion(2, 2));
  Map<String, Object> expected = map("array", Arrays.asList(1, 3, 2));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #26
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformWithDuplicateExistingElements() {
  // Duplicate entries in your existing array should be preserved.
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, 2, 2, 3));
  Map<String, Object> transform = map("array", FieldValue.arrayUnion(2));
  Map<String, Object> expected = map("array", Arrays.asList(1, 2, 2, 3));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #27
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformWithExistingElements() {
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, 3));
  Map<String, Object> transform = map("array", FieldValue.arrayUnion(1, 3));
  Map<String, Object> expected = map("array", Arrays.asList(1, 3));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #28
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformWithNonExistingElements() {
  Map<String, Object> baseDoc = map("array", Arrays.asList(1, 3));
  Map<String, Object> transform = map("array", FieldValue.arrayUnion(2, 4));
  Map<String, Object> expected = map("array", Arrays.asList(1, 3, 2, 4));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #29
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformToNonArrayField() {
  Map<String, Object> baseDoc = map("nonArray", 42);
  Map<String, Object> transform = map("nonArray", FieldValue.arrayUnion(1, 2));
  Map<String, Object> expected = map("nonArray", Arrays.asList(1, 2));
  verifyTransform(baseDoc, transform, expected);
}
 
Example #30
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesLocalArrayUnionTransformToMissingField() {
  Map<String, Object> baseDoc = map();
  Map<String, Object> transform = map("missing", FieldValue.arrayUnion(1, 2));
  Map<String, Object> expected = map("missing", Arrays.asList(1, 2));
  verifyTransform(baseDoc, transform, expected);
}