com.google.cloud.firestore.FirestoreOptions Java Examples

The following examples show how to use com.google.cloud.firestore.FirestoreOptions. 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: FirestoreClient.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private FirestoreClient(FirebaseApp app) {
  checkNotNull(app, "FirebaseApp must not be null");
  String projectId = ImplFirebaseTrampolines.getProjectId(app);
  checkArgument(!Strings.isNullOrEmpty(projectId),
      "Project ID is required for accessing Firestore. Use a service account credential or "
          + "set the project ID explicitly via FirebaseOptions. Alternatively you can also "
          + "set the project ID via the GOOGLE_CLOUD_PROJECT environment variable.");
  FirestoreOptions userOptions = ImplFirebaseTrampolines.getFirestoreOptions(app);
  FirestoreOptions.Builder builder = userOptions != null
      ? userOptions.toBuilder() : FirestoreOptions.newBuilder();
  this.firestore = builder
      // CredentialsProvider has highest priority in FirestoreOptions, so we set that.
      .setCredentialsProvider(
          FixedCredentialsProvider.create(ImplFirebaseTrampolines.getCredentials(app)))
      .setProjectId(projectId)
      .build()
      .getService();
}
 
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: 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: IntegrationTestUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the default FirebaseApp for integration testing (if not already initialized), and
 * returns it. Integration tests that interact with the default FirebaseApp should call this
 * method to obtain the app instance. This method ensures that all integration tests get the
 * same FirebaseApp instance, instead of initializing an app per test.
 *
 * @return the default FirebaseApp instance
 */
public static synchronized FirebaseApp ensureDefaultApp() {
  if (masterApp == null) {
    FirebaseOptions options =
        FirebaseOptions.builder()
            .setDatabaseUrl(getDatabaseUrl())
            .setStorageBucket(getStorageBucket())
            .setCredentials(TestUtils.getCertCredential(getServiceAccountCertificate()))
            .setFirestoreOptions(FirestoreOptions.newBuilder()
                .setTimestampsInSnapshotsEnabled(true)
                .setCredentials(TestUtils.getCertCredential(getServiceAccountCertificate()))
                .build())
            .build();
    masterApp = FirebaseApp.initializeApp(options);
  }
  return masterApp;
}
 
Example #5
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 #6
Source File: GcpFirestoreEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoConfigurationEnabled() {
	contextRunner
			.withPropertyValues(
					"spring.cloud.gcp.firestore.emulator.enabled=true",
					"spring.cloud.gcp.firestore.host-port=localhost:9000")
			.run(context -> {
				FirestoreOptions firestoreOptions = context.getBean(FirestoreOptions.class);
				String endpoint =
						((InstantiatingGrpcChannelProvider)
								firestoreOptions.getTransportChannelProvider()).getEndpoint();
				assertThat(endpoint).isEqualTo("localhost:9000");

				FirestoreTemplate firestoreTemplate = context.getBean(FirestoreTemplate.class);
				assertThat(firestoreTemplate.isUsingStreamTokens()).isFalse();
			});
}
 
Example #7
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 #8
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 #9
Source File: BaseIntegrationTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void baseSetup() throws Exception {
  projectId = getEnvVar("FIRESTORE_PROJECT_ID");
  FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder()
      .setCredentials(GoogleCredentials.getApplicationDefault())
      .setProjectId(projectId)
      .build();
  db = firestoreOptions.getService();
  deleteAllDocuments(db);
}
 
Example #10
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 #11
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 #12
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 #13
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 #14
Source File: GcpFirestoreEmulatorAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoConfigurationDisabled() {
	contextRunner
			.run(context -> {
				FirestoreOptions firestoreOptions = context.getBean(FirestoreOptions.class);
				String endpoint =
						((InstantiatingGrpcChannelProvider)
								firestoreOptions.getTransportChannelProvider()).getEndpoint();
				assertThat(endpoint).isEqualTo("firestore.googleapis.com:443");

				FirestoreTemplate firestoreTemplate = context.getBean(FirestoreTemplate.class);
				assertThat(firestoreTemplate.isUsingStreamTokens()).isTrue();
			});
}
 
Example #15
Source File: FirestoreDataSink.java    From daq with Apache License 2.0 5 votes vote down vote up
public FirestoreDataSink() {
  try {
    Credentials projectCredentials = getProjectCredentials();
    FirestoreOptions firestoreOptions =
        FirestoreOptions.getDefaultInstance().toBuilder()
            .setCredentials(projectCredentials)
            .setProjectId(projectId)
            .setTimestampsInSnapshotsEnabled(true)
            .build();

    db = firestoreOptions.getService();
  } catch (Exception e) {
    throw new RuntimeException("While creating Firestore connection to " + projectId, e);
  }
}
 
Example #16
Source File: GcpFirestoreAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public FirestoreOptions firestoreOptions() {
	return FirestoreOptions.getDefaultInstance().toBuilder()
			.setCredentialsProvider(this.credentialsProvider)
			.setProjectId(this.projectId)
			.setHeaderProvider(USER_AGENT_HEADER_PROVIDER)
			.setChannelProvider(
					InstantiatingGrpcChannelProvider.newBuilder()
							.setEndpoint(this.hostPort)
							.build())
			.build();
}
 
Example #17
Source File: GcpFirestoreEmulatorAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public FirestoreOptions firestoreOptions() {
	return FirestoreOptions.newBuilder()
			.setCredentials(emulatorCredentials())
			.setProjectId(EMULATOR_PROJECT_ID)
			.setChannelProvider(
					InstantiatingGrpcChannelProvider.newBuilder()
							.setEndpoint(this.hostPort)
							.setChannelConfigurator(input -> input.usePlaintext())
							.build())
			.build();
}
 
Example #18
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createOptionsWithAllValuesSet() throws IOException {
  GsonFactory jsonFactory = new GsonFactory();
  NetHttpTransport httpTransport = new NetHttpTransport();
  FirestoreOptions firestoreOptions = FirestoreOptions.newBuilder()
      .setTimestampsInSnapshotsEnabled(true)
      .build();
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setDatabaseUrl(FIREBASE_DB_URL)
          .setStorageBucket(FIREBASE_STORAGE_BUCKET)
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .setProjectId(FIREBASE_PROJECT_ID)
          .setJsonFactory(jsonFactory)
          .setHttpTransport(httpTransport)
          .setThreadManager(MOCK_THREAD_MANAGER)
          .setConnectTimeout(30000)
          .setReadTimeout(60000)
          .setFirestoreOptions(firestoreOptions)
          .build();
  assertEquals(FIREBASE_DB_URL, firebaseOptions.getDatabaseUrl());
  assertEquals(FIREBASE_STORAGE_BUCKET, firebaseOptions.getStorageBucket());
  assertEquals(FIREBASE_PROJECT_ID, firebaseOptions.getProjectId());
  assertSame(jsonFactory, firebaseOptions.getJsonFactory());
  assertSame(httpTransport, firebaseOptions.getHttpTransport());
  assertSame(MOCK_THREAD_MANAGER, firebaseOptions.getThreadManager());
  assertEquals(30000, firebaseOptions.getConnectTimeout());
  assertEquals(60000, firebaseOptions.getReadTimeout());
  assertSame(firestoreOptions, firebaseOptions.getFirestoreOptions());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
}
 
Example #19
Source File: GcpFirestoreAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public Firestore firestore(FirestoreOptions firestoreOptions) {
	return firestoreOptions.getService();
}
 
Example #20
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 #21
Source File: FirebaseOptions.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
FirestoreOptions getFirestoreOptions() {
  return firestoreOptions;
}
 
Example #22
Source File: ImplFirebaseTrampolines.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public static FirestoreOptions getFirestoreOptions(@NonNull FirebaseApp app) {
  return app.getOptions().getFirestoreOptions();
}
 
Example #23
Source File: FirebaseOptions.java    From firebase-admin-java with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the <code>FirestoreOptions</code> used to initialize Firestore in the
 * {@link com.google.firebase.cloud.FirestoreClient} API. This can be used to customize
 * low-level transport (GRPC) parameters, and timestamp handling behavior.
 *
 * <p>If credentials or a project ID is set in <code>FirestoreOptions</code>, they will get
 * overwritten by the corresponding parameters in <code>FirebaseOptions</code>.
 *
 * @param firestoreOptions A <code>FirestoreOptions</code> instance.
 * @return This <code>Builder</code> instance is returned so subsequent calls can be chained.
 */
public Builder setFirestoreOptions(FirestoreOptions firestoreOptions) {
  this.firestoreOptions = firestoreOptions;
  return this;
}