Skip to content

Conversation

@ravishanigarapu
Copy link
Contributor

@ravishanigarapu ravishanigarapu commented Aug 5, 2025

📋 Description

JIRA ID: AMM-1187

Skips writing to file. Directly generates and inserts into DB.
Prevents out-of-memory errors or timeouts when handling large volumes.
Improves database throughput and stability.
Makes the load on the DB more manageable.


✅ 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

  • Refactor

    • Improved beneficiary ID generation and insertion by switching to concurrent batch processing for better performance and reliability.
    • Enhanced randomness and logging in ID generation for increased security and clarity.
    • Cleaned up unused variables and improved code readability in user validation logic.
  • Tests

    • Updated and expanded tests to focus on batch data creation and batch database updates, ensuring robust validation of new logic.
    • Removed outdated tests related to raw SQL string generation.

@coderabbitai
Copy link

coderabbitai bot commented Aug 5, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes refactor beneficiary ID generation and insertion in GenerateBeneficiaryService, replacing a single large SQL insert and file write with parallelized ID generation and JDBC batch inserts. The Generator class is updated to use SecureRandom and improved logging. Corresponding tests are reworked to focus on batch data creation and JDBC interactions.

Changes

Cohort / File(s) Change Summary
Beneficiary Service Refactor
src/main/java/com/iemr/common/bengen/service/GenerateBeneficiaryService.java
Replaces SQL string/file-based insertion with parallelized batch data generation and JDBC batch inserts; adds createBatchData method; updates logging and removes old file writing/query logic.
Randomness and Logging Improvements
src/main/java/com/iemr/common/bengen/utils/Generator.java
Refactors to use SecureRandom, improves randomness and logging, introduces new helper methods, and clarifies code structure. No core logic changes to ID generation.
JWT Filter Minor Cleanup
src/main/java/com/iemr/common/bengen/utils/JwtUserIdValidationFilter.java
Removes unused variable, fixes brace in null check, and adjusts whitespace. No control flow or logic changes.
Test Suite Overhaul
src/test/java/com/iemr/common/bengen/service/GenerateBeneficiaryServiceTest.java
Refactors tests to focus on batch data creation and JDBC batch updates, removing SQL string assertions. Updates mocks and assertions to match new service logic, and adds/updates tests for batch data and batch insertions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GenerateBeneficiaryService
    participant Generator
    participant JdbcTemplate

    Client->>GenerateBeneficiaryService: createFile()
    GenerateBeneficiaryService->>Generator: createBatchData(num)
    Generator-->>GenerateBeneficiaryService: List<Object[]> (IDs)
    loop For each batch of 500
        GenerateBeneficiaryService->>JdbcTemplate: batchUpdate(SQL, batch)
        JdbcTemplate-->>GenerateBeneficiaryService: update result
    end
    GenerateBeneficiaryService-->>Client: (done)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

  • PSMRI/BeneficiaryID-Generation-API#17: Refactors GenerateBeneficiaryService to use BeneficiaryIdRepo for fetching IDs, related through changes to ID generation logic in the same service.

Poem

A batch of bunnies, IDs in tow,
Now hop in parallel, swift as they go.
No more one giant SQL leap—
They nibble in batches, not a peep.
Secure and random, their numbers grow,
While tests keep watch on every row.
🐇✨ Batch by batch, the carrots flow!

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

@drtechie
Copy link
Member

drtechie commented Aug 5, 2025

@ravishanigarapu
Please confirm if the test cases are updated as per new methods.
Can you also confirm if the new methods are covered with test cases?

@ravishanigarapu
Copy link
Contributor Author

@ravishanigarapu Please confirm if the test cases are updated as per new methods. Can you also confirm if the new methods are covered with test cases?

image

@drtechie
Copy link
Member

drtechie commented Aug 6, 2025

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Aug 6, 2025

✅ Actions performed

Full review triggered.

Copy link

@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: 5

🔭 Outside diff range comments (2)
src/main/java/com/iemr/common/bengen/service/GenerateBeneficiaryService.java (2)

137-184: Refactor to use batch insert approach and fix SQL injection risk.

This method still uses the old StringBuilder approach and has SQL injection vulnerability. It should be refactored to match the new batch insert pattern used in createFile().

 public List<M_BeneficiaryRegidMapping> getBeneficiaryIDs(Long num, Integer vanID) {
     logger.info("getBeneficiaryIDs start");
     long strt = System.currentTimeMillis();
-    Generator g = new Generator();
-    StringBuffer sb = new StringBuffer(
-            "INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
-                    "(`BeneficiaryID`,`Provisioned`,`Deleted`,`Reserved`," +
-                    "`CreatedDate`,`CreatedBy`,`VanID`) VALUES ");
+    
     Timestamp ts = Timestamp.from(Instant.now());
     List<M_BeneficiaryRegidMapping> list = new ArrayList<M_BeneficiaryRegidMapping>();

-    for (int i = 0; i < num; i++) {
-        sb.append("( ");
-        sb.append(g.generateBeneficiaryId()).append(",").append("b'0'")
-                .append(",").append("b'0'").append(",")
-                .append("b'1'").append(",").append("'")
-                .append(ts).append("',").append("'admin-batch'").append(",")
-                .append(vanID).append("");
-        sb.append(" ), ");
-    }
-
-    sb.deleteCharAt(sb.lastIndexOf(","));
-
-    jdbcTemplate.execute(sb.toString());
+    // Generate batch data
+    List<Object[]> batchData = IntStream.range(0, num.intValue())
+        .mapToObj(i -> {
+            Generator g = new Generator();
+            return new Object[]{
+                g.generateBeneficiaryId(),
+                false, // Provisioned
+                false, // Deleted  
+                true,  // Reserved
+                ts,
+                "admin-batch",
+                vanID
+            };
+        })
+        .collect(Collectors.toList());
+
+    // Batch insert using parameterized query (prevents SQL injection)
+    String sql = "INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
+                 "(`BeneficiaryID`,`Provisioned`,`Deleted`,`Reserved`,`CreatedDate`,`CreatedBy`,`VanID`) " +
+                 "VALUES (?, b'0', b'0', b'1', ?, ?, ?)";
+    
+    for (int i = 0; i < batchData.size(); i += BATCH_SIZE) {
+        List<Object[]> batch = batchData.subList(i, Math.min(i + BATCH_SIZE, batchData.size()));
+        jdbcTemplate.batchUpdate(sql, batch);
+    }

     List<Object[]> result = null;

     logger.info("ts result1 = " + ts);

     result = beneficiaryIdRepo.getBenIDGenerated(vanID, num);

115-135: Remove test/debug methods from production code.

The methods testLoopGenr() and testPMDAvoidGenr() appear to be test or debug code that should not be in production.

These methods should be removed or moved to test classes.

🧹 Nitpick comments (3)
src/main/java/com/iemr/common/bengen/utils/JwtUserIdValidationFilter.java (2)

71-73: Remove or complete the orphan log statement

logger.info("JWT token from header: "); prints an empty message and provides no debugging value after the variable was removed.
Either drop the line or log something meaningful (e.g., header presence) to avoid noise.


149-155: isMobileClient null-check looks good – consider tightening the flow

The added braces fix the previous scoping bug – nice catch.
As a micro-refactor, you could invert the condition and early-return to reduce nesting:

- if (userAgent == null) {
-     return false;
- }
- userAgent = userAgent.toLowerCase();
- return userAgent.contains("okhttp");
+ if (userAgent == null) return false;
+ return userAgent.toLowerCase().contains("okhttp");

Purely optional – current logic is correct.

src/test/java/com/iemr/common/bengen/service/GenerateBeneficiaryServiceTest.java (1)

349-362: Consider making timeout configurable.

The 5-second timeout is hardcoded. Consider making it configurable or environment-specific to avoid flaky tests on slower CI environments.

+private static final Duration TEST_TIMEOUT = Duration.ofSeconds(
+    Integer.parseInt(System.getProperty("test.timeout.seconds", "5"))
+);

 @Test
 @DisplayName("Should complete file creation within reasonable time")
 void createFile_performance_shouldCompleteWithinTimeout() throws IOException {
     // ... setup code ...
     
     // Act & Assert
-    assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
+    assertTimeoutPreemptively(TEST_TIMEOUT, () -> {
         generateBeneficiaryService.createFile();
     });
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c21c3f8 and 921f69f.

📒 Files selected for processing (4)
  • src/main/java/com/iemr/common/bengen/service/GenerateBeneficiaryService.java (3 hunks)
  • src/main/java/com/iemr/common/bengen/utils/Generator.java (2 hunks)
  • src/main/java/com/iemr/common/bengen/utils/JwtUserIdValidationFilter.java (1 hunks)
  • src/test/java/com/iemr/common/bengen/service/GenerateBeneficiaryServiceTest.java (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: the jwt implementation in beneficiaryid-generation-api should be kept simple with only essential cla...
Learnt from: indraniBan
PR: PSMRI/BeneficiaryID-Generation-API#20
File: src/main/java/com/iemr/common/bengen/utils/JwtUtil.java:32-40
Timestamp: 2025-02-10T10:40:00.839Z
Learning: The JWT implementation in BeneficiaryID-Generation-API should be kept simple with only essential claims (subject, userId, issuedAt, expiration). Additional standard claims (jti, iss, aud) are not required.

Applied to files:

  • src/main/java/com/iemr/common/bengen/utils/JwtUserIdValidationFilter.java
🧬 Code Graph Analysis (1)
src/main/java/com/iemr/common/bengen/utils/Generator.java (1)
src/main/java/com/iemr/common/bengen/utils/Verhoeff.java (1)
  • Verhoeff (30-127)
🔇 Additional comments (7)
src/main/java/com/iemr/common/bengen/utils/Generator.java (4)

42-64: LGTM! Well-structured beneficiary ID generation.

The method correctly generates a beneficiary ID with proper checksum calculation and efficient use of constants. The debug logging is appropriately guarded.


66-69: Good implementation with appropriate range constraints.

The method correctly generates the first part of the beneficiary ID with a non-zero, non-one leading digit.


117-122: Good optimization with debug guard.

The method efficiently skips execution when debug logging is disabled.


124-130: Efficient helper method implementation.

Good use of StringBuilder with capacity hint for performance.

src/main/java/com/iemr/common/bengen/service/GenerateBeneficiaryService.java (1)

94-113: No thread-safety issues with Generator—parallel use is safe.

The Generator class holds only static final constants and a logger; all random digits are produced by locally instantiated SecureRandom in each call. There’s no mutable shared state, so calling g.generateBeneficiaryId() in parallel won’t introduce race conditions.

• Generator fields (Logger, TEN, TEN_POW_10) are immutable/static.
• Each getRandomDigit() creates its own SecureRandom.

You can keep the single Generator g = new Generator() outside the stream. If you want to optimize performance, consider using a thread-local or shared SecureRandom per thread, but it isn’t required for correctness in this batch scenario.

src/test/java/com/iemr/common/bengen/service/GenerateBeneficiaryServiceTest.java (2)

89-136: Well-structured test coverage for batch data generation.

The tests properly verify the new batch data creation approach with good coverage of edge cases including zero records.


278-344: Comprehensive batch insert testing.

Good coverage of the batch insert functionality including various record counts and error scenarios.

Comment on lines 51 to +52
private ExecutorService executor = Executors.newCachedThreadPool();

private static final int BATCH_SIZE = 500;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

ExecutorService is never shutdown - potential resource leak.

The ExecutorService at line 51 is created but never shutdown, which can lead to thread leaks.

Add proper lifecycle management:

+import javax.annotation.PreDestroy;

 @Service
 public class GenerateBeneficiaryService {
     private static final Logger logger = LoggerFactory.getLogger(GenerateBeneficiaryService.class);
     private ExecutorService executor = Executors.newCachedThreadPool();
     
+    @PreDestroy
+    public void cleanup() {
+        logger.info("Shutting down executor service");
+        executor.shutdown();
+        try {
+            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
+                executor.shutdownNow();
+            }
+        } catch (InterruptedException e) {
+            executor.shutdownNow();
+            Thread.currentThread().interrupt();
+        }
+    }
📝 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
private ExecutorService executor = Executors.newCachedThreadPool();
private static final int BATCH_SIZE = 500;
// … other imports …
import javax.annotation.PreDestroy;
@Service
public class GenerateBeneficiaryService {
private static final Logger logger = LoggerFactory.getLogger(GenerateBeneficiaryService.class);
private ExecutorService executor = Executors.newCachedThreadPool();
private static final int BATCH_SIZE = 500;
@PreDestroy
public void cleanup() {
logger.info("Shutting down executor service");
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
// … existing methods …
}
🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/bengen/service/GenerateBeneficiaryService.java
around lines 51 to 52, the ExecutorService is instantiated but never shut down,
causing potential thread leaks. Add a method to properly shut down the executor,
such as a shutdown or close method, and ensure it is called when the service is
no longer needed. Use executor.shutdown() followed by awaitTermination to
gracefully stop the threads.

Comment on lines 73 to 92
public void createFile() {
logger.info("BengenApplication.createFile start");
long strt = System.currentTimeMillis();

try {
File file = File.createTempFile("" + System.currentTimeMillis(), ".csv");
logger.info("File: " + file.getAbsolutePath());
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
Integer bentobeGenerate = ConfigProperties.getInteger("no-of-benID-to-be-generate");
bw.write(createQuery(bentobeGenerate).toString());
bw.flush();
bw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createFile finish. time = " + fin + " ms.");
}

public StringBuffer createQuery(Integer num) {
logger.info("BengenApplication.createQuery start");
long strt = System.currentTimeMillis();

Generator g = new Generator();
StringBuffer sb = new StringBuffer(
"INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
"(`BeneficiaryID`,`Provisioned`,`Deleted`," +
"`CreatedDate`,`CreatedBy`) VALUES ");

// INSERT INTO `db_identity`.`m_beneficiaryregidmapping`
// (`BeneficiaryID`,`Provisioned`,`Deleted`,`CreatedDate`,`CreatedBy`) VALUES
// (<{BeneficiaryID: }>, <{Provisioned: b'0'}>, <{Deleted: b'0'}>,
// <{CreatedDate: CURRENT_TIMESTAMP}>, <{CreatedBy: }>);

Timestamp ts = Timestamp.from(Instant.now());
logger.info("BengenApplication.createFile start");
long strt = System.currentTimeMillis();

for (int i = 0; i < num; i++) {
sb.append("( ");
sb.append(g.generateBeneficiaryId())
.append(",")
.append("b'0'")
.append(",")
.append("b'0'")
.append(",")
.append("'")
.append(ts)
.append("',")
.append("'admin-batch'")
.append("");
sb.append(" ), ");
}
Integer count = ConfigProperties.getInteger("no-of-benID-to-be-generate");
List<Object[]> batchArgs = createBatchData(count);

sb.deleteCharAt(sb.lastIndexOf(","));
// Batch insert using JdbcTemplate
String sql = "INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
"(`BeneficiaryID`, `Provisioned`, `Deleted`, `CreatedDate`, `CreatedBy`) " +
"VALUES (?, b'0', b'0', ?, ?)";

jdbcTemplate.execute(sb.toString());
for (int i = 0; i < batchArgs.size(); i += BATCH_SIZE) {
List<Object[]> batch = batchArgs.subList(i, Math.min(i + BATCH_SIZE, batchArgs.size()));
jdbcTemplate.batchUpdate(sql, batch);
}

long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createQuery finish. time = " + fin + " ms.");
long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createFile finish. time = " + fin + " ms.");
}
Copy link

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 and make database name configurable.

The method needs better error handling and the hardcoded database name should be configurable.

 public void createFile() {
     logger.info("BengenApplication.createFile start");
     long strt = System.currentTimeMillis();

     Integer count = ConfigProperties.getInteger("no-of-benID-to-be-generate");
+    if (count == null || count <= 0) {
+        logger.error("Invalid or missing configuration for no-of-benID-to-be-generate");
+        throw new IllegalStateException("Invalid beneficiary ID count configuration");
+    }
+    
     List<Object[]> batchArgs = createBatchData(count);

     // Batch insert using JdbcTemplate
-    String sql = "INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
+    String dbName = ConfigProperties.getString("database.name", "db_identity");
+    String sql = "INSERT INTO `" + dbName + "`.`m_beneficiaryregidmapping` " +
                  "(`BeneficiaryID`, `Provisioned`, `Deleted`, `CreatedDate`, `CreatedBy`) " +
                  "VALUES (?, b'0', b'0', ?, ?)";

     for (int i = 0; i < batchArgs.size(); i += BATCH_SIZE) {
         List<Object[]> batch = batchArgs.subList(i, Math.min(i + BATCH_SIZE, batchArgs.size()));
-        jdbcTemplate.batchUpdate(sql, batch);
+        try {
+            jdbcTemplate.batchUpdate(sql, batch);
+        } catch (Exception e) {
+            logger.error("Failed to insert batch starting at index {}: {}", i, e.getMessage());
+            throw new RuntimeException("Batch insert failed", e);
+        }
     }

     long fin = System.currentTimeMillis() - strt;
     logger.info("BengenApplication.createFile finish. time = " + fin + " ms.");
 }
📝 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 void createFile() {
logger.info("BengenApplication.createFile start");
long strt = System.currentTimeMillis();
try {
File file = File.createTempFile("" + System.currentTimeMillis(), ".csv");
logger.info("File: " + file.getAbsolutePath());
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
Integer bentobeGenerate = ConfigProperties.getInteger("no-of-benID-to-be-generate");
bw.write(createQuery(bentobeGenerate).toString());
bw.flush();
bw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createFile finish. time = " + fin + " ms.");
}
public StringBuffer createQuery(Integer num) {
logger.info("BengenApplication.createQuery start");
long strt = System.currentTimeMillis();
Generator g = new Generator();
StringBuffer sb = new StringBuffer(
"INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
"(`BeneficiaryID`,`Provisioned`,`Deleted`," +
"`CreatedDate`,`CreatedBy`) VALUES ");
// INSERT INTO `db_identity`.`m_beneficiaryregidmapping`
// (`BeneficiaryID`,`Provisioned`,`Deleted`,`CreatedDate`,`CreatedBy`) VALUES
// (<{BeneficiaryID: }>, <{Provisioned: b'0'}>, <{Deleted: b'0'}>,
// <{CreatedDate: CURRENT_TIMESTAMP}>, <{CreatedBy: }>);
Timestamp ts = Timestamp.from(Instant.now());
logger.info("BengenApplication.createFile start");
long strt = System.currentTimeMillis();
for (int i = 0; i < num; i++) {
sb.append("( ");
sb.append(g.generateBeneficiaryId())
.append(",")
.append("b'0'")
.append(",")
.append("b'0'")
.append(",")
.append("'")
.append(ts)
.append("',")
.append("'admin-batch'")
.append("");
sb.append(" ), ");
}
Integer count = ConfigProperties.getInteger("no-of-benID-to-be-generate");
List<Object[]> batchArgs = createBatchData(count);
sb.deleteCharAt(sb.lastIndexOf(","));
// Batch insert using JdbcTemplate
String sql = "INSERT INTO `db_identity`.`m_beneficiaryregidmapping` " +
"(`BeneficiaryID`, `Provisioned`, `Deleted`, `CreatedDate`, `CreatedBy`) " +
"VALUES (?, b'0', b'0', ?, ?)";
jdbcTemplate.execute(sb.toString());
for (int i = 0; i < batchArgs.size(); i += BATCH_SIZE) {
List<Object[]> batch = batchArgs.subList(i, Math.min(i + BATCH_SIZE, batchArgs.size()));
jdbcTemplate.batchUpdate(sql, batch);
}
long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createQuery finish. time = " + fin + " ms.");
long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createFile finish. time = " + fin + " ms.");
}
public void createFile() {
logger.info("BengenApplication.createFile start");
long strt = System.currentTimeMillis();
Integer count = ConfigProperties.getInteger("no-of-benID-to-be-generate");
if (count == null || count <= 0) {
logger.error("Invalid or missing configuration for no-of-benID-to-be-generate");
throw new IllegalStateException("Invalid beneficiary ID count configuration");
}
List<Object[]> batchArgs = createBatchData(count);
// Batch insert using JdbcTemplate
String dbName = ConfigProperties.getString("database.name", "db_identity");
String sql = "INSERT INTO `" + dbName + "`.`m_beneficiaryregidmapping` " +
"(`BeneficiaryID`, `Provisioned`, `Deleted`, `CreatedDate`, `CreatedBy`) " +
"VALUES (?, b'0', b'0', ?, ?)";
for (int i = 0; i < batchArgs.size(); i += BATCH_SIZE) {
List<Object[]> batch = batchArgs.subList(i, Math.min(i + BATCH_SIZE, batchArgs.size()));
try {
jdbcTemplate.batchUpdate(sql, batch);
} catch (Exception e) {
logger.error("Failed to insert batch starting at index {}: {}", i, e.getMessage());
throw new RuntimeException("Batch insert failed", e);
}
}
long fin = System.currentTimeMillis() - strt;
logger.info("BengenApplication.createFile finish. time = " + fin + " ms.");
}
🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/bengen/service/GenerateBeneficiaryService.java
around lines 73 to 92, the createFile method lacks error handling and uses a
hardcoded database name in the SQL insert statement. To fix this, wrap the batch
insert logic in a try-catch block to handle and log any exceptions that occur
during database operations. Also, replace the hardcoded database name with a
configurable property fetched from configuration files or environment variables,
ensuring the SQL statement dynamically uses this configurable database name.

Comment on lines 71 to 91
protected BigInteger generateNumN(int n) {
int[] source = new int[n];
int[] target = new int[n];

for (int i = 0; i < n; i++) {
source[i] = getRandomDigit();
}

for (int i = 0, j = n - 1; i < n; i++, j--) {
int num = (j == 0) ? getRandomDigit() : getRandomDigit() % j;
target[j] = source[i];
source[i] = num;
}

StringBuilder sb = new StringBuilder(n);
for (int value : target) {
sb.append(value);
}

return new BigInteger(sb.toString());
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect shuffling algorithm that doesn't preserve all digits.

The current implementation has a logical error in the shuffling algorithm. At line 82, source[i] = num overwrites the original value without preserving it for potential future swaps. This means some digits will be lost and others duplicated, not creating a true permutation.

If the intent is to generate a random n-digit number, consider this simpler approach:

 protected BigInteger generateNumN(int n) {
-    int[] source = new int[n];
-    int[] target = new int[n];
-
-    for (int i = 0; i < n; i++) {
-        source[i] = getRandomDigit();
-    }
-
-    for (int i = 0, j = n - 1; i < n; i++, j--) {
-        int num = (j == 0) ? getRandomDigit() : getRandomDigit() % j;
-        target[j] = source[i];
-        source[i] = num;
-    }
-
-    StringBuilder sb = new StringBuilder(n);
-    for (int value : target) {
-        sb.append(value);
-    }
-
-    return new BigInteger(sb.toString());
+    StringBuilder sb = new StringBuilder(n);
+    for (int i = 0; i < n; i++) {
+        sb.append(getRandomDigit());
+    }
+    return new BigInteger(sb.toString());
 }

Or if you need a shuffled permutation of digits 0-9:

 protected BigInteger generateNumN(int n) {
-    int[] source = new int[n];
-    int[] target = new int[n];
-
-    for (int i = 0; i < n; i++) {
-        source[i] = getRandomDigit();
-    }
-
-    for (int i = 0, j = n - 1; i < n; i++, j--) {
-        int num = (j == 0) ? getRandomDigit() : getRandomDigit() % j;
-        target[j] = source[i];
-        source[i] = num;
-    }
-
-    StringBuilder sb = new StringBuilder(n);
-    for (int value : target) {
-        sb.append(value);
-    }
-
-    return new BigInteger(sb.toString());
+    List<Integer> digits = IntStream.range(0, 10).boxed().collect(Collectors.toList());
+    Collections.shuffle(digits, new SecureRandom());
+    
+    StringBuilder sb = new StringBuilder(n);
+    for (int i = 0; i < n; i++) {
+        sb.append(digits.get(i));
+    }
+    return new BigInteger(sb.toString());
 }
📝 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
protected BigInteger generateNumN(int n) {
int[] source = new int[n];
int[] target = new int[n];
for (int i = 0; i < n; i++) {
source[i] = getRandomDigit();
}
for (int i = 0, j = n - 1; i < n; i++, j--) {
int num = (j == 0) ? getRandomDigit() : getRandomDigit() % j;
target[j] = source[i];
source[i] = num;
}
StringBuilder sb = new StringBuilder(n);
for (int value : target) {
sb.append(value);
}
return new BigInteger(sb.toString());
}
protected BigInteger generateNumN(int n) {
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) {
sb.append(getRandomDigit());
}
return new BigInteger(sb.toString());
}
Suggested change
protected BigInteger generateNumN(int n) {
int[] source = new int[n];
int[] target = new int[n];
for (int i = 0; i < n; i++) {
source[i] = getRandomDigit();
}
for (int i = 0, j = n - 1; i < n; i++, j--) {
int num = (j == 0) ? getRandomDigit() : getRandomDigit() % j;
target[j] = source[i];
source[i] = num;
}
StringBuilder sb = new StringBuilder(n);
for (int value : target) {
sb.append(value);
}
return new BigInteger(sb.toString());
}
protected BigInteger generateNumN(int n) {
List<Integer> digits = IntStream.range(0, 10).boxed().collect(Collectors.toList());
Collections.shuffle(digits, new SecureRandom());
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) {
sb.append(digits.get(i));
}
return new BigInteger(sb.toString());
}
🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/bengen/utils/Generator.java between lines 71
and 91, the current shuffling logic overwrites elements in the source array
causing loss of digits and duplicates, thus not producing a valid permutation.
To fix this, replace the flawed shuffle with a proper algorithm like the
Fisher-Yates shuffle that swaps elements without overwriting, ensuring all
original digits are preserved and randomly permuted. Alternatively, if the goal
is just to generate a random n-digit number, simplify by directly generating
each digit without attempting to shuffle arrays.

Comment on lines 99 to 103
private int getRandomDigit() {
SecureRandom secureRandom = new SecureRandom();
return secureRandom.nextInt(10);

}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Performance issue: Creating SecureRandom instance on every call.

Creating a new SecureRandom instance for each random digit is inefficient. Consider using a shared instance or ThreadLocalRandom for better performance in concurrent scenarios.

+private static final SecureRandom SECURE_RANDOM = new SecureRandom();
+
 private int getRandomDigit() {
-    SecureRandom secureRandom = new SecureRandom();
-    return secureRandom.nextInt(10);
+    return SECURE_RANDOM.nextInt(10);
 }

Or for better thread safety in parallel streams:

 private int getRandomDigit() {
-    SecureRandom secureRandom = new SecureRandom();
-    return secureRandom.nextInt(10);
+    return ThreadLocalRandom.current().nextInt(10);
 }
📝 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
private int getRandomDigit() {
SecureRandom secureRandom = new SecureRandom();
return secureRandom.nextInt(10);
}
// Reuse a single SecureRandom instance instead of creating one per call
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private int getRandomDigit() {
return SECURE_RANDOM.nextInt(10);
}
🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/bengen/utils/Generator.java around lines 99 to
103, the method getRandomDigit creates a new SecureRandom instance on every
call, which is inefficient. To fix this, create a single shared SecureRandom
instance as a static final field in the class and reuse it in the method, or
alternatively use ThreadLocalRandom.current().nextInt(10) for better performance
and thread safety in concurrent scenarios.

Comment on lines 105 to 114
private int getRandomInRange(int min, int max) {
SecureRandom sr = new SecureRandom();
if (min > max) {
throw new IllegalArgumentException("min must be <= max");
}
if (max == Integer.MAX_VALUE) {
return sr.nextInt(max - min) + min;
}
return sr.nextInt(min, max + 1); // safe here
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect MAX_VALUE handling and SecureRandom instantiation.

Two issues:

  1. Line 111: When max == Integer.MAX_VALUE, the result excludes max from the range
  2. Creating new SecureRandom instance is inefficient
+private static final SecureRandom SECURE_RANDOM = new SecureRandom();
+
 private int getRandomInRange(int min, int max) {
-    SecureRandom sr = new SecureRandom();
     if (min > max) {
         throw new IllegalArgumentException("min must be <= max");
     }
     if (max == Integer.MAX_VALUE) {
-        return sr.nextInt(max - min) + min;
+        // Handle MAX_VALUE case - use long to avoid overflow
+        return SECURE_RANDOM.nextInt(max - min + 1) + min;
     }
-    return sr.nextInt(min, max + 1); // safe here
+    return SECURE_RANDOM.nextInt(min, max + 1);
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/iemr/common/bengen/utils/Generator.java lines 105 to 114,
fix the getRandomInRange method by reusing a single SecureRandom instance
instead of creating a new one each call to improve efficiency. Also, correct the
logic for the case when max equals Integer.MAX_VALUE to ensure the max value is
included in the random range by adjusting the bounds accordingly.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 7, 2025

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