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

The following examples show how to use com.google.firebase.database.DatabaseReference#updateChildren() . 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: PersistenceTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void userMergeIsSaved() {
  PersistenceManager manager = newTestPersistenceManager();
  DatabaseConfig cfg = newFrozenTestConfig();
  DatabaseReference ref = refWithConfig(cfg, manager);
  goOffline(cfg);
  Map<String, Object> merge = new HashMap<String, Object>();
  merge.put("foo", "foo-value");
  ref.updateChildren(merge);
  waitForQueue(ref);
  List<UserWriteRecord> records = manager.loadUserWrites();
  assertEquals(1, records.size());
  UserWriteRecord record = records.get(0);
  assertEquals(ref.getPath(), record.getPath());
  assertEquals(1, record.getWriteId());
  Map<String, Object> expected = new HashMap<String, Object>();
  expected.put("foo", "foo-value");
  assertEquals(expected, record.getMerge().getValue(true));
}
 
Example 2
Source File: PersistenceTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleMergeTest() throws Throwable {
  PersistenceManager manager = newTestPersistenceManager();
  DatabaseConfig cfg1 = newFrozenTestConfig();
  DatabaseReference ref1 = refWithConfig(cfg1, manager).push();
  goOffline(cfg1);
  Map<String, Object> updates = new HashMap<String, Object>();
  updates.put("foo", "bar");
  ref1.updateChildren(updates);
  waitForQueue(ref1);

  DatabaseConfig cfg2 = newFrozenTestConfig();
  DatabaseReference ref2 = refWithConfig(cfg2, manager);
  ref2 = ref2.child(ref1.getKey());

  Object value = new ReadFuture(ref2).waitForLastValue();
  assertEquals(updates, value);
}
 
Example 3
Source File: PersistenceTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void deepUpdateTest() throws Throwable {
  PersistenceManager manager = newTestPersistenceManager();
  DatabaseConfig cfg1 = newFrozenTestConfig();
  DatabaseReference ref1 = refWithConfig(cfg1, manager).push();
  goOffline(cfg1);
  Map<String, Object> updates = new HashMap<String, Object>();
  updates.put("foo/deep/update", "bar");
  ref1.updateChildren(updates);
  waitForQueue(ref1);

  DatabaseConfig cfg2 = newFrozenTestConfig();
  DatabaseReference ref2 = refWithConfig(cfg2, manager);
  ref2 = ref2.child(ref1.getKey());

  Object value = new ReadFuture(ref2).waitForLastValue();
  assertEquals(value, fromSingleQuotedString("{ 'foo': { 'deep': { 'update': 'bar' } } }"));
}
 
Example 4
Source File: ShoppingCartWindow.java    From NITKart with MIT License 6 votes vote down vote up
private void clearCart() {

        if (!isCartEmpty) {
            DatabaseReference myRefClear = FirebaseDatabase.getInstance().getReference("users").child(user.getUid());
            myRefClear.child(user.getUid()).push();

            // As firebase does not accept keys with empty values, I'm putting a dummy item with empty Strings and -1 as ints
            // Quantity of items in cart is not realtime database quantity but the quantity the user wants
            ArrayList<ShoppingItem> cart = new ArrayList<>();
            cart.add(new ShoppingItem("", "", "", "", -1, -1));
            Map<String, Object> cartItems = new HashMap<>();
            cartItems.put("cartItems", cart);

            // Adding a isCartEmpty State Variable for cart window display

            Map<String, Object> cartState = new HashMap<>();
            cartState.put("isCartEmpty", Boolean.TRUE);

            // Updating the database for the user
            myRefClear.updateChildren(cartItems);
            myRefClear.updateChildren(cartState);

            isCartEmpty = true;
        }
    }
 
Example 5
Source File: DatabaseTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void updateChildrenShouldTriggerListenerWithUpdatedData() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseDatabase database = FirebaseDatabase.getInstance();

  auth.signOut();
  Task<?> signInTask = auth.signInWithEmailAndPassword("[email protected]", "password");
  Tasks2.waitForSuccess(signInTask);

  DatabaseReference doc = database.getReference("restaurants").child(TestId.create());
  HashMap<String, Object> originalData = new HashMap<>();
  originalData.put("location", "Google NYC");

  try {
    Task<?> setTask = doc.setValue(new HashMap<>(originalData));
    Tasks2.waitForSuccess(setTask);
    SnapshotListener listener = new SnapshotListener();
    doc.addListenerForSingleValueEvent(listener);

    HashMap<String, Object> updateData = new HashMap<>();
    updateData.put("count", 412L);

    Task<?> updateTask = doc.updateChildren(new HashMap<>(updateData));
    Task<DataSnapshot> snapshotTask = listener.toTask();
    Tasks2.waitForSuccess(updateTask);
    Tasks2.waitForSuccess(snapshotTask);

    DataSnapshot result = snapshotTask.getResult();
    HashMap<String, Object> finalData = new HashMap<>();
    finalData.put("location", "Google NYC");
    finalData.put("count", 412L);
    assertThat(result.getValue()).isEqualTo(finalData);
  } finally {
    Tasks2.waitBestEffort(doc.removeValue());
  }
}
 
Example 6
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateChangesAreStoredCorrectlyInServer()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  new WriteFuture(writer,
      new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4).build()).timedGet();

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

  TestHelpers.waitFor(semaphore);

  DataSnapshot snap = TestHelpers.getSnap(reader);
  Map<String, Object> expected = new MapBuilder().put("a", 42L).put("b", 2L).put("c", 3L)
      .put("d", 4L).build();
  Object result = snap.getValue();
  TestHelpers.assertDeepEquals(expected, result);
}
 
Example 7
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAffectPriorityRemotely()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  new WriteFuture(writer, new MapBuilder().put("a", 1).put("b", 2).put("c", 3).build(), "testpri")
      .timedGet();

  DataSnapshot snap = TestHelpers.getSnap(reader);
  assertEquals("testpri", snap.getPriority());

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

  TestHelpers.waitFor(semaphore);
  snap = TestHelpers.getSnap(reader);
  assertEquals("testpri", snap.getPriority());
}
 
Example 8
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateReplacesChildren() 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.untilCountAfterNull(writer, 2);

  writer.setValueAsync(
      new MapBuilder().put("a", new MapBuilder().put("aa", 1).put("ab", 2).build()).build());
  final Semaphore semaphore = new Semaphore(0);
  Map<String, Object> expected = MapBuilder.of("a", MapBuilder.of("aa", 1L));
  writer.updateChildren(expected, 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());

  snap = readFuture.timedGet().get(1).getSnapshot();
  TestHelpers.assertDeepEquals(expected, snap.getValue());
}
 
Example 9
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 10
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPriorityUpdate() throws InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  Map<String, Object> writeValue = new MapBuilder().put("a", 5).put(".priority", "pri1").build();

  Map<String, Object> updateValue = new MapBuilder().put("a", 6).put(".priority", "pri2")
      .put("b", new MapBuilder().put(".priority", "pri3").put("c", 10).build()).build();

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

  DataSnapshot snap = TestHelpers.getSnap(reader);
  assertEquals(6L, snap.child("a").getValue());
  assertEquals("pri2", snap.getPriority());
  assertEquals("pri3", snap.child("b").getPriority());
  assertEquals(10L, snap.child("b/c").getValue());
}
 
Example 11
Source File: OrderByTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeepUpdates()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure, IOException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference writer = refs.get(0);
  DatabaseReference reader = refs.get(1);

  final String indexRule = "{ \".indexOn\": \"idx\"}";
  String rules = formatRules(writer, indexRule);

  uploadRules(masterApp, rules);

  Map<String, Object> initial =
      new MapBuilder()
          .put("a", MapBuilder.of("data", "foo", "idx", true))
          .put("b", MapBuilder.of("data", "bar", "idx", true))
          .put("c", MapBuilder.of("data", "baz", "idx", false))
          .build();
  new WriteFuture(writer, initial).timedGet();

  Query query = reader.orderByChild("idx").equalTo(true);

  DataSnapshot snap = TestHelpers.getSnap(query);
  TestHelpers.assertDeepEquals(
      new MapBuilder()
          .put("a", MapBuilder.of("data", "foo", "idx", true))
          .put("b", MapBuilder.of("data", "bar", "idx", true))
          .build(),
      snap.getValue());

  Map<String, Object> update =
      new MapBuilder().put("a/idx", false).put("b/data", "blah").put("c/idx", true).build();
  final Semaphore semaphore = new Semaphore(0);
  writer.updateChildren(
      update,
      new CompletionListener() {
        @Override
        public void onComplete(DatabaseError error, DatabaseReference ref) {
          assertNull(error);
          semaphore.release(1);
        }
      });
  TestHelpers.waitFor(semaphore);

  snap = TestHelpers.getSnap(query);
  TestHelpers.assertDeepEquals(
      new MapBuilder()
          .put("b", MapBuilder.of("data", "blah", "idx", true))
          .put("c", MapBuilder.of("data", "baz", "idx", true))
          .build(),
      snap.getValue());
}