com.google.cloud.firestore.DocumentSnapshot Java Examples
The following examples show how to use
com.google.cloud.firestore.DocumentSnapshot.
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: QueryDataSnippets.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Creates a sample query. * * @return query */ Query createAQueryAlternate() throws Exception { // [START fs_create_query_country] // Create a reference to the cities collection CollectionReference cities = db.collection("cities"); // Create a query against the collection. Query query = cities.whereEqualTo("state", "CA"); // 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_country] return query; }
Example #2
Source File: FirestoreSessionFilter.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Take an HttpServletRequest, and copy all of the current session variables over to it * * @param req Request from which to extract session. * @return a map of strings containing all the session variables loaded or an empty map. */ private Map<String, Object> loadSessionVariables(HttpServletRequest req) throws ExecutionException, InterruptedException { Map<String, Object> datastoreMap = new HashMap<>(); String sessionId = getCookieValue(req, "bookshelfSessionId"); if (sessionId.equals("")) { return datastoreMap; } return firestore .runTransaction( (ob) -> { DocumentSnapshot session = sessions.document(sessionId).get().get(); Map<String, Object> data = session.getData(); if (data == null) { data = Maps.newHashMap(); } return data; }) .get(); }
Example #3
Source File: ManageDataSnippets.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Return information from a conditional transaction. * * * @param population : set initial population. */ String returnInfoFromTransaction(long population) throws Exception { Map<String, Object> map = new HashMap<>(); map.put("population", population); // Block until transaction is complete is using transaction.get() db.collection("cities").document("SF").set(map).get(); // [START fs_return_info_transaction] final DocumentReference docRef = db.collection("cities").document("SF"); ApiFuture<String> futureTransaction = db.runTransaction(transaction -> { DocumentSnapshot snapshot = transaction.get(docRef).get(); Long newPopulation = snapshot.getLong("population") + 1; // conditionally update based on current population if (newPopulation <= 1000000L) { transaction.update(docRef, "population", newPopulation); return "Population increased to " + newPopulation; } else { throw new Exception("Sorry! Population is too big."); } }); // Print information retrieved from transaction System.out.println(futureTransaction.get()); // [END fs_return_info_transaction] return futureTransaction.get(); }
Example #4
Source File: ManageDataSnippets.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** 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> futureTransaction = db.runTransaction(transaction -> { // 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; }); // block on transaction operation using transaction.get() // [END fs_run_simple_transaction] return futureTransaction; }
Example #5
Source File: MyDataStore.java From smart-home-java with Apache License 2.0 | 6 votes |
public String getUserId(String token) throws ExecutionException, InterruptedException { if (token == null) { token = "Bearer 123access"; } ApiFuture<QuerySnapshot> userQuery = database.collection("users").whereEqualTo("fakeAccessToken", token.substring(7)).get(); QuerySnapshot usersSnapshot = userQuery.get(); List<QueryDocumentSnapshot> users = usersSnapshot.getDocuments(); DocumentSnapshot user; try { user = users.get(0); } catch (Exception e) { LOGGER.error("no user found!"); throw e; } return user.getId(); }
Example #6
Source File: QueryDataSnippets.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * 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; }
Example #7
Source File: FirestoreDao.java From getting-started-java with Apache License 2.0 | 6 votes |
private Book documentToBook(DocumentSnapshot document) { Map<String, Object> data = document.getData(); if (data == null) { System.out.println("No data in document " + document.getId()); return null; } return new Book.Builder() .author((String) data.get(Book.AUTHOR)) .description((String) data.get(Book.DESCRIPTION)) .publishedDate((String) data.get(Book.PUBLISHED_DATE)) .imageUrl((String) data.get(Book.IMAGE_URL)) .createdBy((String) data.get(Book.CREATED_BY)) .createdById((String) data.get(Book.CREATED_BY_ID)) .title((String) data.get(Book.TITLE)) .id(document.getId()) .build(); }
Example #8
Source File: TranslateServlet.java From getting-started-java with Apache License 2.0 | 6 votes |
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore"); CollectionReference translations = firestore.collection("translations"); QuerySnapshot snapshot; try { snapshot = translations.limit(10).get().get(); } catch (InterruptedException | ExecutionException e) { throw new ServletException("Exception retrieving documents from Firestore.", e); } List<TranslateMessage> translateMessages = Lists.newArrayList(); List<QueryDocumentSnapshot> documents = Lists.newArrayList(snapshot.getDocuments()); documents.sort(Comparator.comparing(DocumentSnapshot::getCreateTime)); for (DocumentSnapshot document : Lists.reverse(documents)) { String encoded = gson.toJson(document.getData()); TranslateMessage message = gson.fromJson(encoded, TranslateMessage.class); message.setData(decode(message.getData())); translateMessages.add(message); } req.setAttribute("messages", translateMessages); req.setAttribute("page", "list"); req.getRequestDispatcher("/base.jsp").forward(req, resp); }
Example #9
Source File: ProtoQuerySnapshot.java From startup-os with Apache License 2.0 | 6 votes |
public ProtoQuerySnapshot(QuerySnapshot querySnapshot, Message.Builder builder) throws InvalidProtocolBufferException { // TODO: Avoid parsing the same objects twice in getDocuments() and getDocumentChanges(). ImmutableList.Builder<T> protos = ImmutableList.builder(); for (DocumentSnapshot docSnapshot : querySnapshot.getDocuments()) { protos.add((T) FirestoreProtoClient.parseProto(docSnapshot, builder)); } this.protos = protos.build(); ImmutableList.Builder<ProtoChange<T>> protoChanges = ImmutableList.builder(); for (DocumentChange docChange : querySnapshot.getDocumentChanges()) { T proto = (T) FirestoreProtoClient.parseProto(docChange.getDocument(), builder); protoChanges.add( new ProtoChange<T>( proto, docChange.getNewIndex(), docChange.getOldIndex(), convertChangeType(docChange.getType()))); } this.protoChanges = protoChanges.build(); }
Example #10
Source File: ManageDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testUpdateServerTimestamp() throws Exception { manageDataSnippets.updateServerTimestamp(); DocumentReference docRef = db.collection("objects").document("some-id"); DocumentSnapshot data = getDocumentData(docRef); assertTrue(data.getDate("timestamp") instanceof Date); }
Example #11
Source File: QuickstartIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
private void deleteAllDocuments() throws Exception { ApiFuture<QuerySnapshot> future = db.collection("users").get(); QuerySnapshot querySnapshot = future.get(); for (DocumentSnapshot doc : querySnapshot.getDocuments()) { // block on delete operation db.document("users/" + doc.getId()).delete().get(); } }
Example #12
Source File: QueryDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
private List<String> getResults(Query query) throws Exception { // asynchronously retrieve query results ApiFuture<QuerySnapshot> future = query.get(); // block on response QuerySnapshot querySnapshot = future.get(); List<String> docIds = new ArrayList<>(); for (DocumentSnapshot document : querySnapshot.getDocuments()) { docIds.add(document.getId()); } return docIds; }
Example #13
Source File: BaseIntegrationTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
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(); } }
Example #14
Source File: BaseIntegrationTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
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(); }
Example #15
Source File: ManageDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testUpdateNestedFields() throws Exception { manageDataSnippets.updateNestedFields(); DocumentReference docRef = db.collection("users").document("frank"); DocumentSnapshot snapshot = getDocumentData(docRef); assertEquals((long) snapshot.getLong("age"), 13); assertEquals(snapshot.getString("favorites.color"), "Red"); assertEquals(snapshot.getString("favorites.food"), "Pizza"); }
Example #16
Source File: ListenDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * 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); }
Example #17
Source File: ListenDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * 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); }
Example #18
Source File: MyDataStore.java From smart-home-java with Apache License 2.0 | 5 votes |
public Map<String, Object> getState(String userId, String deviceId) throws ExecutionException, InterruptedException { DocumentSnapshot device = database .collection("users") .document(userId) .collection("devices") .document(deviceId) .get() .get(); return (Map<String, Object>) device.get("states"); }
Example #19
Source File: QueryDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * Create a query using a snapshot as a start point. * * @return query */ Query createStartAtSnapshotQueryCursor() throws InterruptedException, ExecutionException, TimeoutException { // [START fs_document_snapshot_cursor] // Fetch the snapshot with an API call, waiting for a maximum of 30 seconds for a result. ApiFuture<DocumentSnapshot> future = db.collection("cities").document("SF").get(); DocumentSnapshot snapshot = future.get(30, TimeUnit.SECONDS); // Construct the query Query query = db.collection("cities").orderBy("population").startAt(snapshot); // [END fs_document_snapshot_cursor] return query; }
Example #20
Source File: FirestoreProtoClient.java From startup-os with Apache License 2.0 | 5 votes |
public static Message parseProto(DocumentSnapshot document, Message.Builder builder) throws InvalidProtocolBufferException { return builder .build() .getParserForType() .parseFrom(Base64.getDecoder().decode(document.getString(PROTO_FIELD))); }
Example #21
Source File: RetrieveDataSnippets.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * Return multiple documents from a collection based on a query. * * @return list of documents of capital cities. */ 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<QueryDocumentSnapshot> documents = future.get().getDocuments(); for (DocumentSnapshot document : documents) { System.out.println(document.getId() + " => " + document.toObject(City.class)); } // [END fs_get_multiple_docs] return documents; }
Example #22
Source File: FirestoreDao.java From getting-started-java with Apache License 2.0 | 5 votes |
@Override public Book readBook(String bookId) { try { DocumentSnapshot document = booksCollection.document(bookId).get().get(); return documentToBook(document); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return null; }
Example #23
Source File: ManageDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testWriteBatchIsSuccessful() throws Exception { manageDataSnippets.writeBatch(); CollectionReference collection = db.collection("cities"); ApiFuture<DocumentSnapshot> document = collection.document("NYC").get(); assertTrue(document.get().exists()); DocumentReference documentReference = collection.document("SF"); Map<String, Object> data = getDocumentDataAsMap(documentReference); assertTrue(data.containsKey("population")); document = collection.document("LA").get(); assertFalse(document.get().exists()); }
Example #24
Source File: FirestoreProtoClient.java From startup-os with Apache License 2.0 | 5 votes |
public DocumentSnapshot getDocument(String path) { try { return getDocumentAsync(path).get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } }
Example #25
Source File: ManageDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testUpdateDocumentIncrementSuccessful() throws Exception { manageDataSnippets.updateDocumentIncrement(); CollectionReference collection = db.collection("cities"); DocumentReference documentReference = collection.document("DC"); final DocumentSnapshot data = documentReference.get().get(); assertTrue(data.contains("population")); assertEquals((Long) 150L, data.getLong("population")); }
Example #26
Source File: RetrieveDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testRetrieveQueryResults() throws Exception { List<QueryDocumentSnapshot> docs = retrieveDataSnippets.getQueryResults(); assertEquals(docs.size(), 3); Set<String> docIds = new HashSet<>(); for (DocumentSnapshot doc : docs) { docIds.add(doc.getId()); } assertTrue(docIds.contains("BJ") && docIds.contains("TOK") && docIds.contains("DC")); }
Example #27
Source File: FirestoreDefaultClassMapper.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
public <T> Document entityToDocument(T entity, String documentResourceName) { DocumentSnapshot documentSnapshot = INTERNAL.snapshotFromObject(NOT_USED_PATH, entity); Map<String, Value> valuesMap = INTERNAL.protoFromSnapshot(documentSnapshot); return Document.newBuilder() .putAllFields(valuesMap) .setName(documentResourceName).build(); }
Example #28
Source File: RetrieveDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Test public void testRetrieveAllDocuments() throws Exception { List<QueryDocumentSnapshot> docs = retrieveDataSnippets.getAllDocuments(); assertEquals(docs.size(), 5); Set<String> docIds = new HashSet<>(); for (DocumentSnapshot doc : docs) { docIds.add(doc.getId()); } assertTrue( docIds.contains("SF") && docIds.contains("LA") && docIds.contains("DC") && docIds.contains("TOK") && docIds.contains("BJ")); }
Example #29
Source File: RetrieveDataSnippetsIT.java From java-docs-samples with Apache License 2.0 | 5 votes |
private static void deleteAllDocuments() 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(); } }
Example #30
Source File: MyDataStore.java From smart-home-java with Apache License 2.0 | 4 votes |
public Boolean isHomegraphEnabled(String userId) throws ExecutionException, InterruptedException { DocumentSnapshot user = database.collection("users").document(userId).get().get(); return (Boolean) user.get("homegraph"); }