Java 类com.google.firebase.database.DatabaseReference 实例源码

项目:smartswitch    文件:SwitchesAdapter.java   
@Override
public void onBindViewHolder(SwitchesAdapter.SwitchViewHolder holder, int position) {
    final Switch switch1 = mSwitches.get(position);

    holder.mSwitchTextView.setText(switch1.getName().toUpperCase().replace("PIN", "").replace("LIGHTBULB", "LIGHT BULB"));

    holder.mSwitchToggel.setBackgroundDrawable(switch1.getIcon());
    holder.mSwitchToggel.setOnCheckedChangeListener(null);
    holder.mSwitchToggel.setChecked(switch1.getStatus());
    holder.mSwitchToggel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch1.setStatus(isChecked);

            DatabaseReference switchRef = mDatabaseReference.child(switch1.getName()).getRef();
            switchRef.setValue(switch1);

            notifyDataSetChanged();
        }
    });
}
项目:Subs    文件:DatabaseCompletionListener.java   
public <T> void updateChildren(DatabaseReference databaseReference,
        @NonNull final ObservableEmitter<T> emitter, Map<String, Object> childUpdates) {
    if (isNetworkAvailable) {
        databaseReference.updateChildren(childUpdates, (databaseError, databaseReference1) -> {
            if (emitter.isDisposed()) {
                return;
            }
            if (databaseError == null) {
                emitter.onComplete();
            } else {
                emitter.onError(new Throwable(databaseError.getMessage()));
            }
        });
    } else {
        databaseReference.updateChildren(childUpdates);
        emitter.onComplete();
    }
}
项目:firebase-admin-java    文件:RulesTestIT.java   
@Test
public void testAuthenticatedImmediatelyAfterTokenChange() throws Exception {
  DatabaseConfig config = TestHelpers.getDatabaseConfig(masterApp);
  AuthTokenProvider originalProvider = config.getAuthTokenProvider();
  try {
    TestTokenProvider provider = new TestTokenProvider(TestHelpers.getExecutorService(config));
    config.setAuthTokenProvider(provider);

    DatabaseReference root = FirebaseDatabase.getInstance(masterApp).getReference();
    DatabaseReference ref = root.child(writer.getPath().toString());

    String token = TestOnlyImplFirebaseTrampolines.getToken(masterApp, true);
    provider.setToken(token);

    DatabaseError err = new WriteFuture(ref.child("any_auth"), true).timedGet();
    assertNull(err);
  } finally {
    config.setAuthTokenProvider(originalProvider);
  }
}
项目:DBPA    文件:Firebase.java   
protected List<Post> searchPostsByAuthor(Author author) {
    DatabaseReference myRef = mFirebaseInstance.getReference("post");
    myRef.orderByChild("author/key").equalTo(author.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<Post> result = new ArrayList<>();
            for (DataSnapshot child : dataSnapshot.getChildren()) {
                Post post = child.getValue(Post.class);
                result.add(post);
            }
            searchPostsByAuthorCount++;
            if(searchPostsByAuthorCount== ITERATIONS){
                logEvent("Search Posts by Authors ("+ ITERATIONS +")", initialTimeSearchPostsByAuthor, new Date());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
    return null;
}
项目:mobile-app-dev-book    文件:JournalFragment.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_journal_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        FirebaseDatabase dbRef = FirebaseDatabase.getInstance();
        FirebaseAuth auth = FirebaseAuth.getInstance();
        FirebaseUser user = auth.getCurrentUser();
        DatabaseReference userRef = dbRef.getReference(user.getUid());
        userRef.addChildEventListener (chEvListener);
        userRef.addValueEventListener(valEvListener);
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        adapter = new JournalAdapter(allTrips, mListener);
        recyclerView.setAdapter(adapter);
    }
    return view;
}
项目:firebase-admin-java    文件:EventTestIT.java   
@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);
}
项目:firebase-admin-java    文件:EventTestIT.java   
@Test
public void testWriteNestedLeafNodeWaitForEvents() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;
  EventHelper helper =
      new EventHelper()
          .addChildExpectation(ref, Event.EventType.CHILD_ADDED, "foo")
          .addValueExpectation(ref)
          .startListening(true);

  ZombieVerifier.verifyRepoZombies(ref);

  ref.child("foo").setValueAsync(42);
  assertTrue(helper.waitForEvents());
  ZombieVerifier.verifyRepoZombies(ref);
  helper.cleanup();
}
项目:permitlog-android    文件:HomeFragment.java   
public void saveDrive(boolean night, boolean weather, boolean adverse, String driverId) {
    // Check if the user is signed in:
    boolean isSignedIn = FirebaseHelper.signInIfNeeded((MainActivity)getActivity());
    // Don't do anything if the user isn't signed in:
    if (!isSignedIn) return;
    // Delete the ongoing drive now that it's over:
    ongoingRef.removeValue();

    // Set the ending time so that startingTime-endingTime is exact in minutes:
    endingTime.set(Calendar.SECOND, startingTime.get(Calendar.SECOND));
    endingTime.set(Calendar.MILLISECOND, startingTime.get(Calendar.MILLISECOND));

    // Connect to the database
    DatabaseReference driveRef = FirebaseDatabase.getInstance().getReference().child(userId).child("times").push();
    driveRef.child("start").setValue(startingTime.getTimeInMillis());
    driveRef.child("end").setValue(endingTime.getTimeInMillis());
    driveRef.child("night").setValue(night);
    driveRef.child("weather").setValue(weather);
    driveRef.child("adverse").setValue(adverse);
    driveRef.child("driver_id").setValue(driverId);
}
项目:Runnest    文件:FirebaseHelper.java   
/**
 * Given the name of a challenge and one of its two users, adds one checkpoint its list, named after its
 * sequence number in the challenge.
 *
 * @param checkPoint        Checkpoint to add.
 * @param challengeName     Challenge to modify.
 * @param user              The user of the challenge to which to add data.
 * @param seqNumber         Sequence number of the checkpoint in the current challenge.
 */
public void addChallengeCheckPoint(CheckPoint checkPoint, String challengeName, String user, int seqNumber) {

    if (user == null || challengeName == null || checkPoint == null) {
        throw new IllegalArgumentException("Challenge node or data parameters can't be null");
    } else if (user.isEmpty() || challengeName.isEmpty()) {
        throw new IllegalArgumentException("Challenge node parameters can't be empty");
    }

    DatabaseReference checkPointRef = databaseReference.child(FirebaseNodes.CHALLENGES).child(challengeName).child(user)
            .child(FirebaseNodes.ChallengeStatus.DATA.toString()).child(Integer.toString(seqNumber));

    Map<String, Object> checkPointUpdate = new HashMap<>();
    checkPointUpdate.put("/" + FirebaseNodes.LATITUDE, checkPoint.getLatitude());
    checkPointUpdate.put("/" + FirebaseNodes.LONGITUDE, checkPoint.getLongitude());

    checkPointRef.updateChildren(checkPointUpdate);
}
项目:EasyFirebase    文件:RxFirebaseHelper.java   
public <T> Observable<T> push(final DatabaseReference databaseReference) {
    final Observable<T> observable = Observable.create(new Observable.OnSubscribe<T>() {
                                                           @Override
                                                           public void call(final Subscriber<? super T> subscriber) {
                                                               databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                                                                   @Override
                                                                   public void onDataChange(DataSnapshot dataSnapshot) {
                                                                       subscriber.onNext(null);
                                                                       subscriber.onCompleted();
                                                                   }

                                                                   @Override
                                                                   public void onCancelled(DatabaseError databaseError) {

                                                                   }
                                                               });
                                                           }
                                                       });

    databaseReference.push();
    return observable;
}
项目:Forager    文件:StartGame.java   
private void subtractFromDistanceRemaining(final DatabaseReference databaseReference, FirebaseUser firebaseUser) {
    databaseReference.child("global")
            .child("distanceRemaining")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Update the database
                    subtractFromDistanceRemaining(databaseReference, (dataSnapshot.getValue(Long.class).intValue() - 1));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, "Database Error Occurred", databaseError.toException());
                    FirebaseCrash.report(databaseError.toException());
                }
            });
}
项目:share-location    文件:FirebaseHelper.java   
private static void deleteGroupFromUser(final String groupId, String userId) {
    final DatabaseReference currentUserGroupsRef = userDataRef.child(userId).child("groups");
    currentUserGroupsRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                if (ds.getValue().equals(groupId)) {
                    currentUserGroupsRef.child(ds.getKey()).removeValue();
                    pullFromFirebase(2); // Fetch group data from Firebase from new list
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
项目:firebase-admin-java    文件:EventTestIT.java   
@Test
public void testSubscribeThenUnsubscribeWithoutProblems()
    throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  ValueEventListener listener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {}

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

  ValueEventListener listenerHandle = ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle);
  ZombieVerifier.verifyRepoZombies(ref);
  ValueEventListener listenerHandle2 = ref.addValueEventListener(listener);
  ZombieVerifier.verifyRepoZombies(ref);
  ref.removeEventListener(listenerHandle2);
  ZombieVerifier.verifyRepoZombies(ref);
}
项目:AndroidBackendlessChat    文件:FirebaseEventsManager.java   
public void threadOn(String threadId, Deferred<BThread, Void, Void> deferred){
    if (DEBUG) Timber.v("threadOn, EntityID: %s",threadId);
    if (!isListeningToThread(threadId))
    {
        threadsIds.add(threadId);

        final DatabaseReference threadRef = FirebasePaths.threadRef(threadId);

        // Add an observer to the thread details so we get
        // updated when the thread details change
        DatabaseReference detailsRef = threadRef.child(BFirebaseDefines.Path.BDetailsPath);

        FirebaseEventCombo combo = getCombo(threadId, detailsRef.toString(), new ThreadUpdateChangeListener(threadId, handlerThread, deferred));

        detailsRef.addValueEventListener(combo.getListener());
    }
    else if (DEBUG) Timber.e("Thread is already handled..");

}
项目:social-app-android    文件:DatabaseHelper.java   
public void updateComment(String commentId, String commentText, String postId, final OnTaskCompleteListener onTaskCompleteListener) {
    DatabaseReference mCommentReference = database.getReference().child("post-comments").child(postId).child(commentId).child("text");
    mCommentReference.setValue(commentText).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(true);
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(false);
            }
            LogUtil.logError(TAG, "updateComment", e);
        }
    });
}
项目:firebase-admin-java    文件:RepoTest.java   
@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());
}
项目:Forager    文件:AccountSettings.java   
private void setNumberOfPointsToUI(DatabaseReference databaseReference, FirebaseUser firebaseUser) {
    databaseReference.child("users")
            .child(firebaseUser.getUid())
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Update the android UI
                    setNumberOfPointsToUI(dataSnapshot.getValue(User.class).getNumberOfPoints());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, "Database Error Occurred", databaseError.toException());
                    FirebaseCrash.report(databaseError.toException());
                }
            });
}
项目:Forager    文件:AccountSettings.java   
private void setNumberOfMushroomsToUI(DatabaseReference databaseReference, FirebaseUser firebaseUser) {
    databaseReference.child("users")
            .child(firebaseUser.getUid())
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Update the android UI
                    setNumberOfMushroomsToUI(dataSnapshot.getValue(User.class).getNumberOfMushrooms());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, "Database Error Occurred", databaseError.toException());
                    FirebaseCrash.report(databaseError.toException());
                }
            });
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@Test
public void testInvalidPathsToOrderBy() {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  List<String> badKeys = ImmutableList.<String>builder()
      .add("$child/foo", "$childfoo", "$/foo", "$child/foo/bar", "$child/.foo", ".priority",
          "$priority", "$key", ".key", "$child/.priority")
      .build();
  for (String key : badKeys) {
    try {
      ref.orderByChild(key);
      fail("Should throw");
    } catch (DatabaseException | IllegalArgumentException e) { // ignore
    }
  }
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testWriteParentNodeOverwriteAtLeafNodeWaitForEvents() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

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

  ref.child("a").setValueAsync(new MapBuilder().put("aa", 2).build());
  ref.child("a/aa").setValueAsync(1);

  assertTrue(helper.waitForEvents());
  helper.cleanup();
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@Test
public void testStartAtEndAtWithPriority() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

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

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

  helper.waitForEvents();
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@Test
public void testStartAtEndAtWithPriorityUsingServerData() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

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

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

  helper.waitForEvents();
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@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();
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testWriteValueReconnectRead()
    throws ExecutionException, TimeoutException, InterruptedException, TestFailure {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  WriteFuture writeFuture = new WriteFuture(writer, 42);
  writeFuture.timedGet();

  ReadFuture future = new ReadFuture(reader);

  EventRecord eventRecord = future.timedGet().get(0);
  long result = (Long) eventRecord.getSnapshot().getValue();
  assertEquals(42L, result);
  assertEquals(42, (int) eventRecord.getSnapshot().getValue(Integer.class));
}
项目:friendlypix-android    文件:FirebasePostQueryAdapter.java   
@Override
public void onBindViewHolder(final PostViewHolder holder, int position) {
    DatabaseReference ref = FirebaseUtil.getPostsRef().child(mPostPaths.get(position));
    // TODO: Fix this so async event won't bind the wrong view post recycle.
    ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Post post = dataSnapshot.getValue(Post.class);
            Log.d(TAG, "post key: " + dataSnapshot.getKey());
            mOnSetupViewListener.onSetupView(holder, post, holder.getAdapterPosition(),
                    dataSnapshot.getKey());
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
            Log.e(TAG, "Error occurred: " + firebaseError.getMessage());
        }
    };
    ref.addValueEventListener(postListener);
    holder.mPostRef = ref;
    holder.mPostListener = postListener;
}
项目:CustomerSupportDesk    文件:FireBaseReferenceHelper.java   
public DatabaseReference complaints() {

        if (complaintsReference == null) {
            complaintsReference = FirebaseDatabase.getInstance().getReference(Config.COMPLAINTS_NODE);
        }

        return complaintsReference;
    }
项目:Programmers    文件:MessagesActivity.java   
@Override
public void handleMessages(String friendId) {

    DatabaseReference userAndFriendMessagesRef = Library.getMessagesRef(friendId);
    messageAdapter = new MessageAdapter(this, userAndFriendMessagesRef);
    recyclerView.setAdapter(messageAdapter);
}
项目:BuddyBook    文件:FirebaseDatabaseHelper.java   
private void insert(DataSnapshot dataSnapshot,OnPaidOperationListener listener, final Book bookApi, DatabaseReference ref){

        if(bookApi.getId() == null ){ //Here we generate our id
            bookApi.setId(ref.push().getKey());
        }

        ref.updateChildren(Collections.singletonMap(bookApi.getId(), (Object) bookApi));
        listener.onInsertBook(true);
    }
项目:chat-sdk-android-push-firebase    文件:BThreadWrapper.java   
public Promise<BThread, BError, Void> recoverPrivateThread(){

        if (DEBUG) Timber.v("recoverPrivateThread");
        final Deferred<BThread, BError, Void> deferred = new DeferredObject<>();
        // Removing the deleted value from firebase.
        DatabaseReference threadUserRef = FirebasePaths.threadRef(entityId)
            .child(BFirebaseDefines.Path.BUsersPath)
            .child(BNetworkManager.sharedManager().getNetworkAdapter().currentUserModel().getEntityID())
            .child(BDefines.Keys.BDeleted);

        threadUserRef.removeValue();

        this.getModel().setDeleted(false);
        this.getModel().setType(BThread.Type.Private);
        final BThread toBeUpdated = this.getModel();
        this.loadMessages().done(new DoneCallback<List<BMessage>>() {
            @Override
            public void onDone(List<BMessage> bMessages) {
                toBeUpdated.setMessages(bMessages);
                DaoCore.updateEntity(toBeUpdated);
                deferred.resolve(toBeUpdated);
            }
        }).fail(new FailCallback<Void>() {
            @Override
            public void onFail(Void aVoid) {
                deferred.resolve(toBeUpdated);
            }
        });
        DaoCore.updateEntity(this.model);

        return deferred.promise();

    }
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testSetAndThenListenForValueEvents()
    throws ExecutionException, TimeoutException, InterruptedException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  new WriteFuture(ref, "cabbage").timedGet();
  EventRecord event = new ReadFuture(ref).timedGet().get(0);

  assertEquals("cabbage", event.getSnapshot().getValue());
}
项目:androidadvanced    文件:FirebaseHelper.java   
public DatabaseReference getChatsReference(String receiver){
    String keySender = getAuthUserEmail().replace(".","_");
    String keyReceiver = receiver.replace(".","_");

    String keyChat = keySender + SEPARATOR + keyReceiver;
    if (keySender.compareTo(keyReceiver) > 0) {
        keyChat = keyReceiver + SEPARATOR + keySender;
    }
    return dataReference.getRoot().child(CHATS_PATH).child(keyChat);
}
项目:firebase-admin-java    文件:Repo.java   
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);
        }
      });
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@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
  }
}
项目:Programmers    文件:Library.java   
public static DatabaseReference getNotificationsRef(String userId) {
    if (notificationsRef == null) {
        notificationsRef = getRootReference().child(AppRules.NOTIFICATIONS)
        .child(userId);
    }
    return notificationsRef;
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@Test
public void testInfoNodeRemoveValue() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.removeValueAsync();
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@Test
public void testInfoNodeChildSetValue() {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference(".info");
  try {
    ref.child("test").setValueAsync("hi");
    fail("Should not be allowed");
  } catch (DatabaseException expected) {
    // No-op, expected
  }
}
项目:firebase-admin-java    文件:InfoTestIT.java   
@Test
public void testInfoServerTimeOffset()
    throws TestFailure, TimeoutException, InterruptedException {
  DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
  DataSnapshot snap =
      new ReadFuture(ref.child(".info/serverTimeOffset")).timedGet().get(0).getSnapshot();
  assertTrue(snap.getValue() instanceof Long);
}
项目:FCM-toolbox    文件:PresenceEventListener.java   
static void updateConnectionReference(DatabaseReference connectionRef, String token) {
    HashMap<String, Object> result = new HashMap<>(3);
    Locale locale = Locale.getDefault();
    final String displayName = Build.MODEL.toLowerCase(locale).startsWith(Build.MANUFACTURER.toLowerCase(locale)) ? Build.MODEL
            : Build.MANUFACTURER.toUpperCase(locale) + " " + Build.MODEL;
    result.put("name", displayName);
    result.put("token", token);
    result.put("timestamp", ServerValue.TIMESTAMP);
    connectionRef.setValue(result);
}
项目:firebase-admin-java    文件:FirebaseDatabaseAuthTestIT.java   
private static void doWrite(
    DatabaseReference ref, final boolean shouldSucceed, final boolean shouldTimeout)
    throws InterruptedException {
  final CountDownLatch lock = new CountDownLatch(1);
  final AtomicBoolean success = new AtomicBoolean(false);
  ApiFutures.addCallback(ref.setValueAsync("wrote something"), new ApiFutureCallback<Void>() {
    @Override
    public void onFailure(Throwable throwable) {
      success.compareAndSet(false, false);
      lock.countDown();
    }

    @Override
    public void onSuccess(Void result) {
      success.compareAndSet(false, true);
      lock.countDown();
    }
  });
  boolean finished = lock.await(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  if (shouldTimeout) {
    assertTrue("Write finished (expected to timeout).", !finished);
  } else if (shouldSucceed) {
    assertTrue("Write timed out (expected to succeed)", finished);
    assertTrue("Write failed (expected to succeed).", success.get());
  } else {
    assertTrue("Write timed out (expected to fail).", finished);
    assertTrue("Write successful (expected to fail).", !success.get());
  }
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testSetChildWithQuote()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ReadFuture readFuture = new ReadFuture(ref);
  new WriteFuture(ref.child("\""), 1).timedGet();
  DataSnapshot snap = readFuture.timedGet().get(0).getSnapshot();
  assertEquals(1L, snap.child("\"").getValue());
}