Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Firebase setup #183

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open

Conversation

SauravBizbRolly
Copy link

@SauravBizbRolly SauravBizbRolly commented Apr 11, 2025

📋 Description

JIRA ID:

Firebase has been integrated into the common API service. A dedicated notification-sending API has been implemented, enabling all microservices to send push notifications by calling this centralized endpoint.

✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features
    • Integrated the Firebase Admin SDK to enhance server-side Firebase capabilities.
    • Introduced a new API endpoint for sending push notifications.
    • Added functionality to initialize and process Firebase messaging.
    • Implemented a structured notification message model to encapsulate notification details.

Copy link
Contributor

coderabbitai bot commented Apr 11, 2025

Walkthrough

This pull request integrates Firebase Admin functionality into the project. A new dependency for Firebase Admin is added in the build file. The application now includes a configuration class for initializing Firebase Messaging and introduces new classes to support sending notifications via Firebase. A REST controller handles incoming notification requests, which are processed by a dedicated service that constructs and sends messages through the FirebaseMessaging API.

Changes

File(s) Change Summary
pom.xml Added dependency for Firebase Admin (com.google.firebase:firebase-admin:9.4.3).
src/main/java/com/iemr/common/CommonApplication.java Added import statements for Firebase-related classes.
src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java Introduced FirebaseNotificationController as a REST controller with an endpoint (/firebaseNotification/sendNotification) to process notification requests.
src/main/java/com/iemr/common/model/notification/NotificationMessage.java Added NotificationMessage model for encapsulating notification details.
src/main/java/com/iemr/common/service/firebaseNotification/FirebaseNotificationService.java Added FirebaseNotificationService to construct and send notifications via FirebaseMessaging.
src/main/java/com/iemr/common/config/firebase/FirebaseMessagingConfig.java Introduced FirebaseMessagingConfig for configuring Firebase Messaging with credentials.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant Ctrl as FirebaseNotificationController
    participant S as FirebaseNotificationService
    participant FM as FirebaseMessaging

    C->>Ctrl: POST /firebaseNotification/sendNotification\nwith NotificationMessage
    Ctrl->>S: sendNotification(NotificationMessage)
    S->>FM: Build Message and send notification
    FM-->>S: Return response/error
    S-->>Ctrl: Notification result
    Ctrl-->>C: Return response
Loading

Poem

I'm a bouncy rabbit, coding in delight,
Firebase magic is now in sight.
New beans and controllers, whimsical and light,
Notifications hop out with every byte.
Cheers to changes that keep our code tight!
🐇🚀

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (5)
src/main/java/com/iemr/common/model/notification/NotificationMessage.java (1)

13-13: Fix spacing in Map generic type declaration.

There's an extra space between the comma and String in the Map generic type declaration.

-    private Map<String ,String> data;
+    private Map<String, String> data;
src/main/java/com/iemr/common/service/firebaseNotification/FirebaseNotificationService.java (4)

30-30: Simplify return statement

This return statement can be simplified by directly returning the response variable.

     try {
         String response = FirebaseMessaging.getInstance().send(message);

-        return response;
+        return response;
     } catch (FirebaseException e) {

26-26: Remove unnecessary empty line

There's an extra empty line here that can be removed.


8-15: Consider using Lombok to reduce boilerplate

You're manually creating a logger, but consider using Lombok's @Slf4j annotation to reduce this boilerplate code, especially if Lombok is already used elsewhere in the project.

 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import lombok.extern.slf4j.Slf4j;

 @Service
+@Slf4j
 public class FirebaseNotificationService {
-    final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

1-38: Consider returning a structured response object instead of a String

Currently, the method returns a String for both success and error cases, making it difficult for the caller to programmatically determine if the operation succeeded. Consider returning a structured response object instead.

Instead of returning a String, consider creating a NotificationResponse class with fields like success, messageId, and errorMessage. This would make error handling more consistent and provide better information to the caller.

Example response class:

public class NotificationResponse {
    private boolean success;
    private String messageId;
    private String errorMessage;
    
    // Constructors, getters, setters
    
    public static NotificationResponse success(String messageId) {
        NotificationResponse response = new NotificationResponse();
        response.setSuccess(true);
        response.setMessageId(messageId);
        return response;
    }
    
    public static NotificationResponse error(String errorMessage) {
        NotificationResponse response = new NotificationResponse();
        response.setSuccess(false);
        response.setErrorMessage(errorMessage);
        return response;
    }
}

Then modify the service method to return this type:

public NotificationResponse sendNotification(NotificationMessage notificationMessage) {
    // Validation logic
    
    try {
        String response = firebaseMessaging.send(message);
        return NotificationResponse.success(response);
    } catch (FirebaseException e) {
        logger.error("Failed to send Firebase notification", e);
        return NotificationResponse.error(e.getMessage());
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f5a727 and 0e24515.

📒 Files selected for processing (5)
  • pom.xml (1 hunks)
  • src/main/java/com/iemr/common/CommonApplication.java (3 hunks)
  • src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java (1 hunks)
  • src/main/java/com/iemr/common/model/notification/NotificationMessage.java (1 hunks)
  • src/main/java/com/iemr/common/service/firebaseNotification/FirebaseNotificationService.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: style-check / checkstyle
  • GitHub Check: Analyze (java)
🔇 Additional comments (2)
pom.xml (1)

111-115: Firebase Admin dependency looks good.

The Firebase Admin SDK dependency is correctly specified with the latest stable version (9.4.3).

src/main/java/com/iemr/common/controller/firebaseNotification/FirebaseNotificationController.java (1)

10-12: API endpoint structure looks good but consider validating authorization.

The controller is correctly annotated and mapped with an Authorization header requirement, which is a good security practice.

Comment on lines +7 to +14
@Data
public class NotificationMessage {
private String appType;
private String topic;
private String title;
private String body;
private Map<String ,String> data;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Class structure looks good but consider adding token field.

The NotificationMessage class is well-structured with Lombok's @DaTa annotation for automatic generation of boilerplate code. However, I notice that while the class has a topic field, there's no specific field for recipient tokens despite the controller having a method named sendNotificationByToken.

Consider adding a token field to explicitly support token-based messaging:

@Data
public class NotificationMessage {
    private String appType;
    private String topic;
+   private String token;
    private String title;
    private String body;
    private Map<String ,String> data;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Data
public class NotificationMessage {
private String appType;
private String topic;
private String title;
private String body;
private Map<String ,String> data;
}
@Data
public class NotificationMessage {
private String appType;
private String topic;
private String token;
private String title;
private String body;
private Map<String, String> data;
}

Comment on lines 90 to 91
FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
return FirebaseMessaging.getInstance(firebaseApp);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for FirebaseApp initialization.

The current implementation doesn't handle the case where FirebaseApp is already initialized, which can occur during application restart or in testing environments.

Add proper error handling:

- FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
+ FirebaseApp firebaseApp;
+ try {
+     firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
+ } catch (IllegalStateException e) {
+     // App already exists
+     firebaseApp = FirebaseApp.getInstance();
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
return FirebaseMessaging.getInstance(firebaseApp);
FirebaseApp firebaseApp;
try {
firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
} catch (IllegalStateException e) {
// App already exists
firebaseApp = FirebaseApp.getInstance();
}
return FirebaseMessaging.getInstance(firebaseApp);

Comment on lines 83 to 94
@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(
new ClassPathResource("Place your admin json").getInputStream()

);
FirebaseOptions firebaseOptions = FirebaseOptions.builder().setCredentials(googleCredentials).build();
FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
return FirebaseMessaging.getInstance(firebaseApp);


}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Firebase configuration needs a real service account file path.

The current implementation uses a placeholder "Place your admin json" for the service account credentials file. This will cause a runtime error when deployed.

Replace the placeholder with the actual path to your Firebase service account JSON file:

@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
    GoogleCredentials googleCredentials = GoogleCredentials.fromStream(
-           new ClassPathResource("Place your admin json").getInputStream()
+           new ClassPathResource("firebase-service-account.json").getInputStream()
    );
    FirebaseOptions firebaseOptions = FirebaseOptions.builder().setCredentials(googleCredentials).build();
    FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
    return FirebaseMessaging.getInstance(firebaseApp);
}

Also, ensure that the service account JSON file is properly secured and not committed to version control.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(
new ClassPathResource("Place your admin json").getInputStream()
);
FirebaseOptions firebaseOptions = FirebaseOptions.builder().setCredentials(googleCredentials).build();
FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
return FirebaseMessaging.getInstance(firebaseApp);
}
@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(
new ClassPathResource("firebase-service-account.json").getInputStream()
);
FirebaseOptions firebaseOptions = FirebaseOptions.builder().setCredentials(googleCredentials).build();
FirebaseApp firebaseApp = FirebaseApp.initializeApp(firebaseOptions);
return FirebaseMessaging.getInstance(firebaseApp);
}

Comment on lines +18 to +21
@RequestMapping(value = "sendNotification",method = RequestMethod.POST)
public String sendNotificationByToken(@RequestBody NotificationMessage notificationMessage){
return firebaseNotificationService.sendNotification(notificationMessage);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Method name inconsistent with implementation.

The method is named sendNotificationByToken suggesting token-based messaging, but the implementation doesn't show explicit token handling. Also, there's no input validation or error handling.

Consider these improvements:

@RequestMapping(value = "sendNotification",method = RequestMethod.POST)
-public String sendNotificationByToken(@RequestBody NotificationMessage notificationMessage){
-    return firebaseNotificationService.sendNotification(notificationMessage);
+public ResponseEntity<String> sendNotificationByToken(@RequestBody @Valid NotificationMessage notificationMessage){
+    try {
+        String result = firebaseNotificationService.sendNotification(notificationMessage);
+        return ResponseEntity.ok(result);
+    } catch (Exception e) {
+        logger.error("Error sending notification: ", e);
+        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
+                .body("Failed to send notification: " + e.getMessage());
+    }
}

Don't forget to add the required imports:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import javax.validation.Valid;

Comment on lines +12 to +20
public class FirebaseNotificationController {
final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

@Autowired
FirebaseNotificationService firebaseNotificationService;

@RequestMapping(value = "sendNotification",method = RequestMethod.POST)
public String sendNotificationByToken(@RequestBody NotificationMessage notificationMessage){
return firebaseNotificationService.sendNotification(notificationMessage);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Missing service implementation details.

I cannot find the implementation of FirebaseNotificationService that this controller depends on. The service would need to handle the actual Firebase messaging operations.


🌐 Web query:

What are best practices for implementing Firebase Cloud Messaging on the server-side with Java?

💡 Result:

To implement Firebase Cloud Messaging (FCM) effectively on the server-side with Java, follow these best practices:


Token Management

  • Store tokens securely with timestamps using Firestore or your backend database. Track token freshness by updating timestamps regularly (e.g., monthly) to identify stale tokens[4][5].

    // Store token with server timestamp
    Map<String, Object> tokenData = new HashMap<>();
    tokenData.put("token", registrationToken);
    tokenData.put("timestamp", FieldValue.serverTimestamp());
    
    FirebaseFirestore.getInstance()
        .collection("fcmTokens")
        .document(userId)
        .set(tokenData);
  • Refresh tokens periodically using WorkManager to ensure validity[4]:

    // Periodic token refresh (e.g., monthly)
    PeriodicWorkRequest refreshRequest = new PeriodicWorkRequest.Builder(
        UpdateTokenWorker.class, 30, TimeUnit.DAYS
    ).build();
    WorkManager.getInstance(context).enqueue(refreshRequest);
  • Prune stale tokens by checking timestamps. Remove tokens older than a defined threshold (e.g., 30 days)[5]:

    // Delete tokens older than 30 days
    FirebaseFirestore.getInstance()
        .collection("fcmTokens")
        .whereLessThan("timestamp", Timestamp.now().toDate().getTime() - 30 * 86_400_000L)
        .get()
        .addOnSuccessListener(queryDocumentSnapshots -> {
            for (DocumentSnapshot doc : queryDocumentSnapshots) {
                doc.getReference().delete();
            }
        });

Message Handling

  • Use the Firebase Admin SDK for built-in authentication and message validation[1][3]:

    // Send a multicast message
    MulticastMessage message = MulticastMessage.builder()
        .putData("score", "850")
        .addAllTokens(registrationTokens)
        .build();
    
    BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
  • Prefer data messages for app-controlled behavior. Use notification messages only for UI alerts[7]:

    // Data message example
    Message dataMsg = Message.builder()
        .setToken(registrationToken)
        .putData("action", "REFRESH")
        .build();
  • Limit message size to under 4,000 bytes and avoid sending redundant keys like from or message_id[8].


Error Handling and Retries

  • Check for failures in multicast sends and log invalid tokens[1]:

    if (response.getFailureCount() > 0) {
        List<SendResponse> responses = response.getResponses();
        List<String> failedTokens = new ArrayList<>();
        for (int i = 0; i < responses.size(); i++) {
            if (!responses.get(i).isSuccessful()) {
                failedTokens.add(registrationTokens.get(i));
            }
        }
        System.out.println("Failed tokens: " + failedTokens);
    }
  • Implement exponential backoff for retries. The Admin SDK handles this automatically, but custom implementations should wait at least 10 seconds between attempts[8].


Scaling and Performance

  • Throttle send rates to avoid spikes. Gradually ramp up from 0 to maximum requests per second (RPS) over 60 seconds[8].
  • Avoid "on-the-hour" traffic to prevent congestion during common scheduling windows[8].
  • Monitor FCM quotas and contact Firebase Support if nearing limits (e.g., 100,000 RPS globally)[8].

Security

  • Protect server credentials (e.g., serviceAccountKey.json) using environment variables or secret management tools[3].
  • Validate client tokens before sending messages to prevent abuse[5].

By following these practices, you ensure efficient, reliable, and scalable FCM integration in Java server environments[1][3][5][8].

Citations:


Action Required: Implement FirebaseNotificationService

The controller currently delegates to FirebaseNotificationService without any visible implementation details. Based on best practices for Firebase Cloud Messaging with Java, please ensure that the service:

  • Implements FCM Messaging: Leverage the Firebase Admin SDK to build and send messages (e.g., using multicast or data messages) and properly handle messaging errors.
  • Manages Tokens Effectively: Include secure token storage with timestamps, implement periodic token refresh, and prune stale tokens.
  • Handles Errors and Scaling: Implement error logging, retries with exponential backoff, and throttle messaging requests as needed.
  • Secures Sensitive Information: Ensure server credentials (like serviceAccountKey.json) are protected via environment variables or secret management tools.

Addressing these points will strengthen the reliability and security of FCM operations.

Comment on lines +17 to +18
@Autowired
FirebaseMessaging firebaseMessaging;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent FirebaseMessaging instance usage

The service autowires a FirebaseMessaging instance on line 18, but doesn't use it in the sendNotification method. Instead, it retrieves a new instance with FirebaseMessaging.getInstance() on line 28. This is inconsistent and could lead to problems if the autowired instance has specific configurations that aren't present in the statically retrieved instance.

 public String sendNotification(NotificationMessage notificationMessage) {

     Notification notification = Notification.builder().setTitle(notificationMessage.getTitle()).setBody(notificationMessage.getBody()).build();

     Message message = Message.builder().setTopic(notificationMessage.getTopic()).setNotification(notification).putAllData(notificationMessage.getData()).build();


     try {
-        String response = FirebaseMessaging.getInstance().send(message);
+        String response = firebaseMessaging.send(message);

         return response;

Also applies to: 28-28

Comment on lines +31 to +33
} catch (FirebaseException e) {
return "Error sending notification";

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve exception handling

The current exception handling catches FirebaseException but only returns a generic error message without logging the actual exception details. This makes debugging difficult in production environments.

     try {
         String response = FirebaseMessaging.getInstance().send(message);

         return response;
     } catch (FirebaseException e) {
+        logger.error("Failed to send Firebase notification", e);
         return "Error sending notification";

     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (FirebaseException e) {
return "Error sending notification";
try {
String response = FirebaseMessaging.getInstance().send(message);
return response;
} catch (FirebaseException e) {
logger.error("Failed to send Firebase notification", e);
return "Error sending notification";
}

Comment on lines +20 to +35
public String sendNotification(NotificationMessage notificationMessage) {

Notification notification = Notification.builder().setTitle(notificationMessage.getTitle()).setBody(notificationMessage.getBody()).build();

Message message = Message.builder().setTopic(notificationMessage.getTopic()).setNotification(notification).putAllData(notificationMessage.getData()).build();


try {
String response = FirebaseMessaging.getInstance().send(message);

return response;
} catch (FirebaseException e) {
return "Error sending notification";

}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add request validation and more detailed error handling

The method currently doesn't validate the input NotificationMessage or provide detailed error information. Consider adding validation for required fields and more specific error handling for different types of exceptions.

 public String sendNotification(NotificationMessage notificationMessage) {
+    // Validate input
+    if (notificationMessage == null) {
+        return "Error: Notification message cannot be null";
+    }
+    if (notificationMessage.getTopic() == null || notificationMessage.getTopic().isEmpty()) {
+        return "Error: Topic cannot be empty";
+    }

     Notification notification = Notification.builder().setTitle(notificationMessage.getTitle()).setBody(notificationMessage.getBody()).build();

     Message message = Message.builder().setTopic(notificationMessage.getTopic()).setNotification(notification).putAllData(notificationMessage.getData()).build();

     try {
         String response = firebaseMessaging.send(message);
         logger.info("Successfully sent notification to topic: {}", notificationMessage.getTopic());
         return response;
     } catch (FirebaseException e) {
         logger.error("Failed to send Firebase notification", e);
-        return "Error sending notification";
+        return "Error sending notification: " + e.getMessage();
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public String sendNotification(NotificationMessage notificationMessage) {
Notification notification = Notification.builder().setTitle(notificationMessage.getTitle()).setBody(notificationMessage.getBody()).build();
Message message = Message.builder().setTopic(notificationMessage.getTopic()).setNotification(notification).putAllData(notificationMessage.getData()).build();
try {
String response = FirebaseMessaging.getInstance().send(message);
return response;
} catch (FirebaseException e) {
return "Error sending notification";
}
}
public String sendNotification(NotificationMessage notificationMessage) {
// Validate input
if (notificationMessage == null) {
return "Error: Notification message cannot be null";
}
if (notificationMessage.getTopic() == null || notificationMessage.getTopic().isEmpty()) {
return "Error: Topic cannot be empty";
}
Notification notification = Notification.builder()
.setTitle(notificationMessage.getTitle())
.setBody(notificationMessage.getBody())
.build();
Message message = Message.builder()
.setTopic(notificationMessage.getTopic())
.setNotification(notification)
.putAllData(notificationMessage.getData())
.build();
try {
String response = firebaseMessaging.send(message);
logger.info("Successfully sent notification to topic: {}", notificationMessage.getTopic());
return response;
} catch (FirebaseException e) {
logger.error("Failed to send Firebase notification", e);
return "Error sending notification: " + e.getMessage();
}
}

@drtechie
Copy link
Member

Hi @SauravBizbRolly

Few questions.

  1. Can we add the firebase credentials to CI and environment variables?
  2. Is firebase JSON required for all running common API instance? Can we keep it optional?
  3. Who can access /firebaseNotification notification API?
  4. Where are we storing the FCM receiver ID of the users? Are we sending these notifications to specific users?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/main/java/com/iemr/common/config/firebase/FirebaseMessagingConfig.java (4)

19-21: Good use of a toggle for Firebase enablement.

This property-based toggle effectively allows centralized enabling/disabling of Firebase. As an optional improvement, you might consider a no-op approach instead of throwing an exception when firebaseEnabled is false, thereby keeping the application running for non-Firebase use cases.


36-45: Consider fallback or more explicit error handling for credentials.

If the Base64 credential is provided but invalid, you currently throw an IOException. You might add a clearer message or implement a fallback that tries the file-based credentials if the Base64 parsing fails (and vice versa), depending on your deployment strategy.


47-49: Evaluate setting additional Firebase options if needed.

The FirebaseOptions builder supports specifying a project ID, database URL, etc. If you plan to use advanced Firebase features, configuring these now might simplify future integration.


51-55: Use a custom Firebase App name (optional).

Relying on the default app instance is fine, but if there is ever a need to maintain multiple Firebase configurations, specifying a custom app name (e.g., "CommonAPI") ensures no collisions. Also, consider simple debug logging to confirm initialization.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0e24515 and 70a4256.

📒 Files selected for processing (2)
  • src/main/java/com/iemr/common/CommonApplication.java (3 hunks)
  • src/main/java/com/iemr/common/config/firebase/FirebaseMessagingConfig.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/main/java/com/iemr/common/CommonApplication.java
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Package-test
  • GitHub Check: Analyze (java)
  • GitHub Check: Build

@SauravBizbRolly
Copy link
Author

SauravBizbRolly commented Apr 14, 2025

@drtechie
1.Can we add the firebase credentials to CI and environment variables?
Yes. i update code and push again with this change now
You can securely store the Firebase service account JSON in your CI/CD pipeline as an environment variable (preferably base64-encoded).
At runtime, decode the string and use it to initialize Firebase in your Spring Boot app.

2.Is firebase JSON required for all running common API instance? Can we keep it optional?

No, it is not required for all instances.
You can make Firebase optional by:
Using a config flag like firebase.enabled in application.yml
Skipping Firebase initialization and related logic when this flag is false.

3.Who can access /firebaseNotification notification API?

Restrict it using JWT authentication or Spring Security role-based access control.
Allow only admin users or internal services to access i

2.Where are we storing the FCM receiver ID of the users? Are we sending these notifications to specific users?

Since you're using topics, the logic is slightly different:
You don't need to store individual FCM tokens if you're not targeting users directly.
Instead, devices subscribe to topics (e.g., village_123, asha_worker_group).
The mobile app handles the subscription using the Firebase SDK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants