com.google.firebase.FirebaseApp Java Examples

The following examples show how to use com.google.firebase.FirebaseApp. 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: FirebaseSegmentationRegistrarTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void getFirebaseInstallationsInstance() {
  FirebaseApp defaultApp =
      FirebaseApp.initializeApp(
          ApplicationProvider.getApplicationContext(),
          new FirebaseOptions.Builder().setApplicationId("1:123456789:android:abcdef").build());

  FirebaseApp anotherApp =
      FirebaseApp.initializeApp(
          ApplicationProvider.getApplicationContext(),
          new FirebaseOptions.Builder().setApplicationId("1:987654321:android:abcdef").build(),
          "firebase_app_1");

  FirebaseSegmentation defaultSegmentation = FirebaseSegmentation.getInstance();
  assertNotNull(defaultSegmentation);

  FirebaseSegmentation anotherSegmentation = FirebaseSegmentation.getInstance(anotherApp);
  assertNotNull(anotherSegmentation);
}
 
Example #2
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 #3
Source File: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
static FirebaseTokenVerifierImpl createSessionCookieVerifier(FirebaseApp app, Clock clock) {
  String projectId = ImplFirebaseTrampolines.getProjectId(app);
  checkState(!Strings.isNullOrEmpty(projectId),
      "Must initialize FirebaseApp with a project ID to call verifySessionCookie()");
  IdTokenVerifier idTokenVerifier = newIdTokenVerifier(
      clock, SESSION_COOKIE_ISSUER_PREFIX, projectId);
  GooglePublicKeysManager publicKeysManager = newPublicKeysManager(
      app.getOptions(), clock, SESSION_COOKIE_CERT_URL);
  return FirebaseTokenVerifierImpl.builder()
      .setJsonFactory(app.getOptions().getJsonFactory())
      .setPublicKeysManager(publicKeysManager)
      .setIdTokenVerifier(idTokenVerifier)
      .setShortName("session cookie")
      .setMethod("verifySessionCookie()")
      .setDocUrl("https://firebase.google.com/docs/auth/admin/manage-cookies")
      .build();
}
 
Example #4
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 #5
Source File: FirebaseStorage.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link FirebaseStorage}, initialized with a custom {@link FirebaseApp}
 *
 * @param app The custom {@link FirebaseApp} used for initialization.
 * @return a {@link FirebaseStorage} instance.
 */
@NonNull
public static FirebaseStorage getInstance(@NonNull FirebaseApp app) {
  // noinspection ConstantConditions
  Preconditions.checkArgument(app != null, "Null is not a valid value for the FirebaseApp.");

  String storageBucket = app.getOptions().getStorageBucket();
  if (storageBucket == null) {
    return getInstanceImpl(app, null);
  } else {
    try {
      return getInstanceImpl(
          app, Util.normalize(app, "gs://" + app.getOptions().getStorageBucket()));
    } catch (UnsupportedEncodingException e) {
      Log.e(TAG, "Unable to parse bucket:" + storageBucket, e);
      throw new IllegalArgumentException(STORAGE_URI_PARSE_EXCEPTION);
    }
  }
}
 
Example #6
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 #7
Source File: FirebaseInstallations.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
FirebaseInstallations(
    ExecutorService backgroundExecutor,
    FirebaseApp firebaseApp,
    FirebaseInstallationServiceClient serviceClient,
    PersistedInstallation persistedInstallation,
    Utils utils,
    IidStore iidStore,
    RandomFidGenerator fidGenerator) {
  this.firebaseApp = firebaseApp;
  this.serviceClient = serviceClient;
  this.persistedInstallation = persistedInstallation;
  this.utils = utils;
  this.iidStore = iidStore;
  this.fidGenerator = fidGenerator;
  this.backgroundExecutor = backgroundExecutor;
  this.networkExecutor =
      new ThreadPoolExecutor(
          CORE_POOL_SIZE,
          MAXIMUM_POOL_SIZE,
          KEEP_ALIVE_TIME_IN_SECONDS,
          TimeUnit.SECONDS,
          new LinkedBlockingQueue<>(),
          THREAD_FACTORY);
}
 
Example #8
Source File: AuthUI.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the {@link AuthUI} instance associated the the specified app.
 */
@NonNull
public static AuthUI getInstance(@NonNull FirebaseApp app) {
    String releaseUrl = "https://github.com/firebase/FirebaseUI-Android/releases/tag/6.2.0";
    String devWarning = "Beginning with FirebaseUI 6.2.0 you no longer need to include %s to " +
            "sign in with %s. Go to %s for more information";
    if (ProviderAvailability.IS_TWITTER_AVAILABLE) {
        Log.w(TAG, String.format(devWarning, "the TwitterKit SDK", "Twitter", releaseUrl));
    }
    if (ProviderAvailability.IS_GITHUB_AVAILABLE) {
        Log.w(TAG, String.format(devWarning, "com.firebaseui:firebase-ui-auth-github",
                "GitHub", releaseUrl));
    }

    AuthUI authUi;
    synchronized (INSTANCES) {
        authUi = INSTANCES.get(app);
        if (authUi == null) {
            authUi = new AuthUI(app);
            INSTANCES.put(app, authUi);
        }
    }
    return authUi;
}
 
Example #9
Source File: DataCollectionHelper.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Inject
public DataCollectionHelper(
    FirebaseApp firebaseApp,
    SharedPreferencesUtils sharedPreferencesUtils,
    Subscriber firebaseEventsSubscriber) {
  this.sharedPreferencesUtils = sharedPreferencesUtils;
  isGlobalAutomaticDataCollectionEnabled =
      new AtomicBoolean(firebaseApp.isDataCollectionDefaultEnabled());
  firebaseEventsSubscriber.subscribe(
      DataCollectionDefaultChange.class,
      event -> {
        // We don't need to store this value - on re-initialization, we always get the 'current'
        // state
        // off the firebaseApp
        DataCollectionDefaultChange change = event.getPayload();
        isGlobalAutomaticDataCollectionEnabled.set(change.enabled);
      });
}
 
Example #10
Source File: FirebaseRequestInitializerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryConfig() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("token"))
      .build());
  RetryConfig retryConfig = RetryConfig.builder()
      .setMaxRetries(MAX_RETRIES)
      .build();
  HttpRequest request = TestUtils.createRequest();

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

  assertEquals(0, request.getConnectTimeout());
  assertEquals(0, request.getReadTimeout());
  assertEquals("Bearer token", request.getHeaders().getAuthorization());
  assertEquals(MAX_RETRIES, request.getNumberOfRetries());
  assertNull(request.getIOExceptionHandler());
  assertNotNull(request.getUnsuccessfulResponseHandler());
}
 
Example #11
Source File: AccessHelper.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/** Makes the FirebaseFirestore constructor accessible. */
public static FirebaseFirestore newFirebaseFirestore(
    Context context,
    DatabaseId databaseId,
    String persistenceKey,
    CredentialsProvider credentialsProvider,
    AsyncQueue asyncQueue,
    FirebaseApp firebaseApp,
    FirebaseFirestore.InstanceRegistry instanceRegistry) {
  return new FirebaseFirestore(
      context,
      databaseId,
      persistenceKey,
      credentialsProvider,
      asyncQueue,
      firebaseApp,
      instanceRegistry,
      null,
      null);
}
 
Example #12
Source File: GoogleFirebaseBackend.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
GoogleFirebaseBackend(boolean isEnabled, String name, String credsPath, String db) {
    this.isEnabled = isEnabled;
    if (!isEnabled) {
        return;
    }

    try {
        FirebaseApp fbApp = FirebaseApp.initializeApp(getOpts(credsPath, db), name);
        fbAuth = FirebaseAuth.getInstance(fbApp);
        FirebaseDatabase.getInstance(fbApp);

        log.info("Google Firebase Authentication is ready");
    } catch (IOException e) {
        throw new RuntimeException("Error when initializing Firebase", e);
    }
}
 
Example #13
Source File: SplashScreenActivity.java    From mobikul-standalone-pos with MIT License 6 votes vote down vote up
public void initializeFirebase() {
    if (FirebaseApp.getApps(this).isEmpty()) {
        FirebaseApp.initializeApp(this, FirebaseOptions.fromResource(this));
    }
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
    // [END get_remote_config_instance]

    // Create a Remote Config Setting to enable developer mode, which you can use to increase
    // the number of fetches available per hour during development. See Best Practices in the
    // README for more information.
    // [START enable_dev_mode]
    FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(BuildConfig.DEBUG)
            .build();
    mFirebaseRemoteConfig.setConfigSettings(configSettings);
    // [END enable_dev_mode]

    // Set default Remote Config parameter values. An app uses the in-app default values, and
    // when you need to adjust those defaults, you set an updated value for only the values you
    // want to change in the Firebase console. See Best Practices in the README for more
    // information.
    // [START set_default_values]
    mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
    // [END set_default_values]
}
 
Example #14
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private static TestResponseInterceptor initializeAppForUserManagement(String ...responses) {
  List<MockLowLevelHttpResponse> mocks = new ArrayList<>();
  for (String response : responses) {
    mocks.add(new MockLowLevelHttpResponse().setContent(response));
  }
  MockHttpTransport transport = new MultiRequestMockHttpTransport(mocks);
  FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .setHttpTransport(transport)
      .setProjectId("test-project-id")
      .build());
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseUserManager userManager = auth.getUserManager();
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  userManager.setInterceptor(interceptor);
  return interceptor;
}
 
Example #15
Source File: Global.java    From android_sdk_demo_apps with Apache License 2.0 6 votes vote down vote up
private void initFirebase() {
    if (PROJECT_ID.isEmpty() || API_KEY.isEmpty() || FCM_SENDER_ID.isEmpty()) {
        missingCredentials = true;
        return;
    }

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId(PROJECT_ID)
            .setApiKey(API_KEY)
            .setGcmSenderId(FCM_SENDER_ID)
            .build();

    FirebaseApp.initializeApp(this, options);

    try {
        String token = FirebaseInstanceId.getInstance().getToken();
        if (token != null) {
            Log.d(LOG_TAG, "Obtained FCM token");
            ZopimChat.setPushToken(token);
        }
    } catch (IllegalStateException e) {
        Log.d(LOG_TAG, "Error requesting FCM token");
    }
}
 
Example #16
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 #17
Source File: KakaoLoginApplication.java    From custom-auth-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    self = this;
    FirebaseApp.initializeApp(this);
    KakaoSDK.init(new KakaoAdapter() {
        @Override
        public IApplicationConfig getApplicationConfig() {
            return new IApplicationConfig() {
                @Override
                public Context getApplicationContext() {
                    return self;
                }
            };
        }
    });

}
 
Example #18
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 #19
Source File: GeoFireTestingRule.java    From geofire-java with MIT License 6 votes vote down vote up
@Override
public void starting(Description description) {
    if (FirebaseApp.getApps().isEmpty()) {
        final GoogleCredentials credentials;

        try {
            credentials = GoogleCredentials.fromStream(new FileInputStream(SERVICE_ACCOUNT_CREDENTIALS));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                .setDatabaseUrl(databaseUrl)
                .setCredentials(credentials)
                .build();
        FirebaseApp.initializeApp(firebaseOptions);

        System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "DEBUG");
    }
    this.databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(databaseUrl);
}
 
Example #20
Source File: AuthUI.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private AuthUI(FirebaseApp app) {
    mApp = app;
    mAuth = FirebaseAuth.getInstance(mApp);

    try {
        mAuth.setFirebaseUIVersion(BuildConfig.VERSION_NAME);
    } catch (Exception e) {
        Log.e(TAG, "Couldn't set the FUI version.", e);
    }
    mAuth.useAppLanguage();
}
 
Example #21
Source File: FirebaseDatabase.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a FirebaseDatabase instance for the specified URL.
 *
 * @param url The URL to the Firebase Database instance you want to access.
 * @return A FirebaseDatabase instance.
 */
@NonNull
public static FirebaseDatabase getInstance(@NonNull String url) {
  FirebaseApp instance = FirebaseApp.getInstance();
  if (instance == null) {
    throw new DatabaseException("You must call FirebaseApp.initialize() first.");
  }
  return getInstance(instance, url);
}
 
Example #22
Source File: FirebaseTokenUtilsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSessionCookieVerifierWithoutProjectId() {
  FirebaseApp app = FirebaseApp.initializeApp(FirebaseOptions.builder()
      .setCredentials(MOCK_CREDENTIALS)
      .build());

  thrown.expectMessage("Must initialize FirebaseApp with a project ID to call "
      + "verifySessionCookie()");
  FirebaseTokenUtils.createSessionCookieVerifier(app, CLOCK);
}
 
Example #23
Source File: ResumableUploadQueryRequest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public ResumableUploadQueryRequest(
    @NonNull Uri gsUri, @NonNull FirebaseApp app, @NonNull Uri uploadURL) {
  super(gsUri, app);
  this.uploadURL = uploadURL;

  super.setCustomHeader(PROTOCOL, "resumable");
  super.setCustomHeader(COMMAND, "query");
}
 
Example #24
Source File: UpdateMetadataNetworkRequest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public UpdateMetadataNetworkRequest(
    @NonNull Uri gsUri, @NonNull FirebaseApp app, @Nullable JSONObject metadata) {
  super(gsUri, app);
  this.metadata = metadata;
  // On kitkat and below, patch is not supported.
  this.setCustomHeader("X-HTTP-Method-Override", PATCH);
}
 
Example #25
Source File: ElectricityApplication.java    From android-things-electricity-monitor with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(
            new CalligraphyConfig.Builder().setDefaultFontPath("minyna.ttf").setFontAttrId(R.attr.fontPath)
                    .build());
    AndroidThreeTen.init(this);
    FirebaseApp.initializeApp(this);
    FirebaseMessaging.getInstance().subscribeToTopic("Power_Notifications");
}
 
Example #26
Source File: FirebaseInstanceId.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the {@link FirebaseInstanceId} instance for the specified {@link FirebaseApp}.
 *
 * @return The {@link FirebaseInstanceId} instance for the specified {@link FirebaseApp}.
 */
public static synchronized FirebaseInstanceId getInstance(FirebaseApp app) {
  FirebaseInstanceIdService service = ImplFirebaseTrampolines.getService(app, SERVICE_ID,
      FirebaseInstanceIdService.class);
  if (service == null) {
    service = ImplFirebaseTrampolines.addService(app, new FirebaseInstanceIdService(app));
  }
  return service.getInstance();
}
 
Example #27
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 #28
Source File: FirebaseDatabaseComponent.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
FirebaseDatabaseComponent(@NonNull FirebaseApp app, @Nullable InternalAuthProvider authProvider) {
  this.app = app;

  if (authProvider != null) {
    this.authProvider = AndroidAuthTokenProvider.forAuthenticatedAccess(authProvider);
  } else {
    this.authProvider = AndroidAuthTokenProvider.forUnauthenticatedAccess();
  }
}
 
Example #29
Source File: FirebaseTokenUtils.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
static FirebaseTokenFactory createTokenFactory(FirebaseApp firebaseApp, Clock clock) {
  try {
    return new FirebaseTokenFactory(
        firebaseApp.getOptions().getJsonFactory(),
        clock,
        CryptoSigners.getCryptoSigner(firebaseApp));
  } catch (IOException e) {
    throw new IllegalStateException(
        "Failed to initialize FirebaseTokenFactory. Make sure to initialize the SDK "
            + "with service account credentials or specify a service account "
            + "ID with iam.serviceAccounts.signBlob permission. Please refer to "
            + "https://firebase.google.com/docs/auth/admin/create-custom-tokens for more "
            + "details on creating custom tokens.", e);
  }
}
 
Example #30
Source File: FirebaseRequestInitializer.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
public FirebaseRequestInitializer(FirebaseApp app, @Nullable RetryConfig retryConfig) {
  ImmutableList.Builder<HttpRequestInitializer> initializers =
      ImmutableList.<HttpRequestInitializer>builder()
          .add(new HttpCredentialsAdapter(ImplFirebaseTrampolines.getCredentials(app)))
          .add(new TimeoutInitializer(app.getOptions()));
  if (retryConfig != null) {
    initializers.add(new RetryInitializer(retryConfig));
  }
  this.initializers = initializers.build();
}