Firebase Admin Java SDK

repository·main·Indexed 20 days ago

https://github.com/firebase/firebase-admin-java

A Java SDK providing privileged access to Firebase services from server-side or cloud environments. It supports Firebase custom authentication and Realtime Database access, and is compatible with Google App Engine. Supports Java 8 and higher, with Java 11 and 17 recommended.

Tokens
1.4K
Snippets
4
Records
8
Agent score
70%

What's inside Firebase Admin Java SDK

  1. Overview of the Firebase Admin Java SDK

    main

    The Firebase Admin Java SDK allows you to access Firebase services from privileged environments, such as servers or cloud functions, using Java.

    Currently, the SDK provides support for:

    • Firebase custom authentication
    • Firebase Realtime Database access

    It is compatible with Google App Engine.

  2. Install the Firebase Admin Java SDK

    main

    The Firebase Admin Java SDK is distributed via Maven Central. To use it in your project, configure your build tool (like Maven or Gradle) to include the following coordinates:

    • Group ID: com.google.firebase
    • Artifact ID: firebase-admin
    <!-- Maven dependency example -->
    <dependency>
      <groupId>com.google.firebase</groupId>
      <artifactId>firebase-admin</artifactId>
      <version>LATEST_VERSION</version>
    </dependency>
  3. Handle BatchResponse from FCM message operations

    main

    When using FirebaseMessaging#sendAll(List<Message>) or FirebaseMessaging#sendMulticast(MulticastMessage), the SDK returns a BatchResponse. This object contains the individual results for every message sent in the batch.

    You can use BatchResponse to inspect which specific messages succeeded or failed and to get aggregate counts of successes and failures.

    // Example of processing a BatchResponse
    BatchResponse response = messaging.sendAll(messages);
    
    int successes = response.getSuccessCount();
    int failures = response.getFailureCount();
    
    List<SendResponse> individualResponses = response.getResponses();
    for (SendResponse res : individualResponses) {
        if (!res.isSuccessful()) {
            // Handle individual message failure
            System.out.println("Message failed: " + res.getException().getMessage());
        }
    }
  4. Create an Index from a query definition

    main

    Use Index.fromQueryDefinition(String str) to create an index based on a Firebase Realtime Database query definition string.

    Supported strings:

    • ".value": Returns a ValueIndex for indexing by node value.
    • ".key": Returns a KeyIndex for indexing by node key.
    • Any other string: Returns a PathIndex corresponding to the provided path.

    Note: Passing ".priority" will throw an IllegalStateException because priority is the default ordering behavior.

    // Example of creating an index for a specific path
    Index pathIndex = Index.fromQueryDefinition("some/path/to/index");
    
    // Example of creating a value index
    Index valueIndex = Index.fromQueryDefinition(".value");
  5. Use the Index class for sorting and comparing nodes

    main

    The Index class is an abstract base class used to define how nodes in a Realtime Database snapshot are ordered and compared. It implements Comparator<NamedNode>, allowing you to sort nodes based on specific criteria (like value, key, or a specific path).

    Key methods for consumers:

    • compare(NamedNode one, NamedNode two, boolean reverse): Compares two nodes. Use the reverse flag to toggle between ascending and descending order.
    • indexedValueChanged(Node oldNode, Node newNode): Determines if the indexed value has changed between two nodes, which is useful for tracking updates.
    • getQueryDefinition(): Returns the string representation of the query definition this index represents.
  6. BatchResponse methods

    main

    The BatchResponse interface provides the following methods to inspect the results of a bulk FCM operation:

    • getResponses(): Returns a List<SendResponse> containing the result of each individual message in the batch.
    • getSuccessCount(): Returns the total number of messages that were successfully sent.
    • getFailureCount(): Returns the total number of messages that failed to send.
  7. Access identity provider metadata with ProviderUserInfo

    main

    The ProviderUserInfo class provides immutable metadata about how a user is identified by a specific identity provider (IdP). It implements the UserInfo interface and is used to retrieve details such as the user's unique ID, display name, email, phone number, and profile photo URL associated with that specific provider.

    Available methods:

    • getUid(): Returns the unique identifier for the user from the provider.
    • getDisplayName(): Returns the user's display name (can be null).
    • getEmail(): Returns the user's email address (can be null).
    • getPhoneNumber(): Returns the user's phone number (can be null).
    • getPhotoUrl(): Returns the user's profile photo URL (can be null).
    • getProviderId(): Returns the ID of the identity provider (e.g., 'google.com').
    // Note: ProviderUserInfo is package-private and typically accessed 
    // via the Firebase Auth API through the UserInfo interface.
    
    String uid = userInfo.getUid();
    String email = userInfo.getEmail();
    String providerId = userInfo.getProviderId();