Java Code Examples for com.google.firebase.database.DatabaseReference#CompletionListener

The following examples show how to use com.google.firebase.database.DatabaseReference#CompletionListener . 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: Repo.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
void callOnComplete(
    final DatabaseReference.CompletionListener onComplete,
    final DatabaseError error,
    final Path path) {
  if (onComplete != null) {
    final DatabaseReference ref;
    ChildKey last = path.getBack();
    if (last != null && last.isPriorityChildName()) {
      ref = InternalHelpers.createReference(this, path.getParent());
    } else {
      ref = InternalHelpers.createReference(this, path);
    }
    postEvent(
        new Runnable() {
          @Override
          public void run() {
            onComplete.onComplete(error, ref);
          }
        });
  }
}
 
Example 2
Source File: RepoTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallOnComplete() {
  final Repo repo = newRepo();
  final AtomicReference<DatabaseError> errorResult = new AtomicReference<>();
  final AtomicReference<DatabaseReference> refResult = new AtomicReference<>();
  DatabaseReference.CompletionListener listener = new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference ref) {
      errorResult.set(error);
      refResult.set(ref);
    }
  };
  repo.callOnComplete(listener, null, new Path("/foo"));
  assertNull(errorResult.get());
  assertEquals("foo", refResult.get().getKey());

  DatabaseError ex = DatabaseError.fromCode(DatabaseError.WRITE_CANCELED);
  repo.callOnComplete(listener, ex, new Path("/bar"));
  assertEquals(ex, errorResult.get());
  assertEquals("bar", refResult.get().getKey());
}
 
Example 3
Source File: Repo.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void onDisconnectSetValue(
    final Path path, final Node newValue, final DatabaseReference.CompletionListener onComplete) {
  connection.onDisconnectPut(
      path.asList(),
      newValue.getValue(true),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("onDisconnect().setValue", path, error);
          if (error == null) {
            onDisconnect.remember(path, newValue);
          }
          callOnComplete(onComplete, error, path);
        }
      });
}
 
Example 4
Source File: Utilities.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public static Pair<Task<Void>, DatabaseReference.CompletionListener> wrapOnComplete(
    DatabaseReference.CompletionListener optListener) {
  if (optListener == null) {
    final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
    DatabaseReference.CompletionListener listener =
        new DatabaseReference.CompletionListener() {
          @Override
          public void onComplete(DatabaseError error, DatabaseReference ref) {
            if (error != null) {
              source.setException(error.toException());
            } else {
              source.setResult(null);
            }
          }
        };
    return new Pair<>(source.getTask(), listener);
  } else {
    // If a listener is supplied we do not want to create a Task
    return new Pair<>(null, optListener);
  }
}
 
Example 5
Source File: Repo.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public void onDisconnectUpdate(
    final Path path,
    final Map<Path, Node> newChildren,
    final DatabaseReference.CompletionListener listener,
    Map<String, Object> unParsedUpdates) {
  connection.onDisconnectMerge(
      path.asList(),
      unParsedUpdates,
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("onDisconnect().updateChildren", path, error);
          if (error == null) {
            for (Map.Entry<Path, Node> entry : newChildren.entrySet()) {
              onDisconnect.remember(path.child(entry.getKey()), entry.getValue());
            }
          }
          callOnComplete(listener, error, path);
        }
      });
}
 
Example 6
Source File: Repo.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public void onDisconnectSetValue(
    final Path path, final Node newValue, final DatabaseReference.CompletionListener onComplete) {
  connection.onDisconnectPut(
      path.asList(),
      newValue.getValue(true),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("onDisconnect().setValue", path, error);
          if (error == null) {
            onDisconnect.remember(path, newValue);
          }
          callOnComplete(onComplete, error, path);
        }
      });
}
 
Example 7
Source File: Repo.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
void callOnComplete(
    final DatabaseReference.CompletionListener onComplete,
    final DatabaseError error,
    final Path path) {
  if (onComplete != null) {
    final DatabaseReference ref;
    ChildKey last = path.getBack();
    if (last != null && last.isPriorityChildName()) {
      ref = InternalHelpers.createReference(this, path.getParent());
    } else {
      ref = InternalHelpers.createReference(this, path);
    }
    postEvent(
        new Runnable() {
          @Override
          public void run() {
            onComplete.onComplete(error, ref);
          }
        });
  }
}
 
Example 8
Source File: Repo.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public void onDisconnectCancel(
    final Path path, final DatabaseReference.CompletionListener onComplete) {
  connection.onDisconnectCancel(
      path.asList(),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          if (error == null) {
            onDisconnect.forget(path);
          }
          callOnComplete(onComplete, error, path);
        }
      });
}
 
Example 9
Source File: Repo.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public void setValue(
    final Path path,
    Node newValueUnresolved,
    final DatabaseReference.CompletionListener onComplete) {
  if (operationLogger.logsDebug()) {
    operationLogger.debug("set: " + path);
  }
  if (dataLogger.logsDebug()) {
    dataLogger.debug("set: " + path + " " + newValueUnresolved);
  }

  Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock);
  Node existing = serverSyncTree.calcCompleteEventCache(path, new ArrayList<>());
  Node newValue =
      ServerValues.resolveDeferredValueSnapshot(newValueUnresolved, existing, serverValues);

  final long writeId = this.getNextWriteId();
  List<? extends Event> events =
      this.serverSyncTree.applyUserOverwrite(
          path, newValueUnresolved, newValue, writeId, /*visible=*/ true, /*persist=*/ true);
  this.postEvents(events);

  connection.put(
      path.asList(),
      newValueUnresolved.getValue(true),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("setValue", path, error);
          ackWriteAndRerunTransactions(writeId, path, error);
          callOnComplete(onComplete, error, path);
        }
      });

  Path affectedPath = abortTransactions(path, DatabaseError.OVERRIDDEN_BY_SET);
  this.rerunTransactions(affectedPath);
}
 
Example 10
Source File: RepoTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnDisconnectCancel() throws InterruptedException {
  final Repo repo = newRepo();
  final AtomicReference<DatabaseError> errorResult = new AtomicReference<>();
  final AtomicReference<DatabaseReference> refResult = new AtomicReference<>();
  final Semaphore semaphore = new Semaphore(0);
  final DatabaseReference.CompletionListener listener = newCompletionListener(
      errorResult, refResult);

  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.onDisconnectCancel(new Path(SUCCESS), listener);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertNull(errorResult.get());
  assertEquals("success", refResult.get().getKey());

  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.onDisconnectCancel(new Path(FAILURE), listener);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertNotNull(errorResult.get());
  assertEquals(DatabaseError.DATA_STALE, errorResult.get().getCode());
  assertEquals("failure", refResult.get().getKey());
}
 
Example 11
Source File: Stroke.java    From justaline-android with Apache License 2.0 5 votes vote down vote up
public void setFirebaseValue(StrokeUpdate strokeUpdate, StrokeUpdate previousStrokeUpdate,
                                 DatabaseReference.CompletionListener completionListener) {
//        Stroke copy = new Stroke();
//        copy.lineWidth = strokeUpdate.stroke.lineWidth;
//        int numPointsToSend = strokeUpdate.stroke.points.size();
//        copy.points = strokeUpdate.stroke.points.subList(0, strokeUpdate.stroke.points.size());
//
//        copy.creator = strokeUpdate.stroke.creator;

        // if points havent been set, or if creator or lineWidth has changed, force a full update
        if (previousStrokeUpdate == null
                || previousStrokeUpdate.stroke.points.size() == 0
                || !previousStrokeUpdate.stroke.creator.equals(strokeUpdate.stroke.creator)
                || previousStrokeUpdate.stroke.lineWidth != strokeUpdate.stroke.lineWidth) {
            firebaseReference.setValue(strokeUpdate.stroke, completionListener);
        } else {
            // If only points have updated, calculate the changes since last update, and only upload those points
            Map<String, Object> pointUpdate = new HashMap<>();
            int i = 0;
            for (Vector3f p : strokeUpdate.stroke.points) {
                // If point exceeds previous strokes length, add it
                if (previousStrokeUpdate.stroke.points.size() <= i) {
                    pointUpdate.put(String.valueOf(i), p);
                } else {
                    // Check if point equals previous point
                    Vector3f prev = previousStrokeUpdate.stroke.points.get(i);
                    if (!p.equals(prev)) {
                        pointUpdate.put(String.valueOf(i), p);
                    }
                }
                i++;
            }

            firebaseReference.child("points").updateChildren(pointUpdate, completionListener);
        }
    }
 
Example 12
Source File: Repo.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public void setValue(
    final Path path,
    Node newValueUnresolved,
    final DatabaseReference.CompletionListener onComplete) {
  logger.debug("set: {} {}", path, newValueUnresolved);

  Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock);
  Node newValue = ServerValues.resolveDeferredValueSnapshot(newValueUnresolved, serverValues);

  final long writeId = this.getNextWriteId();
  List<? extends Event> events =
      this.serverSyncTree.applyUserOverwrite(
          path, newValueUnresolved, newValue, writeId, /*visible=*/ true, /*persist=*/ true);
  this.postEvents(events);

  connection.put(
      path.asList(),
      newValueUnresolved.getValue(true),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("setValue", path, error);
          ackWriteAndRerunTransactions(writeId, path, error);
          callOnComplete(onComplete, error, path);
        }
      });

  Path affectedPath = abortTransactions(path, DatabaseError.OVERRIDDEN_BY_SET);
  this.rerunTransactions(affectedPath);
}
 
Example 13
Source File: RepoTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private DatabaseReference.CompletionListener newCompletionListener(
    final AtomicReference<DatabaseError> errorResult,
    final AtomicReference<DatabaseReference> refResult) {
  return new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference ref) {
      errorResult.set(error);
      refResult.set(ref);
    }
  };
}
 
Example 14
Source File: Repo.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public void onDisconnectCancel(
    final Path path, final DatabaseReference.CompletionListener onComplete) {
  connection.onDisconnectCancel(
      path.asList(),
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          if (error == null) {
            onDisconnect.forget(path);
          }
          callOnComplete(onComplete, error, path);
        }
      });
}
 
Example 15
Source File: UtilitiesTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapOnComplete() throws Exception {
  Pair<ApiFuture<Void>, DatabaseReference.CompletionListener> result =
      Utilities.wrapOnComplete(null);
  assertNotNull(result.getFirst());
  assertNotNull(result.getSecond());
  assertFalse(result.getFirst().isDone());

  result.getSecond().onComplete(null, null);
  assertTrue(result.getFirst().isDone());
  assertNull(result.getFirst().get());
}
 
Example 16
Source File: UtilitiesTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapOnCompleteErrorResult() throws InterruptedException {
  Pair<ApiFuture<Void>, DatabaseReference.CompletionListener> result =
      Utilities.wrapOnComplete(null);
  assertNotNull(result.getFirst());
  assertNotNull(result.getSecond());
  assertFalse(result.getFirst().isDone());

  result.getSecond().onComplete(DatabaseError.fromStatus("test error"), null);
  try {
    result.getFirst().get();
  } catch (ExecutionException e) {
    assertNotNull(e.getCause());
  }
}
 
Example 17
Source File: UtilitiesTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapOnCompleteExplicit() {
  CompletionListener listener = new CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference ref) {

    }
  };
  Pair<ApiFuture<Void>, DatabaseReference.CompletionListener> result =
      Utilities.wrapOnComplete(listener);
  assertNull(result.getFirst());
  assertSame(listener, result.getSecond());
}
 
Example 18
Source File: RoomManager.java    From justaline-android with Apache License 2.0 5 votes vote down vote up
private void doStrokeUpdate(final StrokeUpdate strokeUpdate) {
    if (strokeUpdate.remove) {
        strokeUpdate.stroke.removeFirebaseValue();
    } else {
        DatabaseReference.CompletionListener completionListener
                = new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError databaseError,
                                   DatabaseReference databaseReference) {
                synchronized (strokeQueue) {
                    completedStrokeUpdates
                            .put(strokeUpdate.stroke.getFirebaseKey(), strokeUpdate);
                    uploadingStrokes.remove(strokeUpdate.stroke.getFirebaseKey());
                    Iterator<Map.Entry<String, StrokeUpdate>> i = strokeQueue.entrySet().iterator();
                    if (i.hasNext()) {
                        Map.Entry<String, StrokeUpdate> entry
                                = i.next();
                        i.remove();
                        queueStrokeUpdate(entry.getValue());
                    }
                }
            }
        };
        synchronized (strokeQueue) {
            uploadingStrokes.add(strokeUpdate.stroke.getFirebaseKey());
            strokeUpdate.stroke.setFirebaseValue(strokeUpdate,
                    completedStrokeUpdates.get(strokeUpdate.stroke.getFirebaseKey()),
                    completionListener);
        }
    }
}
 
Example 19
Source File: Repo.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public void updateChildren(
    final Path path,
    CompoundWrite updates,
    final DatabaseReference.CompletionListener onComplete,
    Map<String, Object> unParsedUpdates) {
  if (operationLogger.logsDebug()) {
    operationLogger.debug("update: " + path);
  }
  if (dataLogger.logsDebug()) {
    dataLogger.debug("update: " + path + " " + unParsedUpdates);
  }
  if (updates.isEmpty()) {
    if (operationLogger.logsDebug()) {
      operationLogger.debug("update called with no changes. No-op");
    }
    // dispatch on complete
    callOnComplete(onComplete, null, path);
    return;
  }

  // Start with our existing data and merge each child into it.
  Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock);
  CompoundWrite resolved =
      ServerValues.resolveDeferredValueMerge(updates, serverSyncTree, path, serverValues);

  final long writeId = this.getNextWriteId();
  List<? extends Event> events =
      this.serverSyncTree.applyUserMerge(path, updates, resolved, writeId, /*persist=*/ true);
  this.postEvents(events);

  // TODO: DatabaseReference.CompleteionListener isn't really appropriate (the DatabaseReference
  // param is meaningless).
  connection.merge(
      path.asList(),
      unParsedUpdates,
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("updateChildren", path, error);
          ackWriteAndRerunTransactions(writeId, path, error);
          callOnComplete(onComplete, error, path);
        }
      });

  for (Entry<Path, Node> update : updates) {
    Path pathFromRoot = path.child(update.getKey());
    Path affectedPath = abortTransactions(pathFromRoot, DatabaseError.OVERRIDDEN_BY_SET);
    rerunTransactions(affectedPath);
  }
}
 
Example 20
Source File: Repo.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public void updateChildren(
    final Path path,
    CompoundWrite updates,
    final DatabaseReference.CompletionListener onComplete,
    Map<String, Object> unParsedUpdates) {
  logger.debug("update: {} {}", path, unParsedUpdates);
  if (updates.isEmpty()) {
    logger.debug("update called with no changes. No-op");
    // dispatch on complete
    callOnComplete(onComplete, null, path);
    return;
  }

  // Start with our existing data and merge each child into it.
  Map<String, Object> serverValues = ServerValues.generateServerValues(serverClock);
  CompoundWrite resolved = ServerValues.resolveDeferredValueMerge(updates, serverValues);

  final long writeId = this.getNextWriteId();
  List<? extends Event> events =
      this.serverSyncTree.applyUserMerge(path, updates, resolved, writeId, /*persist=*/ true);
  this.postEvents(events);

  // TODO: DatabaseReference.CompleteionListener isn't really appropriate (the DatabaseReference
  // param is meaningless).
  connection.merge(
      path.asList(),
      unParsedUpdates,
      new RequestResultCallback() {
        @Override
        public void onRequestResult(String optErrorCode, String optErrorMessage) {
          DatabaseError error = fromErrorCode(optErrorCode, optErrorMessage);
          warnIfWriteFailed("updateChildren", path, error);
          ackWriteAndRerunTransactions(writeId, path, error);
          callOnComplete(onComplete, error, path);
        }
      });

  for (Entry<Path, Node> update : updates) {
    Path pathFromRoot = path.child(update.getKey());
    Path affectedPath = abortTransactions(pathFromRoot, DatabaseError.OVERRIDDEN_BY_SET);
    rerunTransactions(affectedPath);
  }
}