com.google.firebase.Timestamp Java Examples

The following examples show how to use com.google.firebase.Timestamp. 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: SQLiteTargetCache.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void saveTargetData(TargetData targetData) {
  int targetId = targetData.getTargetId();
  String canonicalId = targetData.getTarget().getCanonicalId();
  Timestamp version = targetData.getSnapshotVersion().getTimestamp();

  com.google.firebase.firestore.proto.Target targetProto =
      localSerializer.encodeTargetData(targetData);

  db.execute(
      "INSERT OR REPLACE INTO targets ("
          + "target_id, "
          + "canonical_id, "
          + "snapshot_version_seconds, "
          + "snapshot_version_nanos, "
          + "resume_token, "
          + "last_listen_sequence_number, "
          + "target_proto) "
          + "VALUES (?, ?, ?, ?, ?, ?, ?)",
      targetId,
      canonicalId,
      version.getSeconds(),
      version.getNanoseconds(),
      targetData.getResumeToken().toByteArray(),
      targetData.getSequenceNumber(),
      targetProto.toByteArray());
}
 
Example #2
Source File: LocalSerializerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodesDeletedDocumentAsMaybeDocument() {
  NoDocument deletedDoc = deletedDoc("some/path", 42);

  com.google.firebase.firestore.proto.MaybeDocument maybeDocProto =
      com.google.firebase.firestore.proto.MaybeDocument.newBuilder()
          .setNoDocument(
              com.google.firebase.firestore.proto.NoDocument.newBuilder()
                  .setName("projects/p/databases/d/documents/some/path")
                  .setReadTime(
                      com.google.protobuf.Timestamp.newBuilder().setSeconds(0).setNanos(42000)))
          .build();

  assertEquals(maybeDocProto, serializer.encodeMaybeDocument(deletedDoc));
  MaybeDocument decoded = serializer.decodeMaybeDocument(maybeDocProto);
  assertEquals(deletedDoc, decoded);
}
 
Example #3
Source File: LocalSerializerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodesDocumentAsMaybeDocument() {
  Document document = doc("some/path", 42, map("foo", "bar"));

  com.google.firebase.firestore.proto.MaybeDocument maybeDocProto =
      com.google.firebase.firestore.proto.MaybeDocument.newBuilder()
          .setDocument(
              com.google.firestore.v1.Document.newBuilder()
                  .setName("projects/p/databases/d/documents/some/path")
                  .putFields("foo", Value.newBuilder().setStringValue("bar").build())
                  .setUpdateTime(
                      com.google.protobuf.Timestamp.newBuilder().setSeconds(0).setNanos(42000)))
          .build();

  assertEquals(maybeDocProto, serializer.encodeMaybeDocument(document));
  MaybeDocument decoded = serializer.decodeMaybeDocument(maybeDocProto);
  assertEquals(document, decoded);
}
 
Example #4
Source File: QuerySnapshotTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testToObjects() {
  // Prevent NPE on trying to access non-existent settings on the mock.
  when(TestUtil.firestore().getFirestoreSettings())
      .thenReturn(new FirebaseFirestoreSettings.Builder().build());

  ObjectValue objectData =
      ObjectValue.fromMap(map("timestamp", ServerTimestamps.valueOf(Timestamp.now(), null)));
  QuerySnapshot foo = TestUtil.querySnapshot("foo", map(), map("a", objectData), true, false);

  List<POJO> docs = foo.toObjects(POJO.class);
  assertEquals(1, docs.size());
  assertNull(docs.get(0).timestamp);

  docs = foo.toObjects(POJO.class, ServerTimestampBehavior.ESTIMATE);
  assertEquals(1, docs.size());
  assertNotNull(docs.get(0).timestamp);
}
 
Example #5
Source File: TransformMutation.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public MaybeDocument applyToLocalView(
    @Nullable MaybeDocument maybeDoc, @Nullable MaybeDocument baseDoc, Timestamp localWriteTime) {
  verifyKeyMatches(maybeDoc);

  if (!this.getPrecondition().isValidFor(maybeDoc)) {
    return maybeDoc;
  }

  Document doc = requireDocument(maybeDoc);
  List<Value> transformResults = localTransformResults(localWriteTime, maybeDoc, baseDoc);
  ObjectValue newData = transformObject(doc.getData(), transformResults);
  return new Document(
      getKey(), doc.getVersion(), newData, Document.DocumentState.LOCAL_MUTATIONS);
}
 
Example #6
Source File: FieldsTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimestampsInSnapshotsLegacyBehaviorForTimestamps() {
  Timestamp timestamp = new Timestamp(100, 123456789);

  DocumentReference docRef = createDocWithTimestampsDisabled();
  waitFor(docRef.set(objectWithTimestamp(timestamp)));
  DocumentSnapshot snapshot = waitFor(docRef.get());
  Map<String, Object> data = snapshot.getData();

  assertThat(snapshot.get("timestamp")).isInstanceOf(Date.class);
  assertThat(data.get("timestamp")).isInstanceOf(Date.class);
  assertThat(snapshot.get("timestamp")).isEqualTo(timestamp.toDate());
  assertThat(data.get("timestamp")).isEqualTo(timestamp.toDate());

  assertThat(snapshot.get("nested.timestamp2")).isInstanceOf(Date.class);
  assertThat(snapshot.get("nested.timestamp2")).isEqualTo(timestamp.toDate());
  @SuppressWarnings("unchecked")
  Map<String, Object> nestedObject = (Map<String, Object>) data.get("nested");
  assertThat(nestedObject).isNotNull();
  assertThat(nestedObject.get("timestamp2")).isEqualTo(timestamp.toDate());
}
 
Example #7
Source File: ServerTimestampTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerTimestampsCanRetainPreviousValueThroughConsecutiveUpdates() {
  writeInitialData();
  waitFor(docRef.getFirestore().getClient().disableNetwork());
  accumulator.awaitRemoteEvent();

  docRef.update("a", FieldValue.serverTimestamp());
  DocumentSnapshot localSnapshot = accumulator.awaitLocalEvent();
  assertEquals(42L, localSnapshot.get("a", ServerTimestampBehavior.PREVIOUS));

  // include b=1 to ensure there's a change resulting in a new snapshot.
  docRef.update("a", FieldValue.serverTimestamp(), "b", 1);
  localSnapshot = accumulator.awaitLocalEvent();
  assertEquals(42L, localSnapshot.get("a", ServerTimestampBehavior.PREVIOUS));

  waitFor(docRef.getFirestore().getClient().enableNetwork());

  DocumentSnapshot remoteSnapshot = accumulator.awaitRemoteEvent();
  assertThat(remoteSnapshot.get("a")).isInstanceOf(Timestamp.class);
}
 
Example #8
Source File: ServerTimestampTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerTimestampsUsesPreviousValueFromLocalMutation() {
  writeInitialData();
  waitFor(docRef.getFirestore().getClient().disableNetwork());
  accumulator.awaitRemoteEvent();

  docRef.update("a", FieldValue.serverTimestamp());
  DocumentSnapshot localSnapshot = accumulator.awaitLocalEvent();
  assertEquals(42L, localSnapshot.get("a", ServerTimestampBehavior.PREVIOUS));

  docRef.update("a", 1337);
  accumulator.awaitLocalEvent();

  docRef.update("a", FieldValue.serverTimestamp());
  localSnapshot = accumulator.awaitLocalEvent();
  assertEquals(1337L, localSnapshot.get("a", ServerTimestampBehavior.PREVIOUS));

  waitFor(docRef.getFirestore().getClient().enableNetwork());

  DocumentSnapshot remoteSnapshot = accumulator.awaitRemoteEvent();
  assertThat(remoteSnapshot.get("a")).isInstanceOf(Timestamp.class);
}
 
Example #9
Source File: SQLiteTargetCache.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
void start() {
  // Store exactly one row in the table. If the row exists at all, it's the global metadata.
  int found =
      db.query(
              "SELECT highest_target_id, highest_listen_sequence_number, "
                  + "last_remote_snapshot_version_seconds, last_remote_snapshot_version_nanos, "
                  + "target_count FROM target_globals LIMIT 1")
          .first(
              row -> {
                highestTargetId = row.getInt(0);
                lastListenSequenceNumber = row.getInt(1);
                lastRemoteSnapshotVersion =
                    new SnapshotVersion(new Timestamp(row.getLong(2), row.getInt(3)));
                targetCount = row.getLong(4);
              });
  hardAssert(found == 1, "Missing target_globals entry");
}
 
Example #10
Source File: ServerTimestampTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerTimestampBehaviorOverloadsOfDocumentSnapshotGet() {
  writeInitialData();
  waitFor(docRef.update(updateData));
  DocumentSnapshot snap = accumulator.awaitLocalEvent();

  // Default behavior should return null timestamp (via any overload).
  assertNull(snap.get("when"));
  assertNull(snap.get(FieldPath.of("when")));
  assertNull(snap.get("when", Timestamp.class));
  assertNull(snap.get(FieldPath.of("when"), Timestamp.class));

  // Estimate should return a Timestamp object (via any overload).
  assertThat(snap.get("when", ServerTimestampBehavior.ESTIMATE)).isInstanceOf(Timestamp.class);
  assertThat(snap.get(FieldPath.of("when"), ServerTimestampBehavior.ESTIMATE))
      .isInstanceOf(Timestamp.class);
  assertThat(snap.get("when", Timestamp.class, ServerTimestampBehavior.ESTIMATE))
      .isInstanceOf(Timestamp.class);
  assertThat(snap.get(FieldPath.of("when"), Timestamp.class, ServerTimestampBehavior.ESTIMATE))
      .isInstanceOf(Timestamp.class);
}
 
Example #11
Source File: FieldsTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimestampsInSnapshots() {
  Timestamp originalTimestamp = new Timestamp(100, 123456789);
  // Timestamps are currently truncated to microseconds after being written to the database.
  Timestamp truncatedTimestamp =
      new Timestamp(
          originalTimestamp.getSeconds(), originalTimestamp.getNanoseconds() / 1000 * 1000);

  DocumentReference docRef = testCollection().document();
  waitFor(docRef.set(objectWithTimestamp(originalTimestamp)));
  DocumentSnapshot snapshot = waitFor(docRef.get());
  Map<String, Object> data = snapshot.getData();

  Timestamp readTimestamp = (Timestamp) snapshot.get("timestamp");
  assertThat(readTimestamp).isEqualTo(truncatedTimestamp);
  assertThat(readTimestamp).isEqualTo(data.get("timestamp"));

  Timestamp readNestedTimestamp = (Timestamp) snapshot.get("nested.timestamp2");
  assertThat(readNestedTimestamp).isEqualTo(truncatedTimestamp);
  @SuppressWarnings("unchecked")
  Map<String, Object> nestedObject = (Map<String, Object>) data.get("nested");
  assertThat(nestedObject.get("timestamp2")).isEqualTo(readNestedTimestamp);
}
 
Example #12
Source File: SQLiteRemoteDocumentCache.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public void add(MaybeDocument maybeDocument, SnapshotVersion readTime) {
  hardAssert(
      !readTime.equals(SnapshotVersion.NONE),
      "Cannot add document to the RemoteDocumentCache with a read time of zero");

  String path = pathForKey(maybeDocument.getKey());
  Timestamp timestamp = readTime.getTimestamp();
  MessageLite message = serializer.encodeMaybeDocument(maybeDocument);

  db.execute(
      "INSERT OR REPLACE INTO remote_documents "
          + "(path, read_time_seconds, read_time_nanos, contents) "
          + "VALUES (?, ?, ?, ?)",
      path,
      timestamp.getSeconds(),
      timestamp.getNanoseconds(),
      message.toByteArray());

  db.getIndexManager().addToCollectionParentIndex(maybeDocument.getKey().getPath().popLast());
}
 
Example #13
Source File: LocalSerializerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodesUnknownDocumentAsMaybeDocument() {
  UnknownDocument unknownDoc = unknownDoc("some/path", 42);

  com.google.firebase.firestore.proto.MaybeDocument maybeDocProto =
      com.google.firebase.firestore.proto.MaybeDocument.newBuilder()
          .setUnknownDocument(
              com.google.firebase.firestore.proto.UnknownDocument.newBuilder()
                  .setName("projects/p/databases/d/documents/some/path")
                  .setVersion(
                      com.google.protobuf.Timestamp.newBuilder().setSeconds(0).setNanos(42000)))
          .setHasCommittedMutations(true)
          .build();

  assertEquals(maybeDocProto, serializer.encodeMaybeDocument(unknownDoc));
  MaybeDocument decoded = serializer.decodeMaybeDocument(maybeDocProto);
  assertEquals(unknownDoc, decoded);
}
 
Example #14
Source File: WriteBatchTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCanWriteTheSameDocumentMultipleTimes() {
  DocumentReference doc = testDocument();
  EventAccumulator<DocumentSnapshot> accumulator = new EventAccumulator<>();
  doc.addSnapshotListener(MetadataChanges.INCLUDE, accumulator.listener());
  DocumentSnapshot initialSnap = accumulator.await();
  assertFalse(initialSnap.exists());

  waitFor(
      doc.getFirestore()
          .batch()
          .delete(doc)
          .set(doc, map("a", 1, "b", 1, "when", "when"))
          .update(doc, map("b", 2, "when", FieldValue.serverTimestamp()))
          .commit());

  DocumentSnapshot localSnap = accumulator.await();
  assertTrue(localSnap.getMetadata().hasPendingWrites());
  assertEquals(map("a", 1L, "b", 2L, "when", null), localSnap.getData());

  DocumentSnapshot serverSnap = accumulator.await();
  assertFalse(serverSnap.getMetadata().hasPendingWrites());
  Timestamp when = serverSnap.getTimestamp("when");
  assertNotNull(when);
  assertEquals(map("a", 1L, "b", 2L, "when", when), serverSnap.getData());
}
 
Example #15
Source File: FirestoreTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCanMergeServerTimestamps() {
  DocumentReference documentReference = testCollection("rooms").document("eros");
  Map<String, Object> initialValue = map("untouched", true);
  Map<String, Object> mergeData =
      map(
          "time",
          FieldValue.serverTimestamp(),
          "nested",
          map("time", FieldValue.serverTimestamp()));
  waitFor(documentReference.set(initialValue));
  waitFor(documentReference.set(mergeData, SetOptions.merge()));
  DocumentSnapshot doc = waitFor(documentReference.get());
  assertTrue(doc.getBoolean("untouched"));
  assertTrue(doc.get("time") instanceof Timestamp);
  assertTrue(doc.get("nested.time") instanceof Timestamp);
}
 
Example #16
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatchingDeletedDocumentsDoesNothing() {
  MaybeDocument baseDoc = deletedDoc("collection/key", 0);
  Mutation patch = patchMutation("collection/key", map("foo", "bar"));
  MaybeDocument patchedDoc = patch.applyToLocalView(baseDoc, baseDoc, Timestamp.now());
  assertEquals(baseDoc, patchedDoc);
}
 
Example #17
Source File: DefaultMessage.java    From demo-firebase-android with The Unlicense 5 votes vote down vote up
@Ignore
public DefaultMessage(String sender, String receiver, String body, Timestamp createdAt) {
    this.sender = sender;
    this.receiver = receiver;
    this.body = body;
    this.createdAt = createdAt;
}
 
Example #18
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T deserializeToClass(Object o, Class<T> clazz, DeserializeContext context) {
  if (o == null) {
    return null;
  } else if (clazz.isPrimitive()
      || Number.class.isAssignableFrom(clazz)
      || Boolean.class.isAssignableFrom(clazz)
      || Character.class.isAssignableFrom(clazz)) {
    return deserializeToPrimitive(o, clazz, context);
  } else if (String.class.isAssignableFrom(clazz)) {
    return (T) convertString(o, context);
  } else if (Date.class.isAssignableFrom(clazz)) {
    return (T) convertDate(o, context);
  } else if (Timestamp.class.isAssignableFrom(clazz)) {
    return (T) convertTimestamp(o, context);
  } else if (Blob.class.isAssignableFrom(clazz)) {
    return (T) convertBlob(o, context);
  } else if (GeoPoint.class.isAssignableFrom(clazz)) {
    return (T) convertGeoPoint(o, context);
  } else if (DocumentReference.class.isAssignableFrom(clazz)) {
    return (T) convertDocumentReference(o, context);
  } else if (clazz.isArray()) {
    throw deserializeError(
        context.errorPath, "Converting to Arrays is not supported, please use Lists instead");
  } else if (clazz.getTypeParameters().length > 0) {
    throw deserializeError(
        context.errorPath,
        "Class "
            + clazz.getName()
            + " has generic type parameters, please use GenericTypeIndicator instead");
  } else if (clazz.equals(Object.class)) {
    return (T) o;
  } else if (clazz.isEnum()) {
    return deserializeToEnum(o, clazz, context);
  } else {
    return convertBean(o, clazz, context);
  }
}
 
Example #19
Source File: UserDataReader.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private Value parseTimestamp(Timestamp timestamp) {
  // Firestore backend truncates precision down to microseconds. To ensure offline mode works
  // the same with regards to truncation, perform the truncation immediately without waiting for
  // the backend to do that.
  int truncatedNanoseconds = timestamp.getNanoseconds() / 1000 * 1000;

  return Value.newBuilder()
      .setTimestampValue(
          com.google.protobuf.Timestamp.newBuilder()
              .setSeconds(timestamp.getSeconds())
              .setNanos(truncatedNanoseconds))
      .build();
}
 
Example #20
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static Date convertDate(Object o, DeserializeContext context) {
  if (o instanceof Date) {
    return (Date) o;
  } else if (o instanceof Timestamp) {
    return ((Timestamp) o).toDate();
  } else {
    throw deserializeError(
        context.errorPath,
        "Failed to convert value of type " + o.getClass().getName() + " to Date");
  }
}
 
Example #21
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static Timestamp convertTimestamp(Object o, DeserializeContext context) {
  if (o instanceof Timestamp) {
    return (Timestamp) o;
  } else if (o instanceof Date) {
    return new Timestamp((Date) o);
  } else {
    throw deserializeError(
        context.errorPath,
        "Failed to convert value of type " + o.getClass().getName() + " to Timestamp");
  }
}
 
Example #22
Source File: MutationBatch.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public MutationBatch(
    int batchId,
    Timestamp localWriteTime,
    List<Mutation> baseMutations,
    List<Mutation> mutations) {
  hardAssert(!mutations.isEmpty(), "Cannot create an empty mutation batch");
  this.batchId = batchId;
  this.localWriteTime = localWriteTime;
  this.baseMutations = baseMutations;
  this.mutations = mutations;
}
 
Example #23
Source File: UserProfileModel.java    From openwebnet-android with MIT License 5 votes vote down vote up
private Date toDate(Object timestamp) {
    if (timestamp == null) {
        return null;
    } else if (timestamp instanceof Timestamp) {
        return ((Timestamp) timestamp).toDate();
    } else if (timestamp instanceof Date) {
        return (Date) timestamp;
    }
    throw new IllegalArgumentException("invalid timestamp");
}
 
Example #24
Source File: SQLiteTargetCacheTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetadataPersistedAcrossRestarts() {
  String name = "test-targetCache-restarts";

  SQLitePersistence db1 = PersistenceTestHelpers.createSQLitePersistence(name);
  TargetCache targetCache1 = db1.getTargetCache();
  assertEquals(0, targetCache1.getHighestListenSequenceNumber());

  long originalSequenceNumber = 1234;
  int targetId = 5;
  SnapshotVersion snapshotVersion = new SnapshotVersion(new Timestamp(1, 2));

  Query query = query("rooms");
  TargetData targetData =
      new TargetData(query.toTarget(), targetId, originalSequenceNumber, QueryPurpose.LISTEN);
  db1.runTransaction(
      "add query data",
      () -> {
        targetCache1.addTargetData(targetData);
        targetCache1.setLastRemoteSnapshotVersion(snapshotVersion);
      });

  db1.shutdown();

  SQLitePersistence db2 = PersistenceTestHelpers.createSQLitePersistence(name);
  db2.runTransaction(
      "verify sequence number",
      () -> {
        long newSequenceNumber = db2.getReferenceDelegate().getCurrentSequenceNumber();
        assertTrue(newSequenceNumber > originalSequenceNumber);
      });
  TargetCache targetCache2 = db2.getTargetCache();
  assertEquals(targetId, targetCache2.getHighestTargetId());
  assertEquals(snapshotVersion, targetCache2.getLastRemoteSnapshotVersion());
  assertEquals(1, targetCache2.getTargetCount());
  db2.shutdown();
}
 
Example #25
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeletesValuesFromTheFieldMask() {
  Map<String, Object> data = map("foo", map("bar", "bar-value", "baz", "baz-value"));
  Document baseDoc = doc("collection/key", 0, data);

  DocumentKey key = key("collection/key");
  FieldMask mask = fieldMask("foo.bar");
  Mutation patch = new PatchMutation(key, ObjectValue.emptyObject(), mask, Precondition.NONE);

  MaybeDocument patchDoc = patch.applyToLocalView(baseDoc, baseDoc, Timestamp.now());
  Map<String, Object> expectedData = map("foo", map("baz", "baz-value"));
  assertEquals(
      doc("collection/key", 0, expectedData, Document.DocumentState.LOCAL_MUTATIONS), patchDoc);
}
 
Example #26
Source File: EventsActivity.java    From NaviBee with GNU General Public License v3.0 5 votes vote down vote up
public EventItem(String name, String holder, Timestamp time, Map<String, Boolean> users, ArrayList<String> images, String placeName, double longitude, double latitude, Boolean isPrivate){
    this.holder = holder;
    this.name = name;
    this.users = users;
    this.time = time;
    this.images = images;
    this.placeName = placeName;
    this.longitude = longitude;
    this.latitude = latitude;
    this.isPrivate = isPrivate;
}
 
Example #27
Source File: AuditInfoConverter.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@NonNull
static AuditInfo toAuditInfo(@NonNull AuditInfoNestedObject doc) throws DataStoreException {
  checkNotNull(doc.getClientTimeMillis(), "clientTimeMillis");
  return AuditInfo.builder()
      .setUser(UserConverter.toUser(doc.getUser()))
      .setClientTimeMillis(doc.getClientTimeMillis().toDate())
      .setServerTimeMillis(Optional.ofNullable(doc.getServerTimeMillis()).map(Timestamp::toDate))
      .build();
}
 
Example #28
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 #29
Source File: ShareProfileRequest.java    From openwebnet-android with MIT License 5 votes vote down vote up
@Override
public ShareProfileRequest fromMap(Map<String, Object> map, ProfileVersionModel version) {
    ShareProfileRequest request = new ShareProfileRequest();
    request.requestId = UUID.fromString((String) map.get(FIELD_REQUEST_ID));
    request.profileRef = (DocumentReference) map.get(FIELD_PROFILE_REF);
    request.email = (String) map.get(FIELD_EMAIL);
    request.createdAt = ((Timestamp) map.get(FIELD_CREATED_AT)).toDate();
    return request;
}
 
Example #30
Source File: MutationTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppliesPatchToNullDocWithMergeToDocuments() {
  MaybeDocument baseDoc = null;
  Mutation upsert =
      patchMutation(
          "collection/key", map("foo.bar", "new-bar-value"), Arrays.asList(field("foo.bar")));
  MaybeDocument newDoc = upsert.applyToLocalView(baseDoc, baseDoc, Timestamp.now());
  Map<String, Object> expectedData = map("foo", map("bar", "new-bar-value"));
  assertEquals(
      doc("collection/key", 0, expectedData, Document.DocumentState.LOCAL_MUTATIONS), newDoc);
}