Java Code Examples for com.google.firebase.FirebaseApp#initializeApp()

The following examples show how to use com.google.firebase.FirebaseApp#initializeApp() . 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: 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 3
Source File: StorageClientTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppDelete() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .setStorageBucket("mock-bucket-name")
      .build());

  assertNotNull(StorageClient.getInstance());
  assertNotNull(StorageClient.getInstance(app));
  app.delete();
  try {
    StorageClient.getInstance(app);
    fail("No error thrown for deleted app");
  } catch (IllegalStateException expected) {
    // ignore
  }
}
 
Example 4
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithoutServiceAccountCredentials() throws Exception {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  String content = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", BaseEncoding.base64().encode("test-signature".getBytes())));
  response.setContent(content);
  MockHttpTransport transport = new MultiRequestMockHttpTransport(ImmutableList.of(response));

  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setServiceAccountId("[email protected]")
      .setHttpTransport(transport)
      .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(), "[email protected]");
  assertEquals(parsedToken.getPayload().getIssuer(), "[email protected]");
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertEquals("test-signature", new String(parsedToken.getSignatureBytes()));
}
 
Example 5
Source File: FirebaseDatabaseTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testReference() {
  FirebaseApp.initializeApp(firebaseOptions);
  try {
    FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
    DatabaseReference reference = defaultDatabase.getReference();
    assertNotNull(reference);
    assertNull(reference.getKey());
    assertNull(reference.getParent());

    reference = defaultDatabase.getReference("foo");
    assertNotNull(reference);
    assertEquals("foo", reference.getKey());
    assertNull(reference.getParent().getKey());

    reference = defaultDatabase.getReference("foo/bar");
    assertNotNull(reference);
    assertEquals("bar", reference.getKey());
    assertEquals("foo", reference.getParent().getKey());
  } finally {
    TestOnlyImplFirebaseTrampolines.clearInstancesForTest();
  }
}
 
Example 6
Source File: InstanceIdClientImplTest.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 {
    InstanceIdClientImpl client = InstanceIdClientImpl.fromApp(app);

    assertSame(options.getJsonFactory(), client.getJsonFactory());
    HttpRequest request = client.getRequestFactory().buildGetRequest(
        new GenericUrl("https://example.com"));
    assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
  } finally {
    app.delete();
  }
}
 
Example 7
Source File: FirebaseTokenUtilsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSessionCookieVerifier() {
  FirebaseApp app = FirebaseApp.initializeApp(FirebaseOptions.builder()
      .setCredentials(MOCK_CREDENTIALS)
      .setProjectId(TEST_PROJECT_ID)
      .build());

  FirebaseTokenVerifierImpl cookieVerifier = FirebaseTokenUtils.createSessionCookieVerifier(
      app, CLOCK);

  assertEquals("verifySessionCookie()", cookieVerifier.getMethod());
  assertEquals("session cookie", cookieVerifier.getShortName());
  assertEquals("a session cookie", cookieVerifier.getArticledShortName());
  assertEquals("https://firebase.google.com/docs/auth/admin/manage-cookies",
      cookieVerifier.getDocUrl());
  verifyPublicKeysManager(cookieVerifier.getPublicKeysManager(),
      "https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys");
  verifyJwtVerifier(cookieVerifier.getIdTokenVerifier(),
      "https://session.firebase.google.com/test-project-id");
}
 
Example 8
Source File: StorageRegistrarTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void getComponents_publishesLibVersionComponent() {
  FirebaseApp app =
      FirebaseApp.initializeApp(
          RuntimeEnvironment.application.getApplicationContext(),
          new FirebaseOptions.Builder()
              .setApplicationId("1:196403931065:android:60949756fbe381ea")
              .build());
  UserAgentPublisher userAgentPublisher = app.get(UserAgentPublisher.class);
  String actualUserAgent = userAgentPublisher.getUserAgent();

  assertThat(actualUserAgent).contains("fire-gcs");
}
 
Example 9
Source File: Application.java    From spring-security-firebase with MIT License 5 votes vote down vote up
@Bean
public FirebaseAuth firebaseAuth() throws IOException {
	
	FileInputStream serviceAccount = new FileInputStream(
			"firebase-adminsdk.json");

	FirebaseOptions options = new FirebaseOptions.Builder()
			.setCredentials(GoogleCredentials.fromStream(serviceAccount))
			.setDatabaseUrl("https://mydatabaseurl.firebaseio.com/").build();	

	FirebaseApp.initializeApp(options);
	
	return FirebaseAuth.getInstance();
}
 
Example 10
Source File: IntegrationTestUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public static FirebaseApp initApp(String name) {
  FirebaseOptions options =
      new FirebaseOptions.Builder()
          .setDatabaseUrl(getDatabaseUrl())
          .setCredentials(TestUtils.getCertCredential(getServiceAccountCertificate()))
          .build();
  return FirebaseApp.initializeApp(options, name);
}
 
Example 11
Source File: FirebaseDatabaseSnippets.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public void initializeApp() throws IOException {
  // [START init_admin_sdk_for_db]
  // Fetch the service account key JSON file contents
  FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");

  // Initialize the app with a service account, granting admin privileges
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(GoogleCredentials.fromStream(serviceAccount))
      .setDatabaseUrl("https://<databaseName>.firebaseio.com")
      .build();
  FirebaseApp.initializeApp(options);

  // As an admin, the app has access to read and write all data, regardless of Security Rules
  DatabaseReference ref = FirebaseDatabase.getInstance()
      .getReference("restricted_access/secret_document");
  ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      Object document = dataSnapshot.getValue();
      System.out.println(document);
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });
  // [END init_admin_sdk_for_db]
}
 
Example 12
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String askForNotificationPermission(JSONArray args){
     this.log("askForNotificationPermission", args);
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         String channelName = "Default Name";
         String channelDescription = "Default Description";
         NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
         if (notificationManager != null) {
             NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
             channel.setDescription(channelDescription);
             notificationManager.createNotificationChannel(channel);
         }
    }
    CountlyPush.init(activity.getApplication(), pushTokenTypeVariable);
    FirebaseApp.initializeApp(context);
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w("Tag", "getInstanceId failed", task.getException());
                        return;
                    }
                    String token = task.getResult().getToken();
                    CountlyPush.onTokenRefresh(token);
                }
            });
    return "askForNotificationPermission";
}
 
Example 13
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCustomTokenWithDiscoveredServiceAccount() throws Exception {
  String content = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", BaseEncoding.base64().encode("test-signature".getBytes())));
  List<MockLowLevelHttpResponse> responses = ImmutableList.of(
      // Service account discovery response
      new MockLowLevelHttpResponse().setContent("[email protected]"),

      // Sign blob response
      new MockLowLevelHttpResponse().setContent(content)
  );
  MockHttpTransport transport = new MultiRequestMockHttpTransport(responses);

  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setHttpTransport(transport)
      .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(), "[email protected]");
  assertEquals(parsedToken.getPayload().getIssuer(), "[email protected]");
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertEquals("test-signature", new String(parsedToken.getSignatureBytes()));
}
 
Example 14
Source File: RemixedDungeonApp.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    remixedDungeonApp = this;

    if(checkOwnSignature()) {
        FirebaseApp.initializeApp(this);
        EventCollector.init();
    }

    try {
        HQSdk.enableAttribution(false);
        HQSdk.init(getApplicationContext(), "22b4f34f2616d7f", BuildConfig.DEBUG, new HQCallback<Void>(){

            @Override
            public void onSuccess(Void aVoid) {

            }

            @Override
            public void onError(Throwable throwable) {
                EventCollector.logException(new HqSdkError(throwable));
            }
        });
    } catch (Throwable hqSdkCrash) {
        EventCollector.logException(new HqSdkCrash(hqSdkCrash));
    }


    try {
        ModdingMode.selectMod(RemixedDungeon.activeMod());
        Class.forName("android.os.AsyncTask");
    } catch (Throwable ignore) {
        if(BuildConfig.DEBUG) {
            Log.d("Classes", ignore.getMessage());
        }
    }
}
 
Example 15
Source File: FirebaseMessagingTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private FirebaseMessaging getMessagingForSend(
    Supplier<? extends FirebaseMessagingClient> supplier) {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);
  return FirebaseMessaging.builder()
      .setFirebaseApp(app)
      .setMessagingClient(supplier)
      .setInstanceIdClient(Suppliers.<InstanceIdClient>ofInstance(null))
      .build();
}
 
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: FirestoreArrayTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private FirebaseApp initializeApp(Context context) {
    return FirebaseApp.initializeApp(context, new FirebaseOptions.Builder()
            .setApplicationId("firebaseuitests-app123")
            .setApiKey("AIzaSyCIA_uf-5Y4G83vlZmjMmCM_wkX62iWXf0")
            .setProjectId("firebaseuitests")
            .build(), FIREBASE_APP_NAME);
}
 
Example 18
Source File: FirebaseDatabaseTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInstanceForApp() {
  FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testGetInstanceForApp");
  try {
    FirebaseDatabase db = FirebaseDatabase.getInstance(app);
    assertNotNull(db);
    assertSame(db, FirebaseDatabase.getInstance(app));
  } finally {
    TestOnlyImplFirebaseTrampolines.clearInstancesForTest();
  }
}
 
Example 19
Source File: ShutdownExample.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  final Semaphore shutdownLatch = new Semaphore(0);

  FirebaseApp app =
      FirebaseApp.initializeApp(
          new FirebaseOptions.Builder()
              .setDatabaseUrl("https://admin-java-sdk.firebaseio.com")
              .build());

  FirebaseDatabase db = FirebaseDatabase.getInstance(app);
  DatabaseReference ref = db.getReference();

  ValueEventListener listener =
      ref.child("shutdown")
          .addValueEventListener(
              new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                  Boolean shouldShutdown = snapshot.getValue(Boolean.class);
                  if (shouldShutdown != null && shouldShutdown) {
                    System.out.println("Should shut down");
                    shutdownLatch.release(1);
                  } else {
                    System.out.println("Not shutting down: " + shouldShutdown);
                  }
                }

                @Override
                public void onCancelled(DatabaseError error) {
                  System.err.println("Shouldn't happen");
                }
              });

  try {
    // Keeps us running until we receive the notification to shut down
    shutdownLatch.acquire(1);
    ref.child("shutdown").removeEventListener(listener);
    db.goOffline();
    System.out.println("Done, should exit");
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 
Example 20
Source File: FirebaseInstanceIdTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeleteInstanceIdError() throws Exception {
  Map<Integer, String> errors = ImmutableMap.of(
      404, "Instance ID \"test-iid\": Failed to find the instance ID.",
      429, "Instance ID \"test-iid\": Request throttled out by the backend server.",
      500, "Instance ID \"test-iid\": Internal server error.",
      501, "Error while invoking instance ID service."
  );

  String url = "https://console.firebase.google.com/v1/project/test-project/instanceId/test-iid";
  for (Map.Entry<Integer, String> entry : errors.entrySet()) {
    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
        .setStatusCode(entry.getKey())
        .setContent("test error");
    MockHttpTransport transport = new MockHttpTransport.Builder()
        .setLowLevelHttpResponse(response)
        .build();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(new MockGoogleCredentials("test-token"))
        .setProjectId("test-project")
        .setHttpTransport(transport)
        .build();
    final FirebaseApp app = FirebaseApp.initializeApp(options);

    FirebaseInstanceId instanceId = FirebaseInstanceId.getInstance();
    TestResponseInterceptor interceptor = new TestResponseInterceptor();
    instanceId.setInterceptor(interceptor);
    try {
      instanceId.deleteInstanceIdAsync("test-iid").get();
      fail("No error thrown for HTTP error");
    } catch (ExecutionException e) {
      assertTrue(e.getCause() instanceof FirebaseInstanceIdException);
      assertEquals(entry.getValue(), e.getCause().getMessage());
      assertTrue(e.getCause().getCause() instanceof HttpResponseException);
    }

    assertNotNull(interceptor.getResponse());
    HttpRequest request = interceptor.getResponse().getRequest();
    assertEquals("DELETE", request.getRequestMethod());
    assertEquals(url, request.getUrl().toString());
    assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
    app.delete();
  }
}