Java Code Examples for com.google.firebase.database.DatabaseReference#setValueAsync()

The following examples show how to use com.google.firebase.database.DatabaseReference#setValueAsync() . 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: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleLimitQueries() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ValueExpectationHelper expectations = new ValueExpectationHelper();
  expectations.add(ref.limitToLast(1), MapBuilder.of("c", 3L));
  expectations.add(ref.endAt(null).limitToLast(1), MapBuilder.of("c", 3L));
  expectations.add(ref.limitToLast(2), MapBuilder.of("b", 2L, "c", 3L));
  expectations.add(ref.limitToLast(3),
      MapBuilder.of("a", 1L, "b", 2L, "c", 3L));
  expectations.add(ref.limitToLast(4),
      MapBuilder.of("a", 1L, "b", 2L, "c", 3L));

  ref.setValueAsync(MapBuilder.of("a", 1L, "b", 2L, "c", 3L));

  expectations.waitForEvents();
}
 
Example 2
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveListener()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener listener = ref.limitToLast(5)
      .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          semaphore.release();
        }

        @Override
        public void onCancelled(DatabaseError error) {
        }
      });

  ref.setValueAsync(MapBuilder.of("a", 5, "b", 6));
  TestHelpers.waitFor(semaphore, 1);
  ref.limitToLast(5).removeEventListener(listener);
  new WriteFuture(ref, MapBuilder.of("a", 6, "b", 5)).timedGet();
  TestHelpers.waitForQueue(ref);

  assertEquals(0, semaphore.availablePermits());
}
 
Example 3
Source File: GeoFire.java    From geofire-java with MIT License 6 votes vote down vote up
/**
 * Sets the location for a given key.
 *
 * @param key                The key to save the location for
 * @param location           The location of this key
 * @param completionListener A listener that is called once the location was successfully saved on the server or an
 *                           error occurred
 */
public void setLocation(final String key, final GeoLocation location, final CompletionListener completionListener) {
    if (key == null) {
        throw new NullPointerException();
    }
    DatabaseReference keyRef = this.getDatabaseRefForKey(key);
    GeoHash geoHash = new GeoHash(location);
    Map<String, Object> updates = new HashMap<>();
    updates.put("g", geoHash.getGeoHashString());
    updates.put("l", Arrays.asList(location.latitude, location.longitude));
    if (completionListener != null) {
        keyRef.setValue(updates, geoHash.getGeoHashString(), new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                completionListener.onComplete(key, databaseError);
            }
        });
    } else {
        Object priority = geoHash.getGeoHashString();
        keyRef.setValueAsync(updates, priority);
    }
}
 
Example 4
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartAtEndAtWithPriorityAndName2() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ValueExpectationHelper helper = new ValueExpectationHelper();
  helper.add(ref.startAt(1, "c").endAt(2, "b"),
      new MapBuilder().put("a", 1L).put("b", 2L).put("c", 3L).put("d", 4L).build());
  helper.add(ref.startAt(1, "d").endAt(2, "a"),
      MapBuilder.of("d", 4L, "a", 1L));
  helper.add(ref.startAt(1, "e").endAt(2),
      MapBuilder.of("a", 1L, "b", 2L));

  ref.setValueAsync(
      new MapBuilder()
          .put("c", MapBuilder.of(".value", 3, ".priority", 1))
          .put("d", MapBuilder.of(".value", 4, ".priority", 1))
          .put("a", MapBuilder.of(".value", 1, ".priority", 2))
          .put("b", MapBuilder.of(".value", 2, ".priority", 2)).build());

  helper.waitForEvents();
}
 
Example 5
Source File: KeepSyncedTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeepSyncedWithExistingListener() throws Exception {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ReadFuture readFuture;
  ref.keepSynced(true);
  try {
    assertIsKeptSynced(ref);

    readFuture =
        new ReadFuture(ref, new ReadFuture.CompletionCondition() {
            @Override
            public boolean isComplete(List<EventRecord> events) {
              return events.get(events.size() - 1).getSnapshot().getValue().equals("done");
            }
          });
  } finally {
    // cleanup
    ref.keepSynced(false);
  }

  // Should trigger our listener.
  ref.setValueAsync("done");
  readFuture.timedGet();
}
 
Example 6
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteIntegerValueThenChangeToDoubleWithDifferentPriority()
    throws InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 1);
  DatabaseReference node = refs.get(0);

  final EventHelper readHelper =
      new EventHelper()
          .addValueExpectation(node, 1337)
          .addValueExpectation(node, 1337)
          .startListening(true);

  ZombieVerifier.verifyRepoZombies(refs);

  node.setValueAsync(1337);
  node.setValueAsync(1337.0, 1337);

  TestHelpers.waitForRoundtrip(node);
  assertTrue(readHelper.waitForEvents());
  ZombieVerifier.verifyRepoZombies(refs);
  readHelper.cleanup();
}
 
Example 7
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateRaisesCorrectLocalEvents()
    throws InterruptedException, TestFailure, TimeoutException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final ReadFuture readFuture = ReadFuture.untilCountAfterNull(ref, 2);

  ref.setValueAsync(new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4).build());

  EventHelper helper = new EventHelper().addValueExpectation(ref.child("a"))
      .addValueExpectation(ref.child("d"))
      .addChildExpectation(ref, Event.EventType.CHILD_CHANGED, "a")
      .addChildExpectation(ref, Event.EventType.CHILD_CHANGED, "d").addValueExpectation(ref)
      .startListening(true);

  ref.updateChildrenAsync(new MapBuilder().put("a", 4).put("d", 1).build());
  helper.waitForEvents();
  List<EventRecord> events = readFuture.timedGet();
  helper.cleanup();

  Map<String, Object> expected = new MapBuilder().put("a", 4L).put("b", 2L).put("c", 3L)
      .put("d", 1L).build();
  Object result = events.get(events.size() - 1).getSnapshot().getValue();
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 8
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPriority()
    throws TimeoutException, InterruptedException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ReadFuture readFuture = ReadFuture.untilCountAfterNull(ref, 7);

  ref.setValueAsync("a");
  ref.setValueAsync("b", 5);
  ref.setValueAsync("c", "6");
  ref.setValueAsync("d", 7);
  ref.setValueAsync(new MapBuilder().put(".value", "e").put(".priority", 8).build());
  ref.setValueAsync(new MapBuilder().put(".value", "f").put(".priority", "8").build());
  ref.setValueAsync(new MapBuilder().put(".value", "g").put(".priority", null).build());

  List<EventRecord> events = readFuture.timedGet();
  assertNull(events.get(0).getSnapshot().getPriority());
  assertEquals(5.0, events.get(1).getSnapshot().getPriority());
  assertEquals("6", events.get(2).getSnapshot().getPriority());
  assertEquals(7.0, events.get(3).getSnapshot().getPriority());
  assertEquals(8.0, events.get(4).getSnapshot().getPriority());
  assertEquals("8", events.get(5).getSnapshot().getPriority());
  assertNull(events.get(6).getSnapshot().getPriority());
}
 
Example 9
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartAtEndAtWithPriorityAndNameUsingServerData2() throws
    InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ref.setValueAsync(
      new MapBuilder()
          .put("c", MapBuilder.of(".value", 3, ".priority", 1))
          .put("d", MapBuilder.of(".value", 4, ".priority", 1))
          .put("a", MapBuilder.of(".value", 1, ".priority", 2))
          .put("b", MapBuilder.of(".value", 2, ".priority", 2)).build());

  ValueExpectationHelper helper = new ValueExpectationHelper();
  helper.add(ref.startAt(1, "c").endAt(2, "b"),
      new MapBuilder().put("a", 1L).put("b", 2L).put("c", 3L).put("d", 4L).build());
  helper.add(ref.startAt(1, "d").endAt(2, "a"),
      MapBuilder.of("d", 4L, "a", 1L));
  helper.add(ref.startAt(1, "e").endAt(2),
      MapBuilder.of("a", 1L, "b", 2L));

  helper.waitForEvents();
}
 
Example 10
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullPrioritiesIncludedInStartAt() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ref.setValueAsync(
      new MapBuilder()
          .put("a", new MapBuilder().put(".priority", null).put(".value", 0).build())
          .put("b", new MapBuilder().put(".priority", null).put(".value", 1).build())
          .put("c", new MapBuilder().put(".priority", 2).put(".value", 2).build())
          .put("d", new MapBuilder().put(".priority", 3).put(".value", 3).build())
          .put("e", new MapBuilder().put(".priority", "hi").put(".value", 4).build()).build());

  DataSnapshot snap = TestHelpers.getSnap(ref.startAt(2));
  Object result = snap.getValue();
  Map<String, Object> expected = MapBuilder.of("c", 2L, "d", 3L, "e", 4L);
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 11
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteLeafNodeExpectValue() throws InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  final EventHelper readerHelper = new EventHelper().addValueExpectation(reader, 42)
      .startListening(true);
  final EventHelper writerHelper = new EventHelper().addValueExpectation(writer, 42)
      .startListening(true);

  ZombieVerifier.verifyRepoZombies(refs);

  writer.setValueAsync(42);
  assertTrue(writerHelper.waitForEvents());
  assertTrue(readerHelper.waitForEvents());
  writerHelper.cleanup();
  readerHelper.cleanup();
  ZombieVerifier.verifyRepoZombies(refs);
}
 
Example 12
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartAtEndAtWithPriorityAndName() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ValueExpectationHelper helper = new ValueExpectationHelper();
  helper.add(ref.startAt(1, "a").endAt(2, "d"),
      new MapBuilder().put("a", 1L).put("b", 2L).put("c", 3L).put("d", 4L).build());
  helper.add(ref.startAt(1, "b").endAt(2, "c"),
      MapBuilder.of("b", 2L, "c", 3L));
  helper.add(ref.startAt(1, "c").endAt(2),
      MapBuilder.of("c", 3L, "d", 4L));

  ref.setValueAsync(
      new MapBuilder()
          .put("a", MapBuilder.of(".value", 1, ".priority", 1))
          .put("b", MapBuilder.of(".value", 2, ".priority", 1))
          .put("c", MapBuilder.of(".value", 3, ".priority", 2))
          .put("d", MapBuilder.of(".value", 4, ".priority", 2)).build());

  helper.waitForEvents();
}
 
Example 13
Source File: QueryTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeletingEntireQueryWindow()
    throws InterruptedException, TestFailure, TimeoutException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final ReadFuture readFuture = ReadFuture.untilCount(ref.limitToLast(2), 3);

  // wait for null event
  TestHelpers.waitForRoundtrip(ref);

  ref.setValueAsync(
      MapBuilder.of(
          "a", MapBuilder.of(".value", 1, ".priority", 1),
          "b", MapBuilder.of(".value", 2, ".priority", 2),
          "c", MapBuilder.of(".value", 3, ".priority", 3)));

  ref.updateChildrenAsync(new MapBuilder().put("b", null).put("c", null).build());
  List<EventRecord> events = readFuture.timedGet();
  DataSnapshot snap = events.get(1).getSnapshot();

  Map<String, Object> expected = MapBuilder.of("b", 2L, "c", 3L);
  Object result = snap.getValue();
  TestHelpers.assertDeepEquals(expected, result);

  // The original set is still outstanding (synchronous API), so we have a
  // full cache to re-window against
  snap = events.get(2).getSnapshot();
  result = snap.getValue();
  TestHelpers.assertDeepEquals(MapBuilder.of("a", 1L), result);
}
 
Example 14
Source File: InfoTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInfoNodeSetValue() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.setValueAsync("hi");
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
 
Example 15
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteLeafNodeRemoveItTryToAddChildToRemovedNode()
    throws ExecutionException, TimeoutException, InterruptedException, TestFailure {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference reader = refs.get(0);
  final DatabaseReference writer = refs.get(1);

  writer.setValueAsync(5);
  writer.removeValueAsync();
  new WriteFuture(writer.child("abc"), 5).timedGet();

  DataSnapshot snap = new ReadFuture(reader).timedGet().get(0).getSnapshot();

  assertEquals(5L, ((Map) snap.getValue()).get("abc"));
}
 
Example 16
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeepUpdate() throws InterruptedException, TestFailure, TimeoutException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  final ReadFuture readFuture = ReadFuture.untilCount(writer, 2);

  writer.setValueAsync(
      new MapBuilder().put("a", new MapBuilder().put("aa", 1).put("ab", 2).build()).build());
  Map<String, Object> expected = new MapBuilder()
      .put("a", new MapBuilder().put("aa", 10L).put("ab", 20L).build()).build();
  Map<String, Object> update = new MapBuilder().put("a/aa", 10).put(".priority", 3.0)
      .put("a/ab", new MapBuilder().put(".priority", 2.0).put(".value", 20).build()).build();

  final Semaphore semaphore = new Semaphore(0);
  writer.updateChildren(update, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference ref) {
      assertNull(error);
      semaphore.release(1);
    }
  });

  TestHelpers.waitFor(semaphore);

  DataSnapshot snap = TestHelpers.getSnap(reader);
  TestHelpers.assertDeepEquals(expected, snap.getValue());
  assertEquals(3.0, snap.getPriority());

  snap = readFuture.timedGet().get(1).getSnapshot();
  TestHelpers.assertDeepEquals(expected, snap.getValue());
  assertEquals(3.0, snap.getPriority());

  snap = TestHelpers.getSnap(reader.child("a/ab"));
  assertEquals(2.0, snap.getPriority());
}
 
Example 17
Source File: EventTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnceFiresExactlyOnce()
    throws TestFailure, ExecutionException, TimeoutException,
        InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  final AtomicInteger called = new AtomicInteger(0);
  ref.addListenerForSingleValueEvent(
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          called.incrementAndGet();
        }

        @Override
        public void onCancelled(DatabaseError error) {
          fail("Should not be cancelled");
        }
      });

  ZombieVerifier.verifyRepoZombies(ref);

  ref.setValueAsync(42);
  ref.setValueAsync(84);
  new WriteFuture(ref, null).timedGet();
  assertEquals(1, called.get());
  ZombieVerifier.verifyRepoZombies(ref);
}
 
Example 18
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsciiControlCharacters() throws DatabaseException {
  DatabaseReference node = IntegrationTestUtils.getRandomNode(masterApp);
  // Test all controls characters PLUS 0x7F (127).
  for (int i = 0; i <= 32; i++) {
    String ch = new String(Character.toChars(i < 32 ? i : 127));
    Map<String, Object> obj = TestHelpers.buildObjFromPath(new Path(ch), "test_value");
    try {
      node.setValueAsync(obj);
      fail("Ascii control character should not be allowed in path.");
    } catch (DatabaseException e) {
      // expected
    }
  }
}
 
Example 19
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testChildAddedEvents() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  Map<String, Object> initial =
      new MapBuilder()
          .put("a", MapBuilder.of("value", 5L))
          .put("c", MapBuilder.of("value", 3L))
          .build();

  final List<String> snapshotNames = new ArrayList<>();
  final List<String> prevNames = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  final ChildEventListener testListener =
      ref.orderByChild("value")
          .addChildEventListener(
              new TestChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot snap, String prevName) {
                  snapshotNames.add(snap.getKey());
                  prevNames.add(prevName);
                  semaphore.release();
                }
              });

  ref.setValueAsync(initial);
  TestHelpers.waitFor(semaphore, 2);
  Assert.assertEquals(Arrays.asList("c", "a"), snapshotNames);
  Assert.assertEquals(Arrays.asList(null, "c"), prevNames);

  Map<String, Object> updates = new HashMap<>();
  updates.put("b", MapBuilder.of("value", 4));
  updates.put("d", MapBuilder.of("value", 2));
  ref.updateChildrenAsync(updates);

  TestHelpers.waitFor(semaphore, 2);
  Assert.assertEquals(Arrays.asList("c", "a", "d", "b"), snapshotNames);
  Assert.assertEquals(Arrays.asList(null, "c", null, "c"), prevNames);
  ref.removeEventListener(testListener);
}
 
Example 20
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAndWrite() throws InterruptedException, TimeoutException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  ReadFuture future = ReadFuture.untilNonNull(ref);

  ref.setValueAsync(42);
  List<EventRecord> events = future.timedGet();
  assertEquals(42L, events.get(events.size() - 1).getSnapshot().getValue());
}