com.google.firebase.FirebaseOptions Java Examples

The following examples show how to use com.google.firebase.FirebaseOptions. 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: FirebaseRequestInitializerTest.java    From firebase-admin-java with Apache License 2.0 8 votes vote down vote up
@Test
public void testCredentialsRetryHandler() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("token"))
      .build());
  RetryConfig retryConfig = RetryConfig.builder()
      .setMaxRetries(MAX_RETRIES)
      .build();
  CountingLowLevelHttpRequest countingRequest = CountingLowLevelHttpRequest.fromStatus(401);
  HttpRequest request = TestUtils.createRequest(countingRequest);
  FirebaseRequestInitializer initializer = new FirebaseRequestInitializer(app, retryConfig);
  initializer.initialize(request);
  request.getHeaders().setAuthorization((String) null);

  try {
    request.execute();
  } catch (HttpResponseException e) {
    assertEquals(401, e.getStatusCode());
  }

  assertEquals("Bearer token", request.getHeaders().getAuthorization());
  assertEquals(MAX_RETRIES + 1, countingRequest.getCount());
}
 
Example #2
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpRetries() throws Exception {
  List<MockLowLevelHttpResponse> mockResponses = ImmutableList.of(
      firstRpcResponse.setStatusCode(503).setContent("{}"),
      new MockLowLevelHttpResponse().setContent("{}"));
  MockHttpTransport transport = new MultiRequestMockHttpTransport(mockResponses);
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId(PROJECT_ID)
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  HttpRequestFactory requestFactory = TestApiClientUtils.delayBypassedRequestFactory(app);
  FirebaseProjectManagementServiceImpl serviceImpl = new FirebaseProjectManagementServiceImpl(
      app, new MockSleeper(), new MockScheduler(), requestFactory);
  serviceImpl.setInterceptor(interceptor);

  serviceImpl.deleteShaCertificate(SHA1_RESOURCE_NAME);

  String expectedUrl = String.format(
      "%s/v1beta1/%s", FIREBASE_PROJECT_MANAGEMENT_URL, SHA1_RESOURCE_NAME);
  checkRequestHeader(expectedUrl, HttpMethod.DELETE);
}
 
Example #3
Source File: TestComponentRegistrar.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public List<Component<?>> getComponents() {
  return Arrays.asList(
      Component.builder(TestComponentOne.class)
          .add(Dependency.required(Context.class))
          .factory(container -> new TestComponentOne(container.get(Context.class)))
          .build(),
      Component.builder(TestComponentTwo.class)
          .add(Dependency.required(FirebaseApp.class))
          .add(Dependency.required(FirebaseOptions.class))
          .add(Dependency.required(TestComponentOne.class))
          .factory(
              container ->
                  new TestComponentTwo(
                      container.get(FirebaseApp.class),
                      container.get(FirebaseOptions.class),
                      container.get(TestComponentOne.class)))
          .build(),
      Component.builder(TestUserAgentDependentComponent.class)
          .add(Dependency.required(UserAgentPublisher.class))
          .factory(
              container ->
                  new TestUserAgentDependentComponent(container.get(UserAgentPublisher.class)))
          .build(),
      LibraryVersionComponent.create(TEST_COMPONENT_NAME, TEST_VERSION));
}
 
Example #4
Source File: FirebaseAuthModule.java    From curiostack with MIT License 6 votes vote down vote up
@Provides
@Singleton
static FirebaseApp firebaseApp(FirebaseAuthConfig config) {
  final FirebaseOptions options;
  try {
    options =
        new FirebaseOptions.Builder()
            .setCredentials(
                GoogleCredentials.fromStream(
                    new ByteArrayInputStream(
                        Base64.getDecoder().decode(config.getServiceAccountBase64()))))
            .setDatabaseUrl("https://" + config.getProjectId() + ".firebaseio.com")
            .build();
  } catch (IOException e) {
    throw new UncheckedIOException("Could not read certificate.", e);
  }
  return FirebaseApp.initializeApp(options);
}
 
Example #5
Source File: FirebaseThreadManagersTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGlobalThreadManagerReInit() {
  MockThreadManager threadManager = new MockThreadManager();
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials())
      .setThreadManager(threadManager)
      .build();
  FirebaseApp defaultApp = FirebaseApp.initializeApp(options);
  assertEquals(1, threadManager.initCount);

  ExecutorService exec1 = threadManager.getExecutor(defaultApp);
  assertEquals(1, threadManager.initCount);
  assertFalse(exec1.isShutdown());

  // Simulate app.delete()
  threadManager.releaseExecutor(defaultApp, exec1);
  assertTrue(exec1.isShutdown());

  // Simulate app re-init
  ExecutorService exec2 = threadManager.getExecutor(defaultApp);
  assertEquals(2, threadManager.initCount);
  assertNotSame(exec1, exec2);

  threadManager.releaseExecutor(defaultApp, exec2);
  assertTrue(exec2.isShutdown());
}
 
Example #6
Source File: FirebaseSaveObject.java    From Examples with MIT License 6 votes vote down vote up
/**
 * initialize firebase.
 */
private void initFirebase() {
    try {
        // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.
        // .setServiceAccount(new FileInputStream(new File("filepath"))) - Firebase private key file path.
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                .setServiceAccount(new FileInputStream(new File("C:\\Users\\Vicky\\Documents\\NetBeansProjects\\Examples\\src\\com\\javaquery\\google\\firebase\\Firebase-30f95674f4d5.json")))
                .build();

        FirebaseApp.initializeApp(firebaseOptions);
        firebaseDatabase = FirebaseDatabase.getInstance();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
}
 
Example #7
Source File: CrashlyticsCoreInitializationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  mockAppContext = newMockContext();
  mockResources = mock(Resources.class);
  testFirebaseOptions = new FirebaseOptions.Builder().setApplicationId(GOOGLE_APP_ID).build();

  fileStore = new FileStoreImpl(getContext());

  cleanSdkDirectory();

  mockSettingsController = mock(SettingsController.class);
  final SettingsData settingsData = new TestSettingsData();
  when(mockSettingsController.getSettings()).thenReturn(settingsData);
  when(mockSettingsController.getAppSettings()).thenReturn(Tasks.forResult(settingsData.appData));
}
 
Example #8
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testProjectIdRequired() {
  FirebaseApp.initializeApp(new FirebaseOptions.Builder()
          .setCredentials(credentials)
          .build());
  FirebaseAuth auth = FirebaseAuth.getInstance();
  try {
    auth.getUserManager();
    fail("No error thrown for missing project ID");
  } catch (IllegalArgumentException expected) {
    assertEquals(
        "Project ID is required to access the auth service. 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.",
        expected.getMessage());
  }
}
 
Example #9
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomToken() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
 
Example #10
Source File: ValidationTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private static void withApp(String name, Consumer<FirebaseApp> toRun) {
  FirebaseApp app =
      FirebaseApp.initializeApp(
          ApplicationProvider.getApplicationContext(),
          new FirebaseOptions.Builder()
              .setApiKey("key")
              .setApplicationId("appId")
              .setProjectId("projectId")
              .build(),
          name);
  try {
    toRun.accept(app);
  } finally {
    app.delete();
  }
}
 
Example #11
Source File: PushClient.java    From hawkular-android-client with Apache License 2.0 6 votes vote down vote up
public void setUpPush() {
    if (!isPushAvailable()) {
        return;
    }

    FirebaseApp.initializeApp(this.context, new FirebaseOptions.Builder()
            .setApiKey(PushConfiguration.Fcm.API_KEY)
            .setApplicationId(PushConfiguration.Fcm.APPLICATION_ID)
            .setDatabaseUrl(PushConfiguration.Fcm.DATABASE_URL)
            .setGcmSenderId(PushConfiguration.Fcm.SENDER)
            .setStorageBucket(PushConfiguration.Fcm.STORAGE_BUCKET).build());

    RegistrarManager.config(PushConfiguration.NAME, AeroGearFCMPushConfiguration.class)
        .setPushServerURI(Uris.getUriFromString(PushConfiguration.Ups.URL))
        .setSecret(PushConfiguration.Ups.SECRET)
        .setVariantID(PushConfiguration.Ups.VARIANT)
        .setSenderId(PushConfiguration.Fcm.SENDER)
        .asRegistrar();

    RegistrarManager.getRegistrar(PushConfiguration.NAME).register(context, this);
}
 
Example #12
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithDeveloperClaims() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync(
      "user1", MapBuilder.of("claim", "value")).get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getDeveloperClaims().keySet().size(), 1);
  assertEquals(parsedToken.getPayload().getDeveloperClaims().get("claim"), "value");
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
 
Example #13
Source File: FirebaseMessagingTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMessagingClientWithoutProjectId() {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .build();
  FirebaseApp.initializeApp(options);
  FirebaseMessaging messaging = FirebaseMessaging.getInstance();

  try {
    messaging.getMessagingClient();
    fail("No error thrown for missing project ID");
  } catch (IllegalArgumentException expected) {
    String message = "Project ID is required to access messaging service. 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.";
    assertEquals(message, expected.getMessage());
  }
}
 
Example #14
Source File: FirebaseStorageSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void initializeAppForStorage() throws IOException {
  // [START init_admin_sdk_for_storage]
  FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(GoogleCredentials.fromStream(serviceAccount))
      .setStorageBucket("<BUCKET_NAME>.appspot.com")
      .build();
  FirebaseApp.initializeApp(options);

  Bucket bucket = StorageClient.getInstance().bucket();

  // 'bucket' is an object defined in the google-cloud-storage Java library.
  // See http://googlecloudplatform.github.io/google-cloud-java/latest/apidocs/com/google/cloud/storage/Bucket.html
  // for more details.
  // [END init_admin_sdk_for_storage]
  System.out.println("Retrieved bucket: " + bucket.getName());
}
 
Example #15
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public FirestoreProtoClient(String project, String token) {
  GoogleCredentials credentials = GoogleCredentials.create(new AccessToken(token, null));
  FirebaseOptions options =
      new FirebaseOptions.Builder().setCredentials(credentials).setProjectId(project).build();
  try {
    FirebaseApp.initializeApp(options);
  } catch (IllegalStateException e) {
    if (e.getMessage().contains("already exists")) {
      // Firestore is probably already initialized - do nothing
    } else {
      throw e;
    }
  }
  client = FirestoreClient.getFirestore();
  storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
}
 
Example #16
Source File: GeoFireTestingRule.java    From geofire-android with Apache License 2.0 6 votes vote down vote up
public void before(Context context) throws Exception {
    if (FirebaseApp.getApps(context).isEmpty()) {
        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                .setApplicationId("1:1010498001935:android:f17a2f247ad8e8bc")
                .setApiKey("AIzaSyBys-YxxE7kON5PxZc5aY6JwVvreyx_owc")
                .setDatabaseUrl(databaseUrl)
                .build();
        FirebaseApp.initializeApp(context, firebaseOptions);
        FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);
    }

    if (FirebaseAuth.getInstance().getCurrentUser() == null) {
        Task<AuthResult> signInTask = TaskUtils.waitForTask(FirebaseAuth.getInstance().signInAnonymously());
        if (signInTask.isSuccessful()) {
            Log.d(TAG, "Signed in as " + signInTask.getResult().getUser());
        } else {
            throw new Exception("Failed to sign in: " + signInTask.getException());
        }
    }

    this.databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(databaseUrl);
}
 
Example #17
Source File: FirebaseRequestInitializerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitTimeouts() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("token"))
      .setConnectTimeout(CONNECT_TIMEOUT_MILLIS)
      .setReadTimeout(READ_TIMEOUT_MILLIS)
      .build());
  HttpRequest request = TestUtils.createRequest();

  FirebaseRequestInitializer initializer = new FirebaseRequestInitializer(app);
  initializer.initialize(request);

  assertEquals(CONNECT_TIMEOUT_MILLIS, request.getConnectTimeout());
  assertEquals(READ_TIMEOUT_MILLIS, request.getReadTimeout());
  assertEquals("Bearer token", request.getHeaders().getAuthorization());
  assertEquals(HttpRequest.DEFAULT_NUMBER_OF_RETRIES, request.getNumberOfRetries());
  assertNull(request.getIOExceptionHandler());
  assertTrue(request.getUnsuccessfulResponseHandler() instanceof HttpCredentialsAdapter);
}
 
Example #18
Source File: FirebaseDatabaseAuthTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDatabaseAuthVariablesAuthorization() throws InterruptedException {
  Map<String, Object> authVariableOverrides = ImmutableMap.<String, Object>of(
      "uid", "test",
      "custom", "secret"
  );
  FirebaseOptions options =
      new FirebaseOptions.Builder(masterApp.getOptions())
          .setDatabaseAuthVariableOverride(authVariableOverrides)
          .build();
  FirebaseApp testUidApp = FirebaseApp.initializeApp(options, "testGetAppWithUid");
  FirebaseDatabase masterDb = FirebaseDatabase.getInstance(masterApp);
  FirebaseDatabase testAuthOverridesDb = FirebaseDatabase.getInstance(testUidApp);

  assertWriteSucceeds(masterDb.getReference());

  // "test" UID can only read/write to /test-uid-only and /test-custom-field-only locations.
  assertWriteFails(testAuthOverridesDb.getReference());
  assertWriteSucceeds(testAuthOverridesDb.getReference("test-uid-only"));
  assertReadSucceeds(testAuthOverridesDb.getReference("test-uid-only"));
  assertWriteSucceeds(testAuthOverridesDb.getReference("test-custom-field-only"));
  assertReadSucceeds(testAuthOverridesDb.getReference("test-custom-field-only"));
}
 
Example #19
Source File: FirebaseDatabaseAuthTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDatabaseAuthVariablesNoAuthorization() throws InterruptedException {
  FirebaseOptions options =
      new FirebaseOptions.Builder(masterApp.getOptions())
          .setDatabaseAuthVariableOverride(null)
          .build();
  FirebaseApp testUidApp =
      FirebaseApp.initializeApp(options, "testServiceAccountDatabaseWithNoAuth");

  FirebaseDatabase masterDb = FirebaseDatabase.getInstance(masterApp);
  FirebaseDatabase testAuthOverridesDb = FirebaseDatabase.getInstance(testUidApp);

  assertWriteSucceeds(masterDb.getReference());

  assertWriteFails(testAuthOverridesDb.getReference("test-uid-only"));
  assertReadFails(testAuthOverridesDb.getReference("test-uid-only"));
  assertWriteFails(testAuthOverridesDb.getReference("test-custom-field-only"));
  assertReadFails(testAuthOverridesDb.getReference("test-custom-field-only"));
  assertWriteSucceeds(testAuthOverridesDb.getReference("test-noauth-only"));    
}
 
Example #20
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 #21
Source File: JvmAuthTokenProviderTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetToken() throws IOException, InterruptedException {
  MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token");
  TokenRefreshDetector refreshDetector = new TokenRefreshDetector();
  credentials.addChangeListener(refreshDetector);
  credentials.refresh();
  assertEquals(1, refreshDetector.count);

  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);

  JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR);
  TestGetTokenListener listener = new TestGetTokenListener();
  provider.getToken(true, listener);
  assertToken(listener.get(), "mock-token", ImmutableMap.<String, Object>of());
  assertEquals(2, refreshDetector.count);
}
 
Example #22
Source File: JvmAuthTokenProviderTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTokenNoRefresh() throws IOException, InterruptedException {
  MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token");
  TokenRefreshDetector refreshDetector = new TokenRefreshDetector();
  credentials.addChangeListener(refreshDetector);
  credentials.refresh();
  assertEquals(1, refreshDetector.count);

  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);

  JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR);
  TestGetTokenListener listener = new TestGetTokenListener();
  provider.getToken(false, listener);
  assertToken(listener.get(), "mock-token", ImmutableMap.<String, Object>of());
  assertEquals(1, refreshDetector.count);
}
 
Example #23
Source File: JvmAuthTokenProviderTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTokenError() throws InterruptedException {
  MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token") {
    @Override
    public AccessToken refreshAccessToken() throws IOException {
      throw new RuntimeException("Test error");
    }
  };
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);

  JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR);
  TestGetTokenListener listener = new TestGetTokenListener();
  provider.getToken(true, listener);
  assertEquals("java.lang.RuntimeException: Test error", listener.get());
}
 
Example #24
Source File: FirebaseEventProxy.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * FirebaseEventProxy.
 */
public FirebaseEventProxy() {
  String firebaseLocation = "https://crackling-torch-392.firebaseio.com";
  Map<String, Object> databaseAuthVariableOverride = new HashMap<String, Object>();
  // uid and provider will have to match what you have in your firebase security rules
  databaseAuthVariableOverride.put("uid", "gae-firebase-event-proxy");
  databaseAuthVariableOverride.put("provider", "com.example");
  try {
    FirebaseOptions options =
        new FirebaseOptions.Builder()
            .setServiceAccount(new FileInputStream("gae-firebase-secrets.json"))
            .setDatabaseUrl(firebaseLocation)
            .setDatabaseAuthVariableOverride(databaseAuthVariableOverride)
            .build();
    FirebaseApp.initializeApp(options);
  } catch (IOException e) {
    throw new RuntimeException(
        "Error reading firebase secrets from file: src/main/webapp/gae-firebase-secrets.json: "
            + e.getMessage());
  }
}
 
Example #25
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private static FirebaseAuth getRetryDisabledAuth(MockLowLevelHttpResponse response) {
  final MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(response)
      .build();
  final FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .setProjectId("test-project-id")
      .setHttpTransport(transport)
      .build());
  return FirebaseAuth.builder()
      .setFirebaseApp(app)
      .setUserManager(new Supplier<FirebaseUserManager>() {
        @Override
        public FirebaseUserManager get() {
          return new FirebaseUserManager(app, transport.createRequestFactory());
        }
      })
      .build();
}
 
Example #26
Source File: JvmPlatformTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void userAgentHasCorrectParts() {
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(TestUtils.getCertCredential(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options, "userAgentApp");

  try {
    Context cfg = new DatabaseConfig();
    cfg.firebaseApp = app;
    cfg.freeze();
    String userAgent = cfg.getUserAgent();
    String[] parts = userAgent.split("/");
    assertEquals(5, parts.length);
    assertEquals("Firebase", parts[0]); // Firebase
    assertEquals(Constants.WIRE_PROTOCOL_VERSION, parts[1]); // Wire protocol version
    assertEquals(FirebaseDatabase.getSdkVersion(), parts[2]); // SDK version
    assertEquals(System.getProperty("java.version", "Unknown"), parts[3]); // Java "OS" version
    assertEquals(Platform.DEVICE, parts[4]); // AdminJava
  } finally {
    TestOnlyImplFirebaseTrampolines.clearInstancesForTest();
  }
}
 
Example #27
Source File: FirebaseMessagingClientImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromApp() throws IOException {
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project")
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);

  try {
    FirebaseMessagingClientImpl client = FirebaseMessagingClientImpl.fromApp(app);

    assertEquals(TEST_FCM_URL, client.getFcmSendUrl());
    assertEquals("fire-admin-java/" + SdkUtils.getVersion(), client.getClientVersion());
    assertSame(options.getJsonFactory(), client.getJsonFactory());

    HttpRequest request = client.getRequestFactory().buildGetRequest(
        new GenericUrl("https://example.com"));
    assertEquals("Bearer test-token", request.getHeaders().getAuthorization());

    request = client.getChildRequestFactory().buildGetRequest(
        new GenericUrl("https://example.com"));
    assertNull(request.getHeaders().getAuthorization());
  } finally {
    app.delete();
  }
}
 
Example #28
Source File: ResourcesConfigStrategy.java    From white-label-event-app with Apache License 2.0 6 votes vote down vote up
private void configureFirebase() throws ConfigException {
    final InputStream is = getClass().getResourceAsStream(SERVICE_JSON_RESOURCE);
    if (is == null) {
        throw new ConfigException("Can't find service account resource " + SERVICE_JSON_RESOURCE);
    }

    final FirebaseOptions options = new FirebaseOptions.Builder()
        .setServiceAccount(is)
        .setDatabaseUrl(databaseUrl)
        .build();

    try {
        is.close();
    }
    catch (IOException e) {
        throw new ConfigException(e);
    }

    FirebaseApp.initializeApp(options);
}
 
Example #29
Source File: CryptoSignersTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataService() throws IOException {
  String signature = BaseEncoding.base64().encode("signed-bytes".getBytes());
  String response = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", signature));
  MockHttpTransport transport = new MultiRequestMockHttpTransport(
      ImmutableList.of(
          new MockLowLevelHttpResponse().setContent("[email protected]"),
          new MockLowLevelHttpResponse().setContent(response)));
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  CryptoSigner signer = CryptoSigners.getCryptoSigner(app);

  assertTrue(signer instanceof CryptoSigners.IAMCryptoSigner);
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  ((CryptoSigners.IAMCryptoSigner) signer).setInterceptor(interceptor);

  byte[] data = signer.sign("foo".getBytes());
  assertArrayEquals("signed-bytes".getBytes(), data);
  final String url = "https://iam.googleapis.com/v1/projects/-/serviceAccounts/"
      + "[email protected]:signBlob";
  assertEquals(url, interceptor.getResponse().getRequest().getUrl().toString());
}
 
Example #30
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteUsersExceeds1000() throws Exception {
  FirebaseApp.initializeApp(new FirebaseOptions.Builder()
          .setCredentials(credentials)
          .build());
  List<String> ids = new ArrayList<>();
  for (int i = 0; i < 1001; i++) {
    ids.add("id" + i);
  }
  try {
    FirebaseAuth.getInstance().deleteUsersAsync(ids);
    fail("No error thrown for too many uids");
  } catch (IllegalArgumentException expected) {
    // expected
  }
}