Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Firebase Admin Java SDK
https://github.com/firebase/firebase-admin-java
Admin
Firebase Admin Java SDK enables access to Firebase services from privileged environments such as
...
Tokens:
9,388
Snippets:
41
Trust Score:
8.2
Update:
1 week ago
Context
Skills
Chat
Benchmark
91
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Firebase Admin Java SDK The Firebase Admin Java SDK enables server-side access to Firebase services from privileged environments such as servers, cloud functions, or backend services. This official SDK from Google provides comprehensive APIs for Firebase Authentication (user management, custom tokens, ID token verification), Firebase Realtime Database (data reading and writing), Cloud Firestore, Cloud Messaging (FCM), and Cloud Storage. Built for Java 8+ environments including Google App Engine and Google Cloud Platform, it handles authentication via service account credentials and integrates seamlessly with other Google Cloud services. The SDK follows a modular architecture where each Firebase service is accessible through dedicated client classes, all initialized from a central `FirebaseApp` instance. The library supports both synchronous and asynchronous operations using Google's `ApiFuture` pattern, making it suitable for high-performance server applications that need to handle multiple concurrent Firebase operations efficiently. --- ## Initializing Firebase Initialize the Firebase Admin SDK with credentials and configuration options. This must be done before using any other Firebase services. ```java import com.google.auth.oauth2.GoogleCredentials; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import java.io.FileInputStream; import java.io.IOException; public class FirebaseInitializer { public static void main(String[] args) throws IOException { // Initialize with service account credentials FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json"); FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setDatabaseUrl("https://your-project-id.firebaseio.com") .setStorageBucket("your-project-id.appspot.com") .setProjectId("your-project-id") .build(); FirebaseApp.initializeApp(options); System.out.println("Firebase initialized successfully"); // Initialize from environment (uses FIREBASE_CONFIG env var or Application Default Credentials) // FirebaseApp.initializeApp(); // Initialize multiple apps with different names FirebaseOptions secondaryOptions = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(new FileInputStream("path/to/other-key.json"))) .setProjectId("other-project-id") .build(); FirebaseApp.initializeApp(secondaryOptions, "secondary"); // Get app instances FirebaseApp defaultApp = FirebaseApp.getInstance(); FirebaseApp secondaryApp = FirebaseApp.getInstance("secondary"); System.out.println("Default app name: " + defaultApp.getName()); System.out.println("Secondary app name: " + secondaryApp.getName()); } } ``` --- ## Firebase Authentication - Creating Custom Tokens Create custom authentication tokens for client-side authentication. These tokens can be used with Firebase client SDKs to authenticate users. ```java import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import java.util.HashMap; import java.util.Map; public class CustomTokenExample { public static void main(String[] args) { try { // Create a custom token for a user String uid = "user123"; String customToken = FirebaseAuth.getInstance().createCustomToken(uid); System.out.println("Custom token: " + customToken); // Create a custom token with additional claims Map<String, Object> additionalClaims = new HashMap<>(); additionalClaims.put("premiumAccount", true); additionalClaims.put("role", "admin"); additionalClaims.put("accessLevel", 5); String tokenWithClaims = FirebaseAuth.getInstance() .createCustomToken(uid, additionalClaims); System.out.println("Token with claims: " + tokenWithClaims); // Async version FirebaseAuth.getInstance().createCustomTokenAsync(uid) .addListener(() -> System.out.println("Token created asynchronously"), Runnable::run); } catch (FirebaseAuthException e) { System.err.println("Error creating custom token: " + e.getMessage()); } } } ``` --- ## Firebase Authentication - Verifying ID Tokens Verify Firebase ID tokens sent from client applications to ensure they are valid and not tampered with. ```java import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseToken; public class VerifyTokenExample { public static void main(String[] args) { String idToken = "eyJhbGciOiJSUzI1NiIs..."; // Token from client try { // Basic token verification FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken); String uid = decodedToken.getUid(); String email = decodedToken.getEmail(); String name = decodedToken.getName(); boolean emailVerified = decodedToken.isEmailVerified(); System.out.println("User ID: " + uid); System.out.println("Email: " + email); System.out.println("Name: " + name); System.out.println("Email verified: " + emailVerified); // Access custom claims Map<String, Object> claims = decodedToken.getClaims(); System.out.println("Claims: " + claims); // Verify with revocation check (makes additional API call) FirebaseToken verifiedToken = FirebaseAuth.getInstance() .verifyIdToken(idToken, true); System.out.println("Token verified with revocation check for: " + verifiedToken.getUid()); // Async verification FirebaseAuth.getInstance().verifyIdTokenAsync(idToken) .addListener(() -> System.out.println("Token verified asynchronously"), Runnable::run); } catch (FirebaseAuthException e) { System.err.println("Token verification failed: " + e.getMessage()); System.err.println("Error code: " + e.getAuthErrorCode()); } } } ``` --- ## Firebase Authentication - Managing Users Create, retrieve, update, and delete user accounts in Firebase Authentication. ```java import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.UserRecord; import com.google.firebase.auth.UserRecord.CreateRequest; import com.google.firebase.auth.UserRecord.UpdateRequest; import java.util.HashMap; import java.util.Map; public class UserManagementExample { public static void main(String[] args) { try { // Create a new user CreateRequest createRequest = new CreateRequest() .setUid("custom-uid-123") .setEmail("user@example.com") .setPassword("secretPassword123") .setDisplayName("John Doe") .setPhotoUrl("https://example.com/photo.jpg") .setEmailVerified(false) .setPhoneNumber("+15555555555") .setDisabled(false); UserRecord newUser = FirebaseAuth.getInstance().createUser(createRequest); System.out.println("Created user: " + newUser.getUid()); System.out.println("Email: " + newUser.getEmail()); // Get user by UID UserRecord userByUid = FirebaseAuth.getInstance().getUser("custom-uid-123"); System.out.println("User by UID: " + userByUid.getDisplayName()); // Get user by email UserRecord userByEmail = FirebaseAuth.getInstance().getUserByEmail("user@example.com"); System.out.println("User by email: " + userByEmail.getUid()); // Get user by phone number UserRecord userByPhone = FirebaseAuth.getInstance().getUserByPhoneNumber("+15555555555"); System.out.println("User by phone: " + userByPhone.getUid()); // Update user UpdateRequest updateRequest = new UpdateRequest("custom-uid-123") .setDisplayName("Jane Doe") .setPhotoUrl("https://example.com/new-photo.jpg") .setEmailVerified(true) .setDisabled(false); UserRecord updatedUser = FirebaseAuth.getInstance().updateUser(updateRequest); System.out.println("Updated user: " + updatedUser.getDisplayName()); // Set custom claims on user Map<String, Object> customClaims = new HashMap<>(); customClaims.put("admin", true); customClaims.put("accessLevel", 10); FirebaseAuth.getInstance().setCustomUserClaims("custom-uid-123", customClaims); System.out.println("Custom claims set"); // Delete user FirebaseAuth.getInstance().deleteUser("custom-uid-123"); System.out.println("User deleted"); } catch (FirebaseAuthException e) { System.err.println("Auth error: " + e.getMessage()); } } } ``` --- ## Firebase Authentication - Listing Users List all users in Firebase Authentication with pagination support. ```java import com.google.firebase.auth.ExportedUserRecord; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.ListUsersPage; public class ListUsersExample { public static void main(String[] args) { try { // List users with default page size (1000) ListUsersPage page = FirebaseAuth.getInstance().listUsers(null); // Iterate through all users for (ExportedUserRecord user : page.iterateAll()) { System.out.println("User: " + user.getUid() + ", Email: " + user.getEmail()); } // List users with custom page size ListUsersPage smallPage = FirebaseAuth.getInstance().listUsers(null, 100); System.out.println("First page users:"); for (ExportedUserRecord user : smallPage.getValues()) { System.out.println(" - " + user.getEmail()); } // Get next page if available if (smallPage.hasNextPage()) { String nextPageToken = smallPage.getNextPageToken(); ListUsersPage nextPage = FirebaseAuth.getInstance().listUsers(nextPageToken, 100); System.out.println("Next page users:"); for (ExportedUserRecord user : nextPage.getValues()) { System.out.println(" - " + user.getEmail()); } } } catch (FirebaseAuthException e) { System.err.println("Error listing users: " + e.getMessage()); } } } ``` --- ## Firebase Authentication - Session Cookies Create and verify session cookies for server-side session management. ```java import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseToken; import com.google.firebase.auth.SessionCookieOptions; import java.util.concurrent.TimeUnit; public class SessionCookieExample { public static void main(String[] args) { String idToken = "eyJhbGciOiJSUzI1NiIs..."; // ID token from client try { // Create session cookie (valid for 5 days) long expiresIn = TimeUnit.DAYS.toMillis(5); SessionCookieOptions options = SessionCookieOptions.builder() .setExpiresIn(expiresIn) .build(); String sessionCookie = FirebaseAuth.getInstance() .createSessionCookie(idToken, options); System.out.println("Session cookie created: " + sessionCookie.substring(0, 50) + "..."); // Verify session cookie FirebaseToken decodedCookie = FirebaseAuth.getInstance() .verifySessionCookie(sessionCookie); System.out.println("Cookie verified for user: " + decodedCookie.getUid()); // Verify with revocation check FirebaseToken verifiedCookie = FirebaseAuth.getInstance() .verifySessionCookie(sessionCookie, true); System.out.println("Cookie verified (with revocation check): " + verifiedCookie.getUid()); // Revoke user's refresh tokens (invalidates session cookies) String uid = decodedCookie.getUid(); FirebaseAuth.getInstance().revokeRefreshTokens(uid); System.out.println("Refresh tokens revoked for: " + uid); } catch (FirebaseAuthException e) { System.err.println("Session cookie error: " + e.getMessage()); } } } ``` --- ## Firebase Authentication - Email Action Links Generate email action links for password reset, email verification, and sign-in. ```java import com.google.firebase.auth.ActionCodeSettings; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; public class EmailActionLinksExample { public static void main(String[] args) { try { String email = "user@example.com"; // Generate password reset link String resetLink = FirebaseAuth.getInstance().generatePasswordResetLink(email); System.out.println("Password reset link: " + resetLink); // Generate email verification link String verifyLink = FirebaseAuth.getInstance().generateEmailVerificationLink(email); System.out.println("Email verification link: " + verifyLink); // Generate links with custom action code settings ActionCodeSettings actionCodeSettings = ActionCodeSettings.builder() .setUrl("https://www.example.com/finishSignIn") .setHandleCodeInApp(true) .setIosBundleId("com.example.ios") .setAndroidPackageName("com.example.android") .setAndroidMinimumVersion("12") .setAndroidInstallApp(true) .setDynamicLinkDomain("example.page.link") .build(); String customResetLink = FirebaseAuth.getInstance() .generatePasswordResetLink(email, actionCodeSettings); System.out.println("Custom password reset link: " + customResetLink); String customVerifyLink = FirebaseAuth.getInstance() .generateEmailVerificationLink(email, actionCodeSettings); System.out.println("Custom verification link: " + customVerifyLink); // Generate sign-in with email link (passwordless) String signInLink = FirebaseAuth.getInstance() .generateSignInWithEmailLink(email, actionCodeSettings); System.out.println("Sign-in link: " + signInLink); } catch (FirebaseAuthException e) { System.err.println("Email action link error: " + e.getMessage()); } } } ``` --- ## Firebase Cloud Messaging - Sending Messages Send push notifications and data messages to devices, topics, or conditions using Firebase Cloud Messaging. ```java import com.google.firebase.messaging.*; public class MessagingExample { public static void main(String[] args) { try { // Send to a single device Message deviceMessage = Message.builder() .setNotification(Notification.builder() .setTitle("Hello from Firebase") .setBody("This is a notification message") .setImage("https://example.com/image.png") .build()) .putData("key1", "value1") .putData("key2", "value2") .setToken("device-fcm-token") .build(); String response = FirebaseMessaging.getInstance().send(deviceMessage); System.out.println("Message sent: " + response); // Send to a topic Message topicMessage = Message.builder() .setNotification(Notification.builder() .setTitle("Breaking News") .setBody("Something important happened!") .build()) .setTopic("news") .build(); String topicResponse = FirebaseMessaging.getInstance().send(topicMessage); System.out.println("Topic message sent: " + topicResponse); // Send with condition (combining topics) Message conditionMessage = Message.builder() .setNotification(Notification.builder() .setTitle("Special Offer") .setBody("Premium users in US get 50% off!") .build()) .setCondition("'premium' in topics && 'us' in topics") .build(); String conditionResponse = FirebaseMessaging.getInstance().send(conditionMessage); System.out.println("Condition message sent: " + conditionResponse); // Dry run (validation only, message not actually sent) String dryRunResponse = FirebaseMessaging.getInstance().send(deviceMessage, true); System.out.println("Dry run successful: " + dryRunResponse); } catch (FirebaseMessagingException e) { System.err.println("Messaging error: " + e.getMessage()); System.err.println("Error code: " + e.getMessagingErrorCode()); } } } ``` --- ## Firebase Cloud Messaging - Platform-Specific Configuration Configure platform-specific message options for Android, iOS (APNs), and Web. ```java import com.google.firebase.messaging.*; import java.util.Arrays; public class PlatformMessagingExample { public static void main(String[] args) { try { // Message with platform-specific configurations Message message = Message.builder() .setNotification(Notification.builder() .setTitle("Platform Test") .setBody("This message has platform-specific settings") .build()) // Android configuration .setAndroidConfig(AndroidConfig.builder() .setTtl(3600 * 1000L) // 1 hour TTL .setPriority(AndroidConfig.Priority.HIGH) .setRestrictedPackageName("com.example.android") .setNotification(AndroidNotification.builder() .setIcon("ic_notification") .setColor("#FF5733") .setSound("default") .setChannelId("high_priority") .setClickAction("OPEN_ACTIVITY_1") .build()) .build()) // iOS (APNs) configuration .setApnsConfig(ApnsConfig.builder() .setAps(Aps.builder() .setAlert(ApsAlert.builder() .setTitle("iOS Title") .setBody("iOS specific body") .build()) .setBadge(42) .setSound("default") .setCategory("MESSAGE_CATEGORY") .setThreadId("thread-id") .setMutableContent(true) .build()) .putHeader("apns-priority", "10") .putHeader("apns-push-type", "alert") .build()) // Web push configuration .setWebpushConfig(WebpushConfig.builder() .setNotification(WebpushNotification.builder() .setTitle("Web Title") .setBody("Web notification body") .setIcon("https://example.com/icon.png") .setBadge("https://example.com/badge.png") .setDirection(WebpushNotification.Direction.AUTO) .addAction(new WebpushNotification.Action("action1", "Open App")) .build()) .putHeader("Urgency", "high") .putHeader("TTL", "86400") .build()) .setToken("device-fcm-token") .build(); String response = FirebaseMessaging.getInstance().send(message); System.out.println("Platform message sent: " + response); } catch (FirebaseMessagingException e) { System.err.println("Platform messaging error: " + e.getMessage()); } } } ``` --- ## Firebase Cloud Messaging - Batch and Multicast Send messages to multiple devices efficiently using batch and multicast operations. ```java import com.google.firebase.messaging.*; import java.util.Arrays; import java.util.List; public class BatchMessagingExample { public static void main(String[] args) { try { // Send multiple different messages in batch List<Message> messages = Arrays.asList( Message.builder() .setNotification(Notification.builder() .setTitle("Message 1") .setBody("First message") .build()) .setToken("token1") .build(), Message.builder() .setNotification(Notification.builder() .setTitle("Message 2") .setBody("Second message") .build()) .setToken("token2") .build(), Message.builder() .setNotification(Notification.builder() .setTitle("Message 3") .setBody("Third message") .build()) .setTopic("announcements") .build() ); BatchResponse batchResponse = FirebaseMessaging.getInstance().sendEach(messages); System.out.println("Batch sent - Success: " + batchResponse.getSuccessCount() + ", Failures: " + batchResponse.getFailureCount()); // Check individual responses List<SendResponse> responses = batchResponse.getResponses(); for (int i = 0; i < responses.size(); i++) { SendResponse sendResponse = responses.get(i); if (sendResponse.isSuccessful()) { System.out.println("Message " + i + " sent: " + sendResponse.getMessageId()); } else { System.out.println("Message " + i + " failed: " + sendResponse.getException().getMessage()); } } // Multicast: same message to multiple devices List<String> registrationTokens = Arrays.asList("token1", "token2", "token3", "token4"); MulticastMessage multicastMessage = MulticastMessage.builder() .setNotification(Notification.builder() .setTitle("Multicast Message") .setBody("This goes to multiple devices") .build()) .putData("score", "850") .putData("time", "2:45") .addAllTokens(registrationTokens) .build(); BatchResponse multicastResponse = FirebaseMessaging.getInstance() .sendEachForMulticast(multicastMessage); System.out.println("Multicast sent - Success: " + multicastResponse.getSuccessCount()); } catch (FirebaseMessagingException e) { System.err.println("Batch messaging error: " + e.getMessage()); } } } ``` --- ## Firebase Cloud Messaging - Topic Management Subscribe and unsubscribe devices from messaging topics. ```java import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.messaging.FirebaseMessagingException; import com.google.firebase.messaging.TopicManagementResponse; import java.util.Arrays; import java.util.List; public class TopicManagementExample { public static void main(String[] args) { List<String> registrationTokens = Arrays.asList( "device-token-1", "device-token-2", "device-token-3" ); try { // Subscribe devices to a topic TopicManagementResponse subscribeResponse = FirebaseMessaging.getInstance() .subscribeToTopic(registrationTokens, "weather"); System.out.println("Subscribe - Success: " + subscribeResponse.getSuccessCount()); System.out.println("Subscribe - Failures: " + subscribeResponse.getFailureCount()); if (subscribeResponse.getFailureCount() > 0) { subscribeResponse.getErrors().forEach(error -> { System.out.println("Error at index " + error.getIndex() + ": " + error.getReason()); }); } // Unsubscribe devices from a topic TopicManagementResponse unsubscribeResponse = FirebaseMessaging.getInstance() .unsubscribeFromTopic(registrationTokens, "old-topic"); System.out.println("Unsubscribe - Success: " + unsubscribeResponse.getSuccessCount()); System.out.println("Unsubscribe - Failures: " + unsubscribeResponse.getFailureCount()); } catch (FirebaseMessagingException e) { System.err.println("Topic management error: " + e.getMessage()); } } } ``` --- ## Firebase Realtime Database Read and write data to Firebase Realtime Database with real-time synchronization and offline support. ```java import com.google.firebase.database.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; public class RealtimeDatabaseExample { public static void main(String[] args) throws InterruptedException { // Get database reference FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference("users"); // Write data Map<String, Object> userData = new HashMap<>(); userData.put("name", "John Doe"); userData.put("email", "john@example.com"); userData.put("age", 30); CountDownLatch latch = new CountDownLatch(1); ref.child("user123").setValue(userData, (error, reference) -> { if (error != null) { System.err.println("Write failed: " + error.getMessage()); } else { System.out.println("Data written successfully to: " + reference.getPath()); } latch.countDown(); }); latch.await(); // Read data once CountDownLatch readLatch = new CountDownLatch(1); ref.child("user123").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println("User data: " + snapshot.getValue()); System.out.println("Name: " + snapshot.child("name").getValue()); readLatch.countDown(); } @Override public void onCancelled(DatabaseError error) { System.err.println("Read cancelled: " + error.getMessage()); readLatch.countDown(); } }); readLatch.await(); // Listen for real-time updates ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println("Data changed: " + snapshot.getValue()); } @Override public void onCancelled(DatabaseError error) { System.err.println("Listener cancelled: " + error.getMessage()); } }); // Update specific fields Map<String, Object> updates = new HashMap<>(); updates.put("age", 31); updates.put("lastLogin", ServerValue.TIMESTAMP); ref.child("user123").updateChildren(updates); // Push new data with auto-generated key DatabaseReference newPostRef = ref.push(); Map<String, Object> newUser = new HashMap<>(); newUser.put("name", "Jane Smith"); newUser.put("email", "jane@example.com"); newPostRef.setValue(newUser); System.out.println("New user key: " + newPostRef.getKey()); // Query data ref.orderByChild("age").startAt(25).endAt(35) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (DataSnapshot child : snapshot.getChildren()) { System.out.println("Query result: " + child.getValue()); } } @Override public void onCancelled(DatabaseError error) { System.err.println("Query cancelled: " + error.getMessage()); } }); // Delete data // ref.child("user123").removeValue(); // Control connection // database.goOffline(); // database.goOnline(); } } ``` --- ## Cloud Firestore Access Google Cloud Firestore for flexible, scalable NoSQL document database operations. ```java import com.google.api.core.ApiFuture; import com.google.cloud.firestore.*; import com.google.firebase.cloud.FirestoreClient; import java.util.*; import java.util.concurrent.ExecutionException; public class FirestoreExample { public static void main(String[] args) throws ExecutionException, InterruptedException { // Get Firestore instance Firestore db = FirestoreClient.getFirestore(); // Create/update a document Map<String, Object> userData = new HashMap<>(); userData.put("name", "John Doe"); userData.put("email", "john@example.com"); userData.put("age", 30); userData.put("created", FieldValue.serverTimestamp()); userData.put("tags", Arrays.asList("developer", "admin")); ApiFuture<WriteResult> writeResult = db.collection("users") .document("user123") .set(userData); System.out.println("Document written at: " + writeResult.get().getUpdateTime()); // Add document with auto-generated ID ApiFuture<DocumentReference> addResult = db.collection("users") .add(userData); System.out.println("Document added with ID: " + addResult.get().getId()); // Read a document DocumentReference docRef = db.collection("users").document("user123"); ApiFuture<DocumentSnapshot> future = docRef.get(); DocumentSnapshot document = future.get(); if (document.exists()) { System.out.println("Document data: " + document.getData()); System.out.println("Name: " + document.getString("name")); System.out.println("Age: " + document.getLong("age")); } // Query documents ApiFuture<QuerySnapshot> queryFuture = db.collection("users") .whereGreaterThan("age", 25) .whereLessThan("age", 40) .orderBy("age") .limit(10) .get(); List<QueryDocumentSnapshot> documents = queryFuture.get().getDocuments(); for (QueryDocumentSnapshot doc : documents) { System.out.println("User: " + doc.getId() + " => " + doc.getData()); } // Update specific fields ApiFuture<WriteResult> updateResult = docRef.update( "age", 31, "lastModified", FieldValue.serverTimestamp() ); System.out.println("Document updated at: " + updateResult.get().getUpdateTime()); // Batch writes WriteBatch batch = db.batch(); batch.set(db.collection("users").document("user1"), userData); batch.update(db.collection("users").document("user2"), "age", 25); batch.delete(db.collection("users").document("user3")); ApiFuture<List<WriteResult>> batchResult = batch.commit(); System.out.println("Batch committed with " + batchResult.get().size() + " operations"); // Transaction ApiFuture<String> transaction = db.runTransaction(t -> { DocumentSnapshot snapshot = t.get(docRef).get(); long currentAge = snapshot.getLong("age"); t.update(docRef, "age", currentAge + 1); return "Transaction completed"; }); System.out.println(transaction.get()); // Delete document // ApiFuture<WriteResult> deleteResult = docRef.delete(); } } ``` --- ## Cloud Storage Access Google Cloud Storage buckets and objects for file storage operations. ```java import com.google.cloud.storage.Blob; import com.google.cloud.storage.Bucket; import com.google.firebase.cloud.StorageClient; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class CloudStorageExample { public static void main(String[] args) throws IOException { // Get the default storage bucket Bucket bucket = StorageClient.getInstance().bucket(); System.out.println("Default bucket: " + bucket.getName()); // Get a specific bucket Bucket specificBucket = StorageClient.getInstance().bucket("my-custom-bucket"); System.out.println("Specific bucket: " + specificBucket.getName()); // Upload a file byte[] fileContent = Files.readAllBytes(Paths.get("local-file.txt")); Blob blob = bucket.create("uploads/file.txt", fileContent, "text/plain"); System.out.println("File uploaded: " + blob.getName()); System.out.println("Media link: " + blob.getMediaLink()); // Upload with metadata Blob blobWithMetadata = bucket.create( "uploads/document.pdf", Files.readAllBytes(Paths.get("document.pdf")), "application/pdf" ); // Download a file Blob downloadBlob = bucket.get("uploads/file.txt"); if (downloadBlob != null) { byte[] content = downloadBlob.getContent(); Files.write(Paths.get("downloaded-file.txt"), content); System.out.println("File downloaded: " + downloadBlob.getName()); System.out.println("Size: " + downloadBlob.getSize() + " bytes"); System.out.println("Content type: " + downloadBlob.getContentType()); } // List files in bucket System.out.println("Files in bucket:"); for (Blob file : bucket.list().iterateAll()) { System.out.println(" - " + file.getName() + " (" + file.getSize() + " bytes)"); } // Delete a file // boolean deleted = bucket.get("uploads/file.txt").delete(); // System.out.println("File deleted: " + deleted); } } ``` --- ## Error Handling Handle Firebase exceptions properly with error codes and appropriate recovery strategies. ```java import com.google.firebase.auth.AuthErrorCode; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.messaging.FirebaseMessagingException; import com.google.firebase.messaging.MessagingErrorCode; public class ErrorHandlingExample { public static void main(String[] args) { // Authentication error handling try { FirebaseAuth.getInstance().getUser("nonexistent-uid"); } catch (FirebaseAuthException e) { System.err.println("Auth error message: " + e.getMessage()); System.err.println("Auth error code: " + e.getAuthErrorCode()); if (e.getAuthErrorCode() == AuthErrorCode.USER_NOT_FOUND) { System.out.println("User does not exist, creating new user..."); } else if (e.getAuthErrorCode() == AuthErrorCode.INVALID_ID_TOKEN) { System.out.println("Token is invalid, request re-authentication"); } else if (e.getAuthErrorCode() == AuthErrorCode.EXPIRED_ID_TOKEN) { System.out.println("Token expired, refresh required"); } else if (e.getAuthErrorCode() == AuthErrorCode.REVOKED_ID_TOKEN) { System.out.println("Token was revoked, user must re-authenticate"); } } // Messaging error handling try { FirebaseMessaging.getInstance().send(null); } catch (FirebaseMessagingException e) { System.err.println("Messaging error: " + e.getMessage()); System.err.println("Messaging error code: " + e.getMessagingErrorCode()); if (e.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) { System.out.println("Token is no longer valid, remove from database"); } else if (e.getMessagingErrorCode() == MessagingErrorCode.INVALID_ARGUMENT) { System.out.println("Invalid message format"); } else if (e.getMessagingErrorCode() == MessagingErrorCode.QUOTA_EXCEEDED) { System.out.println("Rate limit exceeded, implement backoff"); } else if (e.getMessagingErrorCode() == MessagingErrorCode.SENDER_ID_MISMATCH) { System.out.println("Token was generated for different sender"); } } catch (NullPointerException e) { System.err.println("Message cannot be null"); } // Generic Firebase error handling try { // Firebase operation } catch (Exception e) { if (e.getCause() != null) { System.err.println("Root cause: " + e.getCause().getMessage()); } e.printStackTrace(); } } } ``` --- The Firebase Admin Java SDK is ideal for building secure backend services that need to interact with Firebase services. Common use cases include custom authentication servers that issue tokens for third-party identity providers, admin dashboards for user management, server-side message dispatching systems, and automated data processing pipelines that read from or write to Firebase databases. The SDK integrates well with Spring Boot, Dropwizard, and other Java web frameworks. When integrating the SDK, consider initializing Firebase once at application startup and reusing the singleton instances throughout your application lifecycle. For high-throughput scenarios, leverage the async APIs with `ApiFuture` to avoid blocking threads. The SDK handles credential refresh automatically, but ensure your service account has appropriate IAM permissions for the Firebase services you're using. For production deployments on Google Cloud Platform, Application Default Credentials can simplify authentication without requiring explicit service account key files.