Skip to content

Commit

Permalink
Snippets and tests for Firestore listens (#995)
Browse files Browse the repository at this point in the history
* Snippets and tests for Firestore listens

* Fix comment block

Change-Id: Iab845387ba4188334abd75e7ae0d84bcc3f2f6f9

* Update to 0.33 SDK

Change-Id: I9880508d0ac60cc886df940c43b4d720c129ce2f

* Fix checkstyle issues

Change-Id: Id5074a918a89ba8162b839f01ee213b607dc685b

* Suppress name warning

Change-Id: If24e4daa22b2581e93d50106f65cbc16ad583d0c
  • Loading branch information
samtstern authored and kurtisvg committed Jan 19, 2018
1 parent d450027 commit e0245f6
Show file tree
Hide file tree
Showing 11 changed files with 396 additions and 86 deletions.
2 changes: 1 addition & 1 deletion firestore/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
<version>0.32.0-beta</version>
<version>0.33.0-beta</version>
</dependency>
<!-- [END fs-maven] -->

Expand Down
11 changes: 5 additions & 6 deletions firestore/src/main/java/com/example/firestore/Quickstart.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@

import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
// [START fs_include_dependencies]
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
// [END fs_include_dependencies]
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.firestore.WriteResult;
import com.google.common.collect.ImmutableMap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -126,8 +125,8 @@ void runAQuery() throws Exception {
// ...
// query.get() blocks on response
QuerySnapshot querySnapshot = query.get();
List<DocumentSnapshot> documents = querySnapshot.getDocuments();
for (DocumentSnapshot document : documents) {
List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
for (QueryDocumentSnapshot document : documents) {
System.out.println("User: " + document.getId());
System.out.println("First: " + document.getString("first"));
if (document.contains("middle")) {
Expand All @@ -146,8 +145,8 @@ void retrieveAllDocuments() throws Exception {
// ...
// query.get() blocks on response
QuerySnapshot querySnapshot = query.get();
List<DocumentSnapshot> documents = querySnapshot.getDocuments();
for (DocumentSnapshot document : documents) {
List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
for (QueryDocumentSnapshot document : documents) {
System.out.println("User: " + document.getId());
System.out.println("First: " + document.getString("first"));
if (document.contains("middle")) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.firestore.snippets;

import com.google.api.core.SettableApiFuture;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentChange.Type;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.EventListener;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreException;
import com.google.cloud.firestore.ListenerRegistration;
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;

/**
* Snippets to demonstrate Firestore 'listen' operations.
*/
@SuppressWarnings("Convert2Lambda")
public class ListenDataSnippets {

private static final long TIMEOUT_SECONDS = 5;

private final Firestore db;

ListenDataSnippets(Firestore db) {
this.db = db;
}

/**
* Listen to a single document, returning data after the first snapshot.
*/
Map<String, Object> listenToDocument() throws Exception {
final SettableApiFuture<Map<String, Object>> future = SettableApiFuture.create();

// [START listen_to_document]
DocumentReference docRef = db.collection("cities").document("SF");
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot,
@Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}

if (snapshot != null && snapshot.exists()) {
System.out.println("Current data: " + snapshot.getData());
} else {
System.out.print("Current data: null");
}
// [START_EXCLUDE silent]
if (!future.isDone()) {
future.set(snapshot.getData());
}
// [END_EXCLUDE]
}
});
// [END listen_to_document]

return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}

/**
* Listen to a query, returning the names of all cities in the first snapshot.
*/
List<String> listenForMultiple() throws Exception {
final SettableApiFuture<List<String>> future = SettableApiFuture.create();

// [START listen_to_multiple]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot snapshots,
@Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed:" + e);
return;
}

List<String> cities = new ArrayList<>();
for (DocumentSnapshot doc : snapshots) {
if (doc.get("name") != null) {
cities.add(doc.getString("name"));
}
}
System.out.println("Current cites in CA: " + cities);
// [START_EXCLUDE silent]
if (!future.isDone()) {
future.set(cities);
}
// [END_EXCLUDE]
}
});
// [END listen_to_multiple]

return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}

/**
* Listen to a query, returning the list of DocumentChange events in the first snapshot.
*/
List<DocumentChange> listenForChanges() throws Exception {
SettableApiFuture<List<DocumentChange>> future = SettableApiFuture.create();

// [START listen_for_changes]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot snapshots,
@Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}

for (DocumentChange dc : snapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
System.out.println("New city: " + dc.getDocument().getData());
break;
case MODIFIED:
System.out.println("Modified city: " + dc.getDocument().getData());
break;
case REMOVED:
System.out.println("Removed city: " + dc.getDocument().getData());
break;
default:
break;
}
}
// [START_EXCLUDE silent]
if (!future.isDone()) {
future.set(snapshots.getDocumentChanges());
}
// [END_EXCLUDE]
}
});
// [END listen_for_changes]

return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}

/**
* Demonstrate how to detach an event listener.
*/
void detachListener() {
// [START detach_errors]
Query query = db.collection("cities");
ListenerRegistration registration = query.addSnapshotListener(
new EventListener<QuerySnapshot>() {
// [START_EXCLUDE]
@Override
public void onEvent(@Nullable QuerySnapshot snapshots,
@Nullable FirestoreException e) {

}
// [END_EXCLUDE]
});

// ...

// Stop listening to changes
registration.remove();
// [END detach_errors]
}

/**
* Demonstrate how to handle listening errors.
*/
void listenErrors() {
// [START listen_errors]
db.collection("cities")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot snapshots,
@Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}

for (DocumentChange dc : snapshots.getDocumentChanges()) {
if (dc.getType() == Type.ADDED) {
System.out.println("New city: " + dc.getDocument().getData());
}
}
}
});
// [END listen_errors]
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.FieldValue;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.firestore.SetOptions;
import com.google.cloud.firestore.Transaction;
Expand Down Expand Up @@ -294,8 +295,8 @@ void deleteCollection(CollectionReference collection, int batchSize) {
ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
int deleted = 0;
// future.get() blocks on document retrieval
List<DocumentSnapshot> documents = future.get().getDocuments();
for (DocumentSnapshot document : documents) {
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
for (QueryDocumentSnapshot document : documents) {
document.getReference().delete();
++deleted;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.firestore.WriteResult;

Expand Down Expand Up @@ -106,13 +107,13 @@ public City getDocumentAsEntity() throws Exception {
*
* @return list of documents of capital cities.
*/
public List<DocumentSnapshot> getQueryResults() throws Exception {
public List<QueryDocumentSnapshot> getQueryResults() throws Exception {
// [START fs_get_multiple_docs]
//asynchronously retrieve multiple documents
ApiFuture<QuerySnapshot> future =
db.collection("cities").whereEqualTo("capital", true).get();
// future.get() blocks on response
List<DocumentSnapshot> documents = future.get().getDocuments();
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
for (DocumentSnapshot document : documents) {
System.out.println(document.getId() + " => " + document.toObject(City.class));
}
Expand All @@ -125,13 +126,13 @@ public List<DocumentSnapshot> getQueryResults() throws Exception {
*
* @return list of documents
*/
public List<DocumentSnapshot> getAllDocuments() throws Exception {
public List<QueryDocumentSnapshot> getAllDocuments() throws Exception {
// [START fs_get_all_docs]
//asynchronously retrieve all documents
ApiFuture<QuerySnapshot> future = db.collection("cities").get();
// future.get() blocks on response
List<DocumentSnapshot> documents = future.get().getDocuments();
for (DocumentSnapshot document : documents) {
List<QueryDocumentSnapshot> documents = future.get().getDocuments();
for (QueryDocumentSnapshot document : documents) {
System.out.println(document.getId() + " => " + document.toObject(City.class));
}
// [END fs_get_all_docs]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.firestore;

import com.example.firestore.snippets.ManageDataSnippetsIT;
import com.example.firestore.snippets.model.City;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
import com.google.cloud.firestore.QuerySnapshot;
import java.util.Map;
import org.junit.BeforeClass;

/**
* Base class for tests like {@link ManageDataSnippetsIT}.
*/
public class BaseIntegrationTest {

protected static String projectId = "java-docs-samples-firestore";
protected static Firestore db;

@BeforeClass
public static void baseSetup() throws Exception {
FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder()
.setProjectId(projectId)
.build();
db = firestoreOptions.getService();
deleteAllDocuments(db);
}

protected DocumentSnapshot getDocumentData(DocumentReference docRef) throws Exception {
return docRef.get().get();
}

protected Map<String, Object> getDocumentDataAsMap(DocumentReference docRef) throws Exception {
DocumentSnapshot snapshot = docRef.get().get();
if (!snapshot.exists()) {
throw new RuntimeException("Document does not exist: " + docRef.getPath());
}

return snapshot.getData();
}

protected City getDocumentDataAsCity(DocumentReference docRef) throws Exception {
return docRef.get().get().toObject(City.class);
}

protected static void deleteAllDocuments(Firestore db) throws Exception {
ApiFuture<QuerySnapshot> future = db.collection("cities").get();
QuerySnapshot querySnapshot = future.get();
for (DocumentSnapshot doc : querySnapshot.getDocuments()) {
// block on delete operation
db.collection("cities").document(doc.getId()).delete().get();
}
}

}
Loading

0 comments on commit e0245f6

Please sign in to comment.