com.google.cloud.firestore.QueryDocumentSnapshot Java Examples

The following examples show how to use com.google.cloud.firestore.QueryDocumentSnapshot. 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: MyDataStore.java    From smart-home-java with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: FirestoreSessionFilter.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init(FilterConfig config) throws ServletException {
  // Initialize local copy of datastore session variables.
  firestore = FirestoreOptions.getDefaultInstance().getService();
  sessions = firestore.collection("sessions");

  try {
    // Delete all sessions unmodified for over two days.
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.HOUR, -48);
    Date twoDaysAgo = Calendar.getInstance().getTime();
    QuerySnapshot sessionDocs =
        sessions.whereLessThan("lastModified", dtf.format(twoDaysAgo)).get().get();
    for (QueryDocumentSnapshot snapshot : sessionDocs.getDocuments()) {
      snapshot.getReference().delete();
    }
  } catch (InterruptedException | ExecutionException e) {
    throw new ServletException("Exception initializing FirestoreSessionFilter.", e);
  }
}
 
Example #3
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete a collection in batches to avoid out-of-memory errors.
 * Batch size may be tuned based on document size (atmost 1MB) and application requirements.
 */
void deleteCollection(CollectionReference collection, int batchSize) {
  try {
    // retrieve a small batch of documents to avoid out-of-memory errors
    ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
    int deleted = 0;
    // future.get() blocks on document retrieval
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      document.getReference().delete();
      ++deleted;
    }
    if (deleted >= batchSize) {
      // retrieve and delete another batch
      deleteCollection(collection, batchSize);
    }
  } catch (Exception e) {
    System.err.println("Error deleting collection : " + e.getMessage());
  }
}
 
Example #4
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Example of a paginated query. */
List<Query> paginateCursor() throws InterruptedException, ExecutionException, TimeoutException {
  // [START fs_paginate_cursor]
  // Construct query for first 25 cities, ordered by population.
  CollectionReference cities = db.collection("cities");
  Query firstPage = cities.orderBy("population").limit(25);

  // Wait for the results of the API call, waiting for a maximum of 30 seconds for a result.
  ApiFuture<QuerySnapshot> future = firstPage.get();
  List<QueryDocumentSnapshot> docs = future.get(30, TimeUnit.SECONDS).getDocuments();

  // Construct query for the next 25 cities.
  QueryDocumentSnapshot lastDoc = docs.get(docs.size() - 1);
  Query secondPage = cities.orderBy("population").startAfter(lastDoc).limit(25);

  future = secondPage.get();
  docs = future.get(30, TimeUnit.SECONDS).getDocuments();
  // [END fs_paginate_cursor]
  return Arrays.asList(firstPage, secondPage);
}
 
Example #5
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void retrieveAllDocuments() throws Exception {
  // [START fs_get_all]
  // asynchronously retrieve all users
  ApiFuture<QuerySnapshot> query = db.collection("users").get();
  // ...
  // query.get() blocks on response
  QuerySnapshot querySnapshot = query.get();
  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")) {
      System.out.println("Middle: " + document.getString("middle"));
    }
    System.out.println("Last: " + document.getString("last"));
    System.out.println("Born: " + document.getLong("born"));
  }
  // [END fs_get_all]
}
 
Example #6
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void runAQuery() throws Exception {
  // [START fs_add_query]
  // asynchronously query for all users born before 1900
  ApiFuture<QuerySnapshot> query =
      db.collection("users").whereLessThan("born", 1900).get();
  // ...
  // query.get() blocks on response
  QuerySnapshot querySnapshot = query.get();
  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")) {
      System.out.println("Middle: " + document.getString("middle"));
    }
    System.out.println("Last: " + document.getString("last"));
    System.out.println("Born: " + document.getLong("born"));
  }
  // [END fs_add_query]
}
 
Example #7
Source File: Guestbook.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Query Firstore for Guestbook greetings */
public List<Greeting> getGreetings() {
  // Initialize a List for Greetings.
  ImmutableList.Builder<Greeting> greetings = new ImmutableList.Builder<Greeting>();
  // Construct query.
  ApiFuture<QuerySnapshot> query =
      bookRef.collection("Greetings").orderBy("date", Direction.DESCENDING).get();

  try {
    // Get query documents.
    QuerySnapshot querySnapshot = query.get();
    for (QueryDocumentSnapshot greeting : querySnapshot.getDocuments()) {
      greetings.add(greeting.toObject(Greeting.class));
    }
  } catch (Exception e) {
    System.out.println(e.getMessage());
  }

  return greetings.build();
}
 
Example #8
Source File: TranslateServlet.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@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: FirestoreProtoClient.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public MessageWithId getDocumentFromCollection(
    String path, Message.Builder builder, boolean shouldRemove) {
  try {
    QuerySnapshot querySnapshot = getCollectionReference(path).limit(1).get().get();
    if (querySnapshot.isEmpty()) {
      return null;
    }
    QueryDocumentSnapshot queryDocumentSnapshot = querySnapshot.getDocuments().get(0);
    MessageWithId result =
        MessageWithId.create(
            queryDocumentSnapshot.getId(), parseProto(queryDocumentSnapshot, builder));
    if (shouldRemove) {
      deleteDocument(path + "/" + queryDocumentSnapshot.getId());
    }
    return result;
  } catch (ExecutionException | InterruptedException | InvalidProtocolBufferException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #10
Source File: FirestoreDao.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
private List<Book> documentsToBooks(List<QueryDocumentSnapshot> documents) {
  List<Book> resultBooks = new ArrayList<>();
  for (QueryDocumentSnapshot snapshot : documents) {
    resultBooks.add(documentToBook(snapshot));
  }
  return resultBooks;
}
 
Example #11
Source File: UserJourneyTestIT.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDownClass() throws ExecutionException, InterruptedException {
  // Clear the firestore list if we're not using the local emulator
  Firestore firestore = FirestoreOptions.getDefaultInstance().getService();
  for (QueryDocumentSnapshot docSnapshot :
      firestore.collection("translations").get().get().getDocuments()) {
    try {
      docSnapshot.getReference().delete().get();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
  }

  service.stop();
}
 
Example #12
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #13
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Return all documents in the cities collection.
 *
 * @return list of documents
 */
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<QueryDocumentSnapshot> documents = future.get().getDocuments();
  for (QueryDocumentSnapshot document : documents) {
    System.out.println(document.getId() + " => " + document.toObject(City.class));
  }
  // [END fs_get_all_docs]
  return documents;
}
 
Example #14
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public List<Message> getProtoDocuments(String path, Message.Builder builder) {
  ImmutableList.Builder<Message> result = ImmutableList.builder();
  try {
    Message proto = builder.build();
    QuerySnapshot querySnapshot = getDocumentsAsync(path).get();
    for (QueryDocumentSnapshot document : querySnapshot.getDocuments()) {
      result.add(parseProto(document, builder));
    }
    return result.build();
  } catch (ExecutionException | InterruptedException | InvalidProtocolBufferException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #15
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleCursorConditions() throws Exception {
  // populate us_cities collection
  Map<String, String> city1 = new ImmutableMap.Builder<String, String>()
      .put("name", "Springfield").put("state", "Massachusetts").build();
  Map<String, String> city2 = new ImmutableMap.Builder<String, String>()
      .put("name", "Springfield").put("state", "Missouri").build();
  Map<String, String> city3 = new ImmutableMap.Builder<String, String>()
      .put("name", "Springfield").put("state", "Wisconsin").build();

  db.collection("us_cities").document("Massachusetts").set(city1).get();
  db.collection("us_cities").document("Missouri").set(city2).get();
  db.collection("us_cities").document("Wisconsin").set(city3).get();

  Query query1 = db.collection("us_cities")
      .orderBy("name")
      .orderBy("state")
      .startAt("Springfield");

  // all documents are retrieved
  QuerySnapshot querySnapshot = query1.get().get();
  List<QueryDocumentSnapshot> docs = querySnapshot.getDocuments();
  assertEquals(3, docs.size());


  // Will return "Springfield, Missouri" and "Springfield, Wisconsin"
  Query query2 = db.collection("us_cities")
      .orderBy("name")
      .orderBy("state")
      .startAt("Springfield", "Missouri");

  // only Missouri and Wisconsin are retrieved
  List<String> expectedResults = Arrays.asList("Missouri", "Wisconsin");
  List<String> result = getResults(query2);
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #16
Source File: RetrieveDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: RetrieveDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: UserJourneyTestIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDownClass() throws ExecutionException, InterruptedException {
  // Clear the firestore sessions data.
  Firestore firestore = FirestoreOptions.getDefaultInstance().getService();
  for (QueryDocumentSnapshot docSnapshot :
      firestore.collection("books").get().get().getDocuments()) {
    docSnapshot.getReference().delete().get();
  }

  service.stop();
}
 
Example #19
Source File: SmartHomeEndToEndTest.java    From smart-home-java with Apache License 2.0 4 votes vote down vote up
@Test
void testCreateSyncUpdateDelete() throws ExecutionException, InterruptedException {
  Map<String, Object> deviceCreate = new HashMap<>();
  deviceCreate.put("userId", USER_ID);
  Map<String, Object> deviceData = new HashMap<>();
  deviceData.put("deviceId", DEVICE_ID);
  deviceData.put("name", DEVICE_NAME);
  deviceData.put("type", DEVICE_TYPE);
  deviceData.put("traits", new ArrayList<String>());
  deviceData.put("defaultNames", new ArrayList<String>());
  deviceData.put("nicknames", new ArrayList<String>());
  deviceData.put("willReportState", false);
  deviceData.put("roomHint", DEVICE_PLACEHOLDER);
  deviceData.put("manufacturer", DEVICE_PLACEHOLDER);
  deviceData.put("model", DEVICE_PLACEHOLDER);
  deviceData.put("hwVersion", DEVICE_PLACEHOLDER);
  deviceData.put("swVersion", DEVICE_PLACEHOLDER);
  deviceCreate.put("data", deviceData);
  given()
      .contentType("application/json")
      .body(deviceCreate)
      .when()
      .post("/smarthome/create")
      .then()
      .statusCode(200);

  QueryDocumentSnapshot deviceCreated = MyDataStore.getInstance().getDevices(USER_ID).get(0);
  assertEquals(DEVICE_ID, deviceCreated.get("deviceId"));

  Map<String, Object> syncRequest = new HashMap<>();
  syncRequest.put("requestId", REQUEST_ID);
  List<Map<String, Object>> syncRequestInputs = new ArrayList<>();
  syncRequest.put("inputs", syncRequestInputs);
  Map<String, Object> syncRequestIntent = new HashMap<>();
  syncRequestIntent.put("intent", "action.devices.SYNC");
  syncRequestInputs.add(syncRequestIntent);
  given()
      .contentType("application/json")
      .body(syncRequest)
      .when()
      .post("/smarthome")
      .then()
      .statusCode(200)
      .body(
          "requestId", equalTo(REQUEST_ID),
          "payload.devices[0].id", equalTo(DEVICE_ID),
          "payload.devices[0].name.name", equalTo(DEVICE_NAME),
          "payload.devices[0].type", equalTo(DEVICE_TYPE));

  Map<String, Object> deviceUpdate = new HashMap<>();
  deviceUpdate.put("userId", USER_ID);
  deviceUpdate.put("deviceId", DEVICE_ID);
  deviceUpdate.put("name", DEVICE_NAME_UPDATED);
  deviceUpdate.put("type", DEVICE_TYPE);
  given()
      .contentType("application/json")
      .body(deviceUpdate)
      .when()
      .post("/smarthome/update")
      .then()
      .statusCode(200);

  QueryDocumentSnapshot deviceUpdated = MyDataStore.getInstance().getDevices(USER_ID).get(0);
  assertEquals(DEVICE_NAME_UPDATED, deviceUpdated.get("name"));

  Map<String, Object> deviceDelete = new HashMap<>();
  deviceDelete.put("userId", USER_ID);
  deviceDelete.put("deviceId", DEVICE_ID);
  given()
      .contentType("application/json")
      .body(deviceDelete)
      .when()
      .post("/smarthome/delete")
      .then()
      .statusCode(200);

  assertEquals(0, MyDataStore.getInstance().getDevices(USER_ID).size());
}
 
Example #20
Source File: MyDataStore.java    From smart-home-java with Apache License 2.0 4 votes vote down vote up
public List<QueryDocumentSnapshot> getDevices(String userId)
    throws ExecutionException, InterruptedException {
  ApiFuture<QuerySnapshot> deviceQuery =
      database.collection("users").document(userId).collection("devices").get();
  return deviceQuery.get().getDocuments();
}