com.google.cloud.firestore.Firestore Java Examples

The following examples show how to use com.google.cloud.firestore.Firestore. 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: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize Firestore using default project ID.
 */
public Quickstart() {
  // [START fs_initialize]
  Firestore db = FirestoreOptions.getDefaultInstance().getService();
  // [END fs_initialize]
  this.db = db;
}
 
Example #2
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 #3
Source File: FirestoreClientTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFirestoreOptionsOverride() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(new Builder()
      .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .setProjectId("explicit-project-id")
      .setFirestoreOptions(FirestoreOptions.newBuilder()
          .setTimestampsInSnapshotsEnabled(true)
          .setProjectId("other-project-id")
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .build())
      .build());
  Firestore firestore = FirestoreClient.getFirestore(app);
  assertEquals("explicit-project-id", firestore.getOptions().getProjectId());
  assertTrue(firestore.getOptions().areTimestampsInSnapshotsEnabled());
  assertSame(ImplFirebaseTrampolines.getCredentials(app),
      firestore.getOptions().getCredentialsProvider().getCredentials());

  firestore = FirestoreClient.getFirestore();
  assertEquals("explicit-project-id", firestore.getOptions().getProjectId());
  assertTrue(firestore.getOptions().areTimestampsInSnapshotsEnabled());
  assertSame(ImplFirebaseTrampolines.getCredentials(app),
      firestore.getOptions().getCredentialsProvider().getCredentials());
}
 
Example #4
Source File: FirestoreClientIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFirestoreAccess() throws Exception {
  Firestore firestore = FirestoreClient.getFirestore(IntegrationTestUtils.ensureDefaultApp());
  DocumentReference reference = firestore.collection("cities").document("Mountain View");
  ImmutableMap<String, Object> expected = ImmutableMap.<String, Object>of(
      "name", "Mountain View",
      "country", "USA",
      "population", 77846L,
      "capital", false
  );
  WriteResult result = reference.set(expected).get();
  assertNotNull(result);

  Map<String, Object> data = reference.get().get().getData();
  assertEquals(expected.size(), data.size());
  for (Map.Entry<String, Object> entry : expected.entrySet()) {
    assertEquals(entry.getValue(), data.get(entry.getKey()));
  }

  reference.delete().get();
  assertFalse(reference.get().get().exists());
}
 
Example #5
Source File: FirestoreDocumentationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void writeDocumentFromObject() throws ExecutionException, InterruptedException {
	this.contextRunner.run((context) -> {
		Firestore firestore = context.getBean(Firestore.class);
		FirestoreExample firestoreExample = new FirestoreExample(firestore);

		firestoreExample.writeDocumentFromObject();
		User user = firestoreExample.readDocumentToObject();
		assertThat(user).isEqualTo(new User("Joe",
				Arrays.asList(
						new Phone(12345, PhoneType.CELL),
						new Phone(54321, PhoneType.WORK))));

		firestoreExample.writeDocumentFromObject2();
		user = firestoreExample.readDocumentToObject();
		assertThat(user).isEqualTo(new User("Joseph",
				Arrays.asList(
						new Phone(23456, PhoneType.CELL),
						new Phone(65432, PhoneType.WORK))));
	});
}
 
Example #6
Source File: FirebaseConfiguration.java    From elepy with Apache License 2.0 5 votes vote down vote up
@Override
public void preConfig(ElepyPreConfiguration elepy) {

    if (enableFirestore) {
        elepy.registerDependency(Firestore.class, FirestoreClient.getFirestore(app));
        elepy.withDefaultCrudFactory(FirestoreCrudFactory.class);
    }

    if (bucketName != null) {
        StorageClient client = StorageClient.getInstance(app);
        elepy.withUploads(new CloudStorageFileService(client.bucket(bucketName).getStorage(), bucketName));
    }
}
 
Example #7
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 #8
Source File: BaseIntegrationTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
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 #9
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public Quickstart(String projectId) throws Exception {
  // [START fs_initialize_project_id]
  FirestoreOptions firestoreOptions =
      FirestoreOptions.getDefaultInstance().toBuilder()
          .setProjectId(projectId)
          .setCredentials(GoogleCredentials.getApplicationDefault())
          .build();
  Firestore db = firestoreOptions.getService();
  // [END fs_initialize_project_id]
  this.db = db;
}
 
Example #10
Source File: Persistence.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("JavadocMethod")
public static Firestore getFirestore() {
  if (firestore == null) {
    // Authorized Firestore service
    // [START gae_java11_firestore]
    Firestore db =
        FirestoreOptions.newBuilder().setProjectId("YOUR-PROJECT-ID").build().getService();
    // [END gae_java11_firestore]
    firestore = db;
  }

  return firestore;
}
 
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: BackgroundContextListener.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
  String firestoreProjectId = System.getenv("FIRESTORE_CLOUD_PROJECT");
  Firestore firestore = (Firestore) event.getServletContext().getAttribute("firestore");
  if (firestore == null) {
    firestore =
        FirestoreOptions.getDefaultInstance().toBuilder()
            .setProjectId(firestoreProjectId)
            .build()
            .getService();
    event.getServletContext().setAttribute("firestore", firestore);
  }

  Translate translate = (Translate) event.getServletContext().getAttribute("translate");
  if (translate == null) {
    translate = TranslateOptions.getDefaultInstance().getService();
    event.getServletContext().setAttribute("translate", translate);
  }

  Publisher publisher = (Publisher) event.getServletContext().getAttribute("publisher");
  if (publisher == null) {
    try {
      String topicId = System.getenv("PUBSUB_TOPIC");
      publisher =
          Publisher.newBuilder(
                  ProjectTopicName.newBuilder()
                      .setProject(firestoreProjectId)
                      .setTopic(topicId)
                      .build())
              .build();
      event.getServletContext().setAttribute("publisher", publisher);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example #13
Source File: GcpFirestoreAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testDatastoreOptionsCorrectlySet() {
	this.contextRunner.run((context) -> {
		FirestoreOptions datastoreOptions = context.getBean(Firestore.class).getOptions();
		assertThat(datastoreOptions.getProjectId()).isEqualTo("test-project");
	});
}
 
Example #14
Source File: FirestoreClientTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFirestoreOptions() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(new Builder()
      .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .setProjectId("explicit-project-id")
      .setFirestoreOptions(FIRESTORE_OPTIONS)
      .build());
  Firestore firestore = FirestoreClient.getFirestore(app);
  assertEquals("explicit-project-id", firestore.getOptions().getProjectId());
  assertTrue(firestore.getOptions().areTimestampsInSnapshotsEnabled());

  firestore = FirestoreClient.getFirestore();
  assertEquals("explicit-project-id", firestore.getOptions().getProjectId());
  assertTrue(firestore.getOptions().areTimestampsInSnapshotsEnabled());
}
 
Example #15
Source File: FirestoreClientTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceAccountProjectId() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .setFirestoreOptions(FIRESTORE_OPTIONS)
      .build());
  Firestore firestore = FirestoreClient.getFirestore(app);
  assertEquals("mock-project-id", firestore.getOptions().getProjectId());

  firestore = FirestoreClient.getFirestore();
  assertEquals("mock-project-id", firestore.getOptions().getProjectId());
}
 
Example #16
Source File: FirestoreClientTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExplicitProjectId() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .setProjectId("explicit-project-id")
      .setFirestoreOptions(FIRESTORE_OPTIONS)
      .build());
  Firestore firestore = FirestoreClient.getFirestore(app);
  assertEquals("explicit-project-id", firestore.getOptions().getProjectId());

  firestore = FirestoreClient.getFirestore();
  assertEquals("explicit-project-id", firestore.getOptions().getProjectId());
}
 
Example #17
Source File: FirestoreDocumentationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
FirestoreExample(Firestore firestore) {
	this.firestore = firestore;
}
 
Example #18
Source File: FirebaseFirestoreReactive.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
FirebaseFirestoreReactive(Firestore firestore) {
  this.firestore = firestore;
}
 
Example #19
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 4 votes vote down vote up
public Firestore getClient() {
  return client;
}
 
Example #20
Source File: FirestoreCrudFactory.java    From elepy with Apache License 2.0 4 votes vote down vote up
@Override
public <T> Crud<T> crudFor(Schema<T> type) {
    return new FirestoreCrud<>(elepyContext.getDependency(Firestore.class), type);
}
 
Example #21
Source File: ListenDataSnippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
ListenDataSnippets(Firestore db) {
  this.db = db;
}
 
Example #22
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
ManageDataSnippets(Firestore db) {
  this.db = db;
}
 
Example #23
Source File: References.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public References(Firestore db) {
  this.db = db;
}
 
Example #24
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
QueryDataSnippets(Firestore db) {
  this.db = db;
}
 
Example #25
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
RetrieveDataSnippets(Firestore db) {
  this.db = db;
}
 
Example #26
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
Firestore getDb() {
  return db;
}
 
Example #27
Source File: FirestoreCrud.java    From elepy with Apache License 2.0 4 votes vote down vote up
public FirestoreCrud(Firestore db, Schema<T> schema) {
    this.db = db;
    this.objectMapper = new ObjectMapper();
    this.collection = schema.getPath();
    this.schema = schema;
}
 
Example #28
Source File: Persistence.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void setFirestore(Firestore firestore) {
  Persistence.firestore = firestore;
}
 
Example #29
Source File: FirestoreDao.java    From getting-started-java with Apache License 2.0 4 votes vote down vote up
public FirestoreDao() {
  Firestore firestore = FirestoreOptions.getDefaultInstance().getService();
  booksCollection = firestore.collection("books");
}
 
Example #30
Source File: TranslateServlet.java    From getting-started-java with Apache License 2.0 4 votes vote down vote up
/**
 * Handle a posted message from Pubsub.
 *
 * @param req The message Pubsub posts to this process.
 * @param resp Not used.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {

  // Block requests that don't contain the proper verification token.
  String pubsubVerificationToken = PUBSUB_VERIFICATION_TOKEN;
  if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return;
  }

  // [START getting_started_background_translate_string]
  String body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

  PubSubMessage pubsubMessage = gson.fromJson(body, PubSubMessage.class);
  TranslateMessage message = pubsubMessage.getMessage();

  // Use Translate service client to translate the message.
  Translate translate = (Translate) this.getServletContext().getAttribute("translate");
  message.setData(decode(message.getData()));
  Translation translation =
      translate.translate(
          message.getData(),
          Translate.TranslateOption.sourceLanguage(message.getAttributes().getSourceLang()),
          Translate.TranslateOption.targetLanguage(message.getAttributes().getTargetLang()));
  // [END getting_started_background_translate_string]

  message.setTranslatedText(translation.getTranslatedText());

  try {
    // [START getting_started_background_translate]
    // Use Firestore service client to store the translation in Firestore.
    Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore");

    CollectionReference translations = firestore.collection("translations");

    ApiFuture<WriteResult> setFuture = translations.document().set(message, SetOptions.merge());

    setFuture.get();
    resp.getWriter().write(translation.getTranslatedText());
    // [END getting_started_background_translate]
  } catch (InterruptedException | ExecutionException e) {
    throw new ServletException("Exception storing data in Firestore.", e);
  }
}