Search in sources :

Example 41 with DocumentSnapshot

use of com.google.cloud.firestore.DocumentSnapshot in project java-docs-samples by GoogleCloudPlatform.

the class ListenDataSnippets method listenToDocument.

/**
 * 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]
        }
    });
    return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
Also used : DocumentSnapshot(com.google.cloud.firestore.DocumentSnapshot) FirestoreException(com.google.cloud.firestore.FirestoreException) Map(java.util.Map) DocumentReference(com.google.cloud.firestore.DocumentReference)

Example 42 with DocumentSnapshot

use of com.google.cloud.firestore.DocumentSnapshot in project java-docs-samples by GoogleCloudPlatform.

the class QueryDataSnippets method createAQuery.

/**
 * Creates a sample query.
 *
 * @return query
 */
Query createAQuery() throws Exception {
    // [START fs_create_query]
    // Create a reference to the cities collection
    CollectionReference cities = db.collection("cities");
    // Create a query against the collection.
    Query query = cities.whereEqualTo("capital", true);
    // retrieve  query results asynchronously using query.get()
    ApiFuture<QuerySnapshot> querySnapshot = query.get();
    for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
        System.out.println(document.getId());
    }
    // [END fs_create_query]
    return query;
}
Also used : DocumentSnapshot(com.google.cloud.firestore.DocumentSnapshot) Query(com.google.cloud.firestore.Query) CollectionReference(com.google.cloud.firestore.CollectionReference) QuerySnapshot(com.google.cloud.firestore.QuerySnapshot)

Example 43 with DocumentSnapshot

use of com.google.cloud.firestore.DocumentSnapshot in project java-docs-samples by GoogleCloudPlatform.

the class RetrieveDataSnippets method getDocumentAsMap.

/**
 * Retrieves document in collection as map.
 *
 * @return map (string => object)
 */
public Map<String, Object> getDocumentAsMap() throws Exception {
    // [START fs_get_doc_as_map]
    DocumentReference docRef = db.collection("cities").document("SF");
    // asynchronously retrieve the document
    ApiFuture<DocumentSnapshot> future = docRef.get();
    // ...
    // future.get() blocks on response
    DocumentSnapshot document = future.get();
    if (document.exists()) {
        System.out.println("Document data: " + document.getData());
    } else {
        System.out.println("No such document!");
    }
    // [END fs_get_doc_as_map]
    return (document.exists()) ? document.getData() : null;
}
Also used : QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.cloud.firestore.DocumentSnapshot) DocumentReference(com.google.cloud.firestore.DocumentReference)

Example 44 with DocumentSnapshot

use of com.google.cloud.firestore.DocumentSnapshot in project java-docs-samples by GoogleCloudPlatform.

the class RetrieveDataSnippets method getDocumentAsEntity.

/**
 * Retrieves document in collection as a custom object.
 *
 * @return document data as City object
 */
public City getDocumentAsEntity() throws Exception {
    // [START fs_get_doc_as_entity]
    DocumentReference docRef = db.collection("cities").document("BJ");
    // asynchronously retrieve the document
    ApiFuture<DocumentSnapshot> future = docRef.get();
    // block on response
    DocumentSnapshot document = future.get();
    City city = null;
    if (document.exists()) {
        // convert document to POJO
        city = document.toObject(City.class);
        System.out.println(city);
    } else {
        System.out.println("No such document!");
    }
    // [END fs_get_doc_as_entity]
    return city;
}
Also used : QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.cloud.firestore.DocumentSnapshot) City(com.example.firestore.snippets.model.City) DocumentReference(com.google.cloud.firestore.DocumentReference)

Example 45 with DocumentSnapshot

use of com.google.cloud.firestore.DocumentSnapshot in project java-docs-samples by GoogleCloudPlatform.

the class ManageDataSnippets method runSimpleTransaction.

// [END fs_delete_collection]
/**
 * Run a simple transaction to perform a field value increment.
 *
 * @return transaction future
 */
ApiFuture<Void> runSimpleTransaction() throws Exception {
    // [START fs_run_simple_transaction]
    // Initialize doc
    final DocumentReference docRef = db.collection("cities").document("SF");
    City city = new City("SF");
    city.setCountry("USA");
    city.setPopulation(860000L);
    docRef.set(city).get();
    // run an asynchronous transaction
    ApiFuture<Void> transaction = db.runTransaction(new Transaction.Function<Void>() {

        @Override
        public Void updateCallback(Transaction transaction) throws Exception {
            // retrieve document and increment population field
            DocumentSnapshot snapshot = transaction.get(docRef).get();
            long oldPopulation = snapshot.getLong("population");
            transaction.update(docRef, "population", oldPopulation + 1);
            return null;
        }
    });
    // [END fs_run_simple_transaction]
    return transaction;
}
Also used : QueryDocumentSnapshot(com.google.cloud.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.cloud.firestore.DocumentSnapshot) Transaction(com.google.cloud.firestore.Transaction) City(com.example.firestore.snippets.model.City) DocumentReference(com.google.cloud.firestore.DocumentReference)

Aggregations

DocumentSnapshot (com.google.cloud.firestore.DocumentSnapshot)103 QueryDocumentSnapshot (com.google.cloud.firestore.QueryDocumentSnapshot)73 Test (org.junit.Test)52 DocumentReference (com.google.cloud.firestore.DocumentReference)49 QuerySnapshot (com.google.cloud.firestore.QuerySnapshot)23 ExecutionException (java.util.concurrent.ExecutionException)13 CollectionReference (com.google.cloud.firestore.CollectionReference)12 Query (com.google.cloud.firestore.Query)12 BaseIntegrationTest (com.example.firestore.BaseIntegrationTest)10 SingleField (com.google.cloud.firestore.LocalFirestoreHelper.SingleField)9 WriteResult (com.google.cloud.firestore.WriteResult)9 ArrayList (java.util.ArrayList)8 FileSystemExecutionException (bio.terra.service.filedata.exception.FileSystemExecutionException)6 HashMap (java.util.HashMap)6 BulkWriter (com.google.cloud.firestore.BulkWriter)5 City (com.example.firestore.snippets.model.City)4 Timestamp (com.google.cloud.Timestamp)4 FirestoreBundleTest.verifyNamedQuery (com.google.cloud.firestore.FirestoreBundleTest.verifyNamedQuery)4 AllSupportedTypes (com.google.cloud.firestore.LocalFirestoreHelper.AllSupportedTypes)4 WriteBatch (com.google.cloud.firestore.WriteBatch)4